var Jje=Object.defineProperty;var kK=t=>{throw TypeError(t)};var eSe=(t,e,r)=>e in t?Jje(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var um=(t,e,r)=>eSe(t,typeof e!="symbol"?e+"":e,r),sF=(t,e,r)=>e.has(t)||kK("Cannot "+r);var Ot=(t,e,r)=>(sF(t,e,"read from private field"),r?r.call(t):e.get(t)),Es=(t,e,r)=>e.has(t)?kK("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),On=(t,e,r,n)=>(sF(t,e,"write to private field"),n?n.call(t,r):e.set(t,r),r),Ei=(t,e,r)=>(sF(t,e,"access private method"),r);var KA=(t,e,r,n)=>({set _(i){On(t,e,i,r)},get _(){return Ot(t,e,n)}});function dse(t,e){for(var r=0;rn[i]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))n(i);new MutationObserver(i=>{for(const o of i)if(o.type==="childList")for(const c of o.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&n(c)}).observe(document,{childList:!0,subtree:!0});function r(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 n(i){if(i.ep)return;i.ep=!0;const o=r(i);fetch(i.href,o)}})();var IC=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function sa(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function hse(t){if(t.__esModule)return t;var e=t.default;if(typeof e=="function"){var r=function n(){return this instanceof n?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};r.prototype=e.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(t).forEach(function(n){var i=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(r,n,i.get?i:{enumerable:!0,get:function(){return t[n]}})}),r}var fse={exports:{}},OR={},pse={exports:{}},qi={};/** * @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 oT=Symbol.for("react.element"),tSe=Symbol.for("react.portal"),rSe=Symbol.for("react.fragment"),nSe=Symbol.for("react.strict_mode"),sSe=Symbol.for("react.profiler"),iSe=Symbol.for("react.provider"),aSe=Symbol.for("react.context"),oSe=Symbol.for("react.forward_ref"),lSe=Symbol.for("react.suspense"),cSe=Symbol.for("react.memo"),uSe=Symbol.for("react.lazy"),TK=Symbol.iterator;function dSe(t){return t===null||typeof t!="object"?null:(t=TK&&t[TK]||t["@@iterator"],typeof t=="function"?t:null)}var mse={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},gse=Object.assign,yse={};function Nj(t,e,r){this.props=t,this.context=e,this.refs=yse,this.updater=r||mse}Nj.prototype.isReactComponent={};Nj.prototype.setState=function(t,e){if(typeof t!="object"&&typeof t!="function"&&t!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,t,e,"setState")};Nj.prototype.forceUpdate=function(t){this.updater.enqueueForceUpdate(this,t,"forceUpdate")};function xse(){}xse.prototype=Nj.prototype;function HV(t,e,r){this.props=t,this.context=e,this.refs=yse,this.updater=r||mse}var WV=HV.prototype=new xse;WV.constructor=HV;gse(WV,Nj.prototype);WV.isPureReactComponent=!0;var EK=Array.isArray,vse=Object.prototype.hasOwnProperty,GV={current:null},_se={key:!0,ref:!0,__self:!0,__source:!0};function bse(t,e,r){var n,i={},o=null,c=null;if(e!=null)for(n in e.ref!==void 0&&(c=e.ref),e.key!==void 0&&(o=""+e.key),e)vse.call(e,n)&&!_se.hasOwnProperty(n)&&(i[n]=e[n]);var a=arguments.length-2;if(a===1)i.children=r;else if(1>>1,_e=Se[bt];if(0>>1;bti(nt,et))Qt<_e&&0>i(gt,nt)?(Se[bt]=gt,Se[Qt]=et,bt=Qt):(Se[bt]=nt,Se[pt]=et,bt=pt);else if(Qt<_e&&0>i(gt,et))Se[bt]=gt,Se[Qt]=et,bt=Qt;else break e}}return je}function i(Se,je){var et=Se.sortIndex-je.sortIndex;return et!==0?et:Se.id-je.id}if(typeof performance=="object"&&typeof performance.now=="function"){var o=performance;t.unstable_now=function(){return o.now()}}else{var c=Date,a=c.now();t.unstable_now=function(){return c.now()-a}}var m=[],g=[],_=1,j=null,N=3,C=!1,P=!1,A=!1,I=typeof setTimeout=="function"?setTimeout:null,O=typeof clearTimeout=="function"?clearTimeout:null,R=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function z(Se){for(var je=r(g);je!==null;){if(je.callback===null)n(g);else if(je.startTime<=Se)n(g),je.sortIndex=je.expirationTime,e(m,je);else break;je=r(g)}}function W(Se){if(A=!1,z(Se),!P)if(r(m)!==null)P=!0,ke(V);else{var je=r(g);je!==null&&Ce(W,je.startTime-Se)}}function V(Se,je){P=!1,A&&(A=!1,O(te),te=-1),C=!0;var et=N;try{for(z(je),j=r(m);j!==null&&(!(j.expirationTime>je)||Se&&!he());){var bt=j.callback;if(typeof bt=="function"){j.callback=null,N=j.priorityLevel;var _e=bt(j.expirationTime<=je);je=t.unstable_now(),typeof _e=="function"?j.callback=_e:j===r(m)&&n(m),z(je)}else n(m);j=r(m)}if(j!==null)var Ye=!0;else{var pt=r(g);pt!==null&&Ce(W,pt.startTime-je),Ye=!1}return Ye}finally{j=null,N=et,C=!1}}var K=!1,Q=null,te=-1,X=5,ie=-1;function he(){return!(t.unstable_now()-ieSe||125bt?(Se.sortIndex=et,e(g,Se),r(m)===null&&Se===r(g)&&(A?(O(te),te=-1):A=!0,Ce(W,et-bt))):(Se.sortIndex=_e,e(m,Se),P||C||(P=!0,ke(V))),Se},t.unstable_shouldYield=he,t.unstable_wrapCallback=function(Se){var je=N;return function(){var et=N;N=je;try{return Se.apply(this,arguments)}finally{N=et}}}})(Cse);Nse.exports=Cse;var wSe=Nse.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 jSe=D,bd=wSe;function sn(t){for(var e="https://reactjs.org/docs/error-decoder.html?invariant="+t,r=1;r"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),EB=Object.prototype.hasOwnProperty,SSe=/^[: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]*$/,PK={},IK={};function NSe(t){return EB.call(IK,t)?!0:EB.call(PK,t)?!1:SSe.test(t)?IK[t]=!0:(PK[t]=!0,!1)}function CSe(t,e,r,n){if(r!==null&&r.type===0)return!1;switch(typeof e){case"function":case"symbol":return!0;case"boolean":return n?!1:r!==null?!r.acceptsBooleans:(t=t.toLowerCase().slice(0,5),t!=="data-"&&t!=="aria-");default:return!1}}function kSe(t,e,r,n){if(e===null||typeof e>"u"||CSe(t,e,r,n))return!0;if(n)return!1;if(r!==null)switch(r.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 pu(t,e,r,n,i,o,c){this.acceptsBooleans=e===2||e===3||e===4,this.attributeName=n,this.attributeNamespace=i,this.mustUseProperty=r,this.propertyName=t,this.type=e,this.sanitizeURL=o,this.removeEmptyString=c}var _c={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(t){_c[t]=new pu(t,0,!1,t,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(t){var e=t[0];_c[e]=new pu(e,1,!1,t[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(t){_c[t]=new pu(t,2,!1,t.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(t){_c[t]=new pu(t,2,!1,t,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(t){_c[t]=new pu(t,3,!1,t.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(t){_c[t]=new pu(t,3,!0,t,null,!1,!1)});["capture","download"].forEach(function(t){_c[t]=new pu(t,4,!1,t,null,!1,!1)});["cols","rows","size","span"].forEach(function(t){_c[t]=new pu(t,6,!1,t,null,!1,!1)});["rowSpan","start"].forEach(function(t){_c[t]=new pu(t,5,!1,t.toLowerCase(),null,!1,!1)});var YV=/[\-:]([a-z])/g;function XV(t){return t[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(t){var e=t.replace(YV,XV);_c[e]=new pu(e,1,!1,t,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(t){var e=t.replace(YV,XV);_c[e]=new pu(e,1,!1,t,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(t){var e=t.replace(YV,XV);_c[e]=new pu(e,1,!1,t,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(t){_c[t]=new pu(t,1,!1,t.toLowerCase(),null,!1,!1)});_c.xlinkHref=new pu("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(t){_c[t]=new pu(t,1,!1,t.toLowerCase(),null,!0,!0)});function QV(t,e,r,n){var i=_c.hasOwnProperty(e)?_c[e]:null;(i!==null?i.type!==0:n||!(2a||i[c]!==o[a]){var m=` `+i[c].replace(" at new "," at ");return t.displayName&&m.includes("")&&(m=m.replace("",t.displayName)),m}while(1<=c&&0<=a);break}}}finally{oF=!1,Error.prepareStackTrace=r}return(t=t?t.displayName||t.name:"")?MC(t):""}function TSe(t){switch(t.tag){case 5:return MC(t.type);case 16:return MC("Lazy");case 13:return MC("Suspense");case 19:return MC("SuspenseList");case 0:case 2:case 15:return t=lF(t.type,!1),t;case 11:return t=lF(t.type.render,!1),t;case 1:return t=lF(t.type,!0),t;default:return""}}function MB(t){if(t==null)return null;if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t;switch(t){case Tw:return"Fragment";case kw:return"Portal";case AB:return"Profiler";case JV:return"StrictMode";case PB:return"Suspense";case IB:return"SuspenseList"}if(typeof t=="object")switch(t.$$typeof){case Ese:return(t.displayName||"Context")+".Consumer";case Tse:return(t._context.displayName||"Context")+".Provider";case e6:var e=t.render;return t=t.displayName,t||(t=e.displayName||e.name||"",t=t!==""?"ForwardRef("+t+")":"ForwardRef"),t;case t6:return e=t.displayName||null,e!==null?e:MB(t.type)||"Memo";case ry:e=t._payload,t=t._init;try{return MB(t(e))}catch{}}return null}function ESe(t){var e=t.type;switch(t.tag){case 24:return"Cache";case 9:return(e.displayName||"Context")+".Consumer";case 10:return(e._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return t=e.render,t=t.displayName||t.name||"",e.displayName||(t!==""?"ForwardRef("+t+")":"ForwardRef");case 7:return"Fragment";case 5:return e;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return MB(e);case 8:return e===JV?"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 tx(t){switch(typeof t){case"boolean":case"number":case"string":case"undefined":return t;case"object":return t;default:return""}}function Pse(t){var e=t.type;return(t=t.nodeName)&&t.toLowerCase()==="input"&&(e==="checkbox"||e==="radio")}function ASe(t){var e=Pse(t)?"checked":"value",r=Object.getOwnPropertyDescriptor(t.constructor.prototype,e),n=""+t[e];if(!t.hasOwnProperty(e)&&typeof r<"u"&&typeof r.get=="function"&&typeof r.set=="function"){var i=r.get,o=r.set;return Object.defineProperty(t,e,{configurable:!0,get:function(){return i.call(this)},set:function(c){n=""+c,o.call(this,c)}}),Object.defineProperty(t,e,{enumerable:r.enumerable}),{getValue:function(){return n},setValue:function(c){n=""+c},stopTracking:function(){t._valueTracker=null,delete t[e]}}}}function XA(t){t._valueTracker||(t._valueTracker=ASe(t))}function Ise(t){if(!t)return!1;var e=t._valueTracker;if(!e)return!0;var r=e.getValue(),n="";return t&&(n=Pse(t)?t.checked?"true":"false":t.value),t=n,t!==r?(e.setValue(t),!0):!1}function BI(t){if(t=t||(typeof document<"u"?document:void 0),typeof t>"u")return null;try{return t.activeElement||t.body}catch{return t.body}}function OB(t,e){var r=e.checked;return Co({},e,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:r??t._wrapperState.initialChecked})}function OK(t,e){var r=e.defaultValue==null?"":e.defaultValue,n=e.checked!=null?e.checked:e.defaultChecked;r=tx(e.value!=null?e.value:r),t._wrapperState={initialChecked:n,initialValue:r,controlled:e.type==="checkbox"||e.type==="radio"?e.checked!=null:e.value!=null}}function Mse(t,e){e=e.checked,e!=null&&QV(t,"checked",e,!1)}function RB(t,e){Mse(t,e);var r=tx(e.value),n=e.type;if(r!=null)n==="number"?(r===0&&t.value===""||t.value!=r)&&(t.value=""+r):t.value!==""+r&&(t.value=""+r);else if(n==="submit"||n==="reset"){t.removeAttribute("value");return}e.hasOwnProperty("value")?DB(t,e.type,r):e.hasOwnProperty("defaultValue")&&DB(t,e.type,tx(e.defaultValue)),e.checked==null&&e.defaultChecked!=null&&(t.defaultChecked=!!e.defaultChecked)}function RK(t,e,r){if(e.hasOwnProperty("value")||e.hasOwnProperty("defaultValue")){var n=e.type;if(!(n!=="submit"&&n!=="reset"||e.value!==void 0&&e.value!==null))return;e=""+t._wrapperState.initialValue,r||e===t.value||(t.value=e),t.defaultValue=e}r=t.name,r!==""&&(t.name=""),t.defaultChecked=!!t._wrapperState.initialChecked,r!==""&&(t.name=r)}function DB(t,e,r){(e!=="number"||BI(t.ownerDocument)!==t)&&(r==null?t.defaultValue=""+t._wrapperState.initialValue:t.defaultValue!==""+r&&(t.defaultValue=""+r))}var OC=Array.isArray;function Ww(t,e,r,n){if(t=t.options,e){e={};for(var i=0;i"+e.valueOf().toString()+"",e=QA.firstChild;t.firstChild;)t.removeChild(t.firstChild);for(;e.firstChild;)t.appendChild(e.firstChild)}});function E2(t,e){if(e){var r=t.firstChild;if(r&&r===t.lastChild&&r.nodeType===3){r.nodeValue=e;return}}t.textContent=e}var GC={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},PSe=["Webkit","ms","Moz","O"];Object.keys(GC).forEach(function(t){PSe.forEach(function(e){e=e+t.charAt(0).toUpperCase()+t.substring(1),GC[e]=GC[t]})});function Lse(t,e,r){return e==null||typeof e=="boolean"||e===""?"":r||typeof e!="number"||e===0||GC.hasOwnProperty(t)&&GC[t]?(""+e).trim():e+"px"}function Fse(t,e){t=t.style;for(var r in e)if(e.hasOwnProperty(r)){var n=r.indexOf("--")===0,i=Lse(r,e[r],n);r==="float"&&(r="cssFloat"),n?t.setProperty(r,i):t[r]=i}}var ISe=Co({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 zB(t,e){if(e){if(ISe[t]&&(e.children!=null||e.dangerouslySetInnerHTML!=null))throw Error(sn(137,t));if(e.dangerouslySetInnerHTML!=null){if(e.children!=null)throw Error(sn(60));if(typeof e.dangerouslySetInnerHTML!="object"||!("__html"in e.dangerouslySetInnerHTML))throw Error(sn(61))}if(e.style!=null&&typeof e.style!="object")throw Error(sn(62))}}function BB(t,e){if(t.indexOf("-")===-1)return typeof e.is=="string";switch(t){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var $B=null;function r6(t){return t=t.target||t.srcElement||window,t.correspondingUseElement&&(t=t.correspondingUseElement),t.nodeType===3?t.parentNode:t}var UB=null,Gw=null,Kw=null;function FK(t){if(t=uT(t)){if(typeof UB!="function")throw Error(sn(280));var e=t.stateNode;e&&(e=zR(e),UB(t.stateNode,t.type,e))}}function zse(t){Gw?Kw?Kw.push(t):Kw=[t]:Gw=t}function Bse(){if(Gw){var t=Gw,e=Kw;if(Kw=Gw=null,FK(t),e)for(t=0;t>>=0,t===0?32:31-(VSe(t)/qSe|0)|0}var JA=64,eP=4194304;function RC(t){switch(t&-t){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return t&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return t}}function qI(t,e){var r=t.pendingLanes;if(r===0)return 0;var n=0,i=t.suspendedLanes,o=t.pingedLanes,c=r&268435455;if(c!==0){var a=c&~i;a!==0?n=RC(a):(o&=c,o!==0&&(n=RC(o)))}else c=r&~i,c!==0?n=RC(c):o!==0&&(n=RC(o));if(n===0)return 0;if(e!==0&&e!==n&&!(e&i)&&(i=n&-n,o=e&-e,i>=o||i===16&&(o&4194240)!==0))return e;if(n&4&&(n|=r&16),e=t.entangledLanes,e!==0)for(t=t.entanglements,e&=n;0r;r++)e.push(t);return e}function lT(t,e,r){t.pendingLanes|=e,e!==536870912&&(t.suspendedLanes=0,t.pingedLanes=0),t=t.eventTimes,e=31-vf(e),t[e]=r}function KSe(t,e){var r=t.pendingLanes&~e;t.pendingLanes=e,t.suspendedLanes=0,t.pingedLanes=0,t.expiredLanes&=e,t.mutableReadLanes&=e,t.entangledLanes&=e,e=t.entanglements;var n=t.eventTimes;for(t=t.expirationTimes;0=ZC),GK=" ",KK=!1;function aie(t,e){switch(t){case"keyup":return wNe.indexOf(e.keyCode)!==-1;case"keydown":return e.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function oie(t){return t=t.detail,typeof t=="object"&&"data"in t?t.data:null}var Ew=!1;function SNe(t,e){switch(t){case"compositionend":return oie(e);case"keypress":return e.which!==32?null:(KK=!0,GK);case"textInput":return t=e.data,t===GK&&KK?null:t;default:return null}}function NNe(t,e){if(Ew)return t==="compositionend"||!u6&&aie(t,e)?(t=sie(),hI=o6=Ty=null,Ew=!1,t):null;switch(t){case"paste":return null;case"keypress":if(!(e.ctrlKey||e.altKey||e.metaKey)||e.ctrlKey&&e.altKey){if(e.char&&1=e)return{node:r,offset:e-t};t=n}e:{for(;r;){if(r.nextSibling){r=r.nextSibling;break e}r=r.parentNode}r=void 0}r=QK(r)}}function die(t,e){return t&&e?t===e?!0:t&&t.nodeType===3?!1:e&&e.nodeType===3?die(t,e.parentNode):"contains"in t?t.contains(e):t.compareDocumentPosition?!!(t.compareDocumentPosition(e)&16):!1:!1}function hie(){for(var t=window,e=BI();e instanceof t.HTMLIFrameElement;){try{var r=typeof e.contentWindow.location.href=="string"}catch{r=!1}if(r)t=e.contentWindow;else break;e=BI(t.document)}return e}function d6(t){var e=t&&t.nodeName&&t.nodeName.toLowerCase();return e&&(e==="input"&&(t.type==="text"||t.type==="search"||t.type==="tel"||t.type==="url"||t.type==="password")||e==="textarea"||t.contentEditable==="true")}function ONe(t){var e=hie(),r=t.focusedElem,n=t.selectionRange;if(e!==r&&r&&r.ownerDocument&&die(r.ownerDocument.documentElement,r)){if(n!==null&&d6(r)){if(e=n.start,t=n.end,t===void 0&&(t=e),"selectionStart"in r)r.selectionStart=e,r.selectionEnd=Math.min(t,r.value.length);else if(t=(e=r.ownerDocument||document)&&e.defaultView||window,t.getSelection){t=t.getSelection();var i=r.textContent.length,o=Math.min(n.start,i);n=n.end===void 0?o:Math.min(n.end,i),!t.extend&&o>n&&(i=n,n=o,o=i),i=JK(r,o);var c=JK(r,n);i&&c&&(t.rangeCount!==1||t.anchorNode!==i.node||t.anchorOffset!==i.offset||t.focusNode!==c.node||t.focusOffset!==c.offset)&&(e=e.createRange(),e.setStart(i.node,i.offset),t.removeAllRanges(),o>n?(t.addRange(e),t.extend(c.node,c.offset)):(e.setEnd(c.node,c.offset),t.addRange(e)))}}for(e=[],t=r;t=t.parentNode;)t.nodeType===1&&e.push({element:t,left:t.scrollLeft,top:t.scrollTop});for(typeof r.focus=="function"&&r.focus(),r=0;r=document.documentMode,Aw=null,KB=null,XC=null,ZB=!1;function eZ(t,e,r){var n=r.window===r?r.document:r.nodeType===9?r:r.ownerDocument;ZB||Aw==null||Aw!==BI(n)||(n=Aw,"selectionStart"in n&&d6(n)?n={start:n.selectionStart,end:n.selectionEnd}:(n=(n.ownerDocument&&n.ownerDocument.defaultView||window).getSelection(),n={anchorNode:n.anchorNode,anchorOffset:n.anchorOffset,focusNode:n.focusNode,focusOffset:n.focusOffset}),XC&&R2(XC,n)||(XC=n,n=GI(KB,"onSelect"),0Mw||(t.current=t5[Mw],t5[Mw]=null,Mw--)}function Wa(t,e){Mw++,t5[Mw]=t.current,t.current=e}var rx={},Oc=px(rx),Du=px(!1),S_=rx;function C1(t,e){var r=t.type.contextTypes;if(!r)return rx;var n=t.stateNode;if(n&&n.__reactInternalMemoizedUnmaskedChildContext===e)return n.__reactInternalMemoizedMaskedChildContext;var i={},o;for(o in r)i[o]=e[o];return n&&(t=t.stateNode,t.__reactInternalMemoizedUnmaskedChildContext=e,t.__reactInternalMemoizedMaskedChildContext=i),i}function Lu(t){return t=t.childContextTypes,t!=null}function ZI(){so(Du),so(Oc)}function oZ(t,e,r){if(Oc.current!==rx)throw Error(sn(168));Wa(Oc,e),Wa(Du,r)}function bie(t,e,r){var n=t.stateNode;if(e=e.childContextTypes,typeof n.getChildContext!="function")return r;n=n.getChildContext();for(var i in n)if(!(i in e))throw Error(sn(108,ESe(t)||"Unknown",i));return Co({},r,n)}function YI(t){return t=(t=t.stateNode)&&t.__reactInternalMemoizedMergedChildContext||rx,S_=Oc.current,Wa(Oc,t),Wa(Du,Du.current),!0}function lZ(t,e,r){var n=t.stateNode;if(!n)throw Error(sn(169));r?(t=bie(t,e,S_),n.__reactInternalMemoizedMergedChildContext=t,so(Du),so(Oc),Wa(Oc,t)):so(Du),Wa(Du,r)}var Sm=null,BR=!1,wF=!1;function wie(t){Sm===null?Sm=[t]:Sm.push(t)}function WNe(t){BR=!0,wie(t)}function mx(){if(!wF&&Sm!==null){wF=!0;var t=0,e=Ca;try{var r=Sm;for(Ca=1;t>=c,i-=c,Tm=1<<32-vf(e)+i|r<te?(X=Q,Q=null):X=Q.sibling;var ie=N(O,Q,z[te],W);if(ie===null){Q===null&&(Q=X);break}t&&Q&&ie.alternate===null&&e(O,Q),R=o(ie,R,te),K===null?V=ie:K.sibling=ie,K=ie,Q=X}if(te===z.length)return r(O,Q),po&&Iv(O,te),V;if(Q===null){for(;tete?(X=Q,Q=null):X=Q.sibling;var he=N(O,Q,ie.value,W);if(he===null){Q===null&&(Q=X);break}t&&Q&&he.alternate===null&&e(O,Q),R=o(he,R,te),K===null?V=he:K.sibling=he,K=he,Q=X}if(ie.done)return r(O,Q),po&&Iv(O,te),V;if(Q===null){for(;!ie.done;te++,ie=z.next())ie=j(O,ie.value,W),ie!==null&&(R=o(ie,R,te),K===null?V=ie:K.sibling=ie,K=ie);return po&&Iv(O,te),V}for(Q=n(O,Q);!ie.done;te++,ie=z.next())ie=C(Q,O,te,ie.value,W),ie!==null&&(t&&ie.alternate!==null&&Q.delete(ie.key===null?te:ie.key),R=o(ie,R,te),K===null?V=ie:K.sibling=ie,K=ie);return t&&Q.forEach(function(xe){return e(O,xe)}),po&&Iv(O,te),V}function I(O,R,z,W){if(typeof z=="object"&&z!==null&&z.type===Tw&&z.key===null&&(z=z.props.children),typeof z=="object"&&z!==null){switch(z.$$typeof){case YA:e:{for(var V=z.key,K=R;K!==null;){if(K.key===V){if(V=z.type,V===Tw){if(K.tag===7){r(O,K.sibling),R=i(K,z.props.children),R.return=O,O=R;break e}}else if(K.elementType===V||typeof V=="object"&&V!==null&&V.$$typeof===ry&&dZ(V)===K.type){r(O,K.sibling),R=i(K,z.props),R.ref=aC(O,K,z),R.return=O,O=R;break e}r(O,K);break}else e(O,K);K=K.sibling}z.type===Tw?(R=m_(z.props.children,O.mode,W,z.key),R.return=O,O=R):(W=_I(z.type,z.key,z.props,null,O.mode,W),W.ref=aC(O,R,z),W.return=O,O=W)}return c(O);case kw:e:{for(K=z.key;R!==null;){if(R.key===K)if(R.tag===4&&R.stateNode.containerInfo===z.containerInfo&&R.stateNode.implementation===z.implementation){r(O,R.sibling),R=i(R,z.children||[]),R.return=O,O=R;break e}else{r(O,R);break}else e(O,R);R=R.sibling}R=AF(z,O.mode,W),R.return=O,O=R}return c(O);case ry:return K=z._init,I(O,R,K(z._payload),W)}if(OC(z))return P(O,R,z,W);if(tC(z))return A(O,R,z,W);oP(O,z)}return typeof z=="string"&&z!==""||typeof z=="number"?(z=""+z,R!==null&&R.tag===6?(r(O,R.sibling),R=i(R,z),R.return=O,O=R):(r(O,R),R=EF(z,O.mode,W),R.return=O,O=R),c(O)):r(O,R)}return I}var T1=Cie(!0),kie=Cie(!1),JI=px(null),eM=null,Dw=null,m6=null;function g6(){m6=Dw=eM=null}function y6(t){var e=JI.current;so(JI),t._currentValue=e}function s5(t,e,r){for(;t!==null;){var n=t.alternate;if((t.childLanes&e)!==e?(t.childLanes|=e,n!==null&&(n.childLanes|=e)):n!==null&&(n.childLanes&e)!==e&&(n.childLanes|=e),t===r)break;t=t.return}}function Yw(t,e){eM=t,m6=Dw=null,t=t.dependencies,t!==null&&t.firstContext!==null&&(t.lanes&e&&(Ou=!0),t.firstContext=null)}function hh(t){var e=t._currentValue;if(m6!==t)if(t={context:t,memoizedValue:e,next:null},Dw===null){if(eM===null)throw Error(sn(308));Dw=t,eM.dependencies={lanes:0,firstContext:t}}else Dw=Dw.next=t;return e}var Hv=null;function x6(t){Hv===null?Hv=[t]:Hv.push(t)}function Tie(t,e,r,n){var i=e.interleaved;return i===null?(r.next=r,x6(e)):(r.next=i.next,i.next=r),e.interleaved=r,Um(t,n)}function Um(t,e){t.lanes|=e;var r=t.alternate;for(r!==null&&(r.lanes|=e),r=t,t=t.return;t!==null;)t.childLanes|=e,r=t.alternate,r!==null&&(r.childLanes|=e),r=t,t=t.return;return r.tag===3?r.stateNode:null}var ny=!1;function v6(t){t.updateQueue={baseState:t.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Eie(t,e){t=t.updateQueue,e.updateQueue===t&&(e.updateQueue={baseState:t.baseState,firstBaseUpdate:t.firstBaseUpdate,lastBaseUpdate:t.lastBaseUpdate,shared:t.shared,effects:t.effects})}function Om(t,e){return{eventTime:t,lane:e,tag:0,payload:null,callback:null,next:null}}function $y(t,e,r){var n=t.updateQueue;if(n===null)return null;if(n=n.shared,aa&2){var i=n.pending;return i===null?e.next=e:(e.next=i.next,i.next=e),n.pending=e,Um(t,r)}return i=n.interleaved,i===null?(e.next=e,x6(n)):(e.next=i.next,i.next=e),n.interleaved=e,Um(t,r)}function pI(t,e,r){if(e=e.updateQueue,e!==null&&(e=e.shared,(r&4194240)!==0)){var n=e.lanes;n&=t.pendingLanes,r|=n,e.lanes=r,s6(t,r)}}function hZ(t,e){var r=t.updateQueue,n=t.alternate;if(n!==null&&(n=n.updateQueue,r===n)){var i=null,o=null;if(r=r.firstBaseUpdate,r!==null){do{var c={eventTime:r.eventTime,lane:r.lane,tag:r.tag,payload:r.payload,callback:r.callback,next:null};o===null?i=o=c:o=o.next=c,r=r.next}while(r!==null);o===null?i=o=e:o=o.next=e}else i=o=e;r={baseState:n.baseState,firstBaseUpdate:i,lastBaseUpdate:o,shared:n.shared,effects:n.effects},t.updateQueue=r;return}t=r.lastBaseUpdate,t===null?r.firstBaseUpdate=e:t.next=e,r.lastBaseUpdate=e}function tM(t,e,r,n){var i=t.updateQueue;ny=!1;var o=i.firstBaseUpdate,c=i.lastBaseUpdate,a=i.shared.pending;if(a!==null){i.shared.pending=null;var m=a,g=m.next;m.next=null,c===null?o=g:c.next=g,c=m;var _=t.alternate;_!==null&&(_=_.updateQueue,a=_.lastBaseUpdate,a!==c&&(a===null?_.firstBaseUpdate=g:a.next=g,_.lastBaseUpdate=m))}if(o!==null){var j=i.baseState;c=0,_=g=m=null,a=o;do{var N=a.lane,C=a.eventTime;if((n&N)===N){_!==null&&(_=_.next={eventTime:C,lane:0,tag:a.tag,payload:a.payload,callback:a.callback,next:null});e:{var P=t,A=a;switch(N=e,C=r,A.tag){case 1:if(P=A.payload,typeof P=="function"){j=P.call(C,j,N);break e}j=P;break e;case 3:P.flags=P.flags&-65537|128;case 0:if(P=A.payload,N=typeof P=="function"?P.call(C,j,N):P,N==null)break e;j=Co({},j,N);break e;case 2:ny=!0}}a.callback!==null&&a.lane!==0&&(t.flags|=64,N=i.effects,N===null?i.effects=[a]:N.push(a))}else C={eventTime:C,lane:N,tag:a.tag,payload:a.payload,callback:a.callback,next:null},_===null?(g=_=C,m=j):_=_.next=C,c|=N;if(a=a.next,a===null){if(a=i.shared.pending,a===null)break;N=a,a=N.next,N.next=null,i.lastBaseUpdate=N,i.shared.pending=null}}while(!0);if(_===null&&(m=j),i.baseState=m,i.firstBaseUpdate=g,i.lastBaseUpdate=_,e=i.shared.interleaved,e!==null){i=e;do c|=i.lane,i=i.next;while(i!==e)}else o===null&&(i.shared.lanes=0);k_|=c,t.lanes=c,t.memoizedState=j}}function fZ(t,e,r){if(t=e.effects,e.effects=null,t!==null)for(e=0;er?r:4,t(!0);var n=SF.transition;SF.transition={};try{t(!1),e()}finally{Ca=r,SF.transition=n}}function Wie(){return fh().memoizedState}function YNe(t,e,r){var n=Vy(t);if(r={lane:n,action:r,hasEagerState:!1,eagerState:null,next:null},Gie(t))Kie(e,r);else if(r=Tie(t,e,r,n),r!==null){var i=au();_f(r,t,n,i),Zie(r,e,n)}}function XNe(t,e,r){var n=Vy(t),i={lane:n,action:r,hasEagerState:!1,eagerState:null,next:null};if(Gie(t))Kie(e,i);else{var o=t.alternate;if(t.lanes===0&&(o===null||o.lanes===0)&&(o=e.lastRenderedReducer,o!==null))try{var c=e.lastRenderedState,a=o(c,r);if(i.hasEagerState=!0,i.eagerState=a,jf(a,c)){var m=e.interleaved;m===null?(i.next=i,x6(e)):(i.next=m.next,m.next=i),e.interleaved=i;return}}catch{}finally{}r=Tie(t,e,i,n),r!==null&&(i=au(),_f(r,t,n,i),Zie(r,e,n))}}function Gie(t){var e=t.alternate;return t===So||e!==null&&e===So}function Kie(t,e){QC=nM=!0;var r=t.pending;r===null?e.next=e:(e.next=r.next,r.next=e),t.pending=e}function Zie(t,e,r){if(r&4194240){var n=e.lanes;n&=t.pendingLanes,r|=n,e.lanes=r,s6(t,r)}}var sM={readContext:hh,useCallback:Cc,useContext:Cc,useEffect:Cc,useImperativeHandle:Cc,useInsertionEffect:Cc,useLayoutEffect:Cc,useMemo:Cc,useReducer:Cc,useRef:Cc,useState:Cc,useDebugValue:Cc,useDeferredValue:Cc,useTransition:Cc,useMutableSource:Cc,useSyncExternalStore:Cc,useId:Cc,unstable_isNewReconciler:!1},QNe={readContext:hh,useCallback:function(t,e){return tp().memoizedState=[t,e===void 0?null:e],t},useContext:hh,useEffect:mZ,useImperativeHandle:function(t,e,r){return r=r!=null?r.concat([t]):null,gI(4194308,4,$ie.bind(null,e,t),r)},useLayoutEffect:function(t,e){return gI(4194308,4,t,e)},useInsertionEffect:function(t,e){return gI(4,2,t,e)},useMemo:function(t,e){var r=tp();return e=e===void 0?null:e,t=t(),r.memoizedState=[t,e],t},useReducer:function(t,e,r){var n=tp();return e=r!==void 0?r(e):e,n.memoizedState=n.baseState=e,t={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:t,lastRenderedState:e},n.queue=t,t=t.dispatch=YNe.bind(null,So,t),[n.memoizedState,t]},useRef:function(t){var e=tp();return t={current:t},e.memoizedState=t},useState:pZ,useDebugValue:k6,useDeferredValue:function(t){return tp().memoizedState=t},useTransition:function(){var t=pZ(!1),e=t[0];return t=ZNe.bind(null,t[1]),tp().memoizedState=t,[e,t]},useMutableSource:function(){},useSyncExternalStore:function(t,e,r){var n=So,i=tp();if(po){if(r===void 0)throw Error(sn(407));r=r()}else{if(r=e(),Gl===null)throw Error(sn(349));C_&30||Mie(n,e,r)}i.memoizedState=r;var o={value:r,getSnapshot:e};return i.queue=o,mZ(Rie.bind(null,n,o,t),[t]),n.flags|=2048,V2(9,Oie.bind(null,n,o,r,e),void 0,null),r},useId:function(){var t=tp(),e=Gl.identifierPrefix;if(po){var r=Em,n=Tm;r=(n&~(1<<32-vf(n)-1)).toString(32)+r,e=":"+e+"R"+r,r=$2++,0<\/script>",t=t.removeChild(t.firstChild)):typeof n.is=="string"?t=c.createElement(r,{is:n.is}):(t=c.createElement(r),r==="select"&&(c=t,n.multiple?c.multiple=!0:n.size&&(c.size=n.size))):t=c.createElementNS(t,r),t[cp]=e,t[F2]=n,iae(t,e,!1,!1),e.stateNode=t;e:{switch(c=BB(r,n),r){case"dialog":eo("cancel",t),eo("close",t),i=n;break;case"iframe":case"object":case"embed":eo("load",t),i=n;break;case"video":case"audio":for(i=0;iP1&&(e.flags|=128,n=!0,oC(o,!1),e.lanes=4194304)}else{if(!n)if(t=rM(c),t!==null){if(e.flags|=128,n=!0,r=t.updateQueue,r!==null&&(e.updateQueue=r,e.flags|=4),oC(o,!0),o.tail===null&&o.tailMode==="hidden"&&!c.alternate&&!po)return kc(e),null}else 2*Ho()-o.renderingStartTime>P1&&r!==1073741824&&(e.flags|=128,n=!0,oC(o,!1),e.lanes=4194304);o.isBackwards?(c.sibling=e.child,e.child=c):(r=o.last,r!==null?r.sibling=c:e.child=c,o.last=c)}return o.tail!==null?(e=o.tail,o.rendering=e,o.tail=e.sibling,o.renderingStartTime=Ho(),e.sibling=null,r=jo.current,Wa(jo,n?r&1|2:r&1),e):(kc(e),null);case 22:case 23:return M6(),n=e.memoizedState!==null,t!==null&&t.memoizedState!==null!==n&&(e.flags|=8192),n&&e.mode&1?ad&1073741824&&(kc(e),e.subtreeFlags&6&&(e.flags|=8192)):kc(e),null;case 24:return null;case 25:return null}throw Error(sn(156,e.tag))}function aCe(t,e){switch(f6(e),e.tag){case 1:return Lu(e.type)&&ZI(),t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 3:return E1(),so(Du),so(Oc),w6(),t=e.flags,t&65536&&!(t&128)?(e.flags=t&-65537|128,e):null;case 5:return b6(e),null;case 13:if(so(jo),t=e.memoizedState,t!==null&&t.dehydrated!==null){if(e.alternate===null)throw Error(sn(340));k1()}return t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 19:return so(jo),null;case 4:return E1(),null;case 10:return y6(e.type._context),null;case 22:case 23:return M6(),null;case 24:return null;default:return null}}var cP=!1,Pc=!1,oCe=typeof WeakSet=="function"?WeakSet:Set,Gn=null;function Lw(t,e){var r=t.ref;if(r!==null)if(typeof r=="function")try{r(null)}catch(n){Po(t,e,n)}else r.current=null}function f5(t,e,r){try{r()}catch(n){Po(t,e,n)}}var CZ=!1;function lCe(t,e){if(YB=HI,t=hie(),d6(t)){if("selectionStart"in t)var r={start:t.selectionStart,end:t.selectionEnd};else e:{r=(r=t.ownerDocument)&&r.defaultView||window;var n=r.getSelection&&r.getSelection();if(n&&n.rangeCount!==0){r=n.anchorNode;var i=n.anchorOffset,o=n.focusNode;n=n.focusOffset;try{r.nodeType,o.nodeType}catch{r=null;break e}var c=0,a=-1,m=-1,g=0,_=0,j=t,N=null;t:for(;;){for(var C;j!==r||i!==0&&j.nodeType!==3||(a=c+i),j!==o||n!==0&&j.nodeType!==3||(m=c+n),j.nodeType===3&&(c+=j.nodeValue.length),(C=j.firstChild)!==null;)N=j,j=C;for(;;){if(j===t)break t;if(N===r&&++g===i&&(a=c),N===o&&++_===n&&(m=c),(C=j.nextSibling)!==null)break;j=N,N=j.parentNode}j=C}r=a===-1||m===-1?null:{start:a,end:m}}else r=null}r=r||{start:0,end:0}}else r=null;for(XB={focusedElem:t,selectionRange:r},HI=!1,Gn=e;Gn!==null;)if(e=Gn,t=e.child,(e.subtreeFlags&1028)!==0&&t!==null)t.return=e,Gn=t;else for(;Gn!==null;){e=Gn;try{var P=e.alternate;if(e.flags&1024)switch(e.tag){case 0:case 11:case 15:break;case 1:if(P!==null){var A=P.memoizedProps,I=P.memoizedState,O=e.stateNode,R=O.getSnapshotBeforeUpdate(e.elementType===e.type?A:tf(e.type,A),I);O.__reactInternalSnapshotBeforeUpdate=R}break;case 3:var z=e.stateNode.containerInfo;z.nodeType===1?z.textContent="":z.nodeType===9&&z.documentElement&&z.removeChild(z.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(sn(163))}}catch(W){Po(e,e.return,W)}if(t=e.sibling,t!==null){t.return=e.return,Gn=t;break}Gn=e.return}return P=CZ,CZ=!1,P}function JC(t,e,r){var n=e.updateQueue;if(n=n!==null?n.lastEffect:null,n!==null){var i=n=n.next;do{if((i.tag&t)===t){var o=i.destroy;i.destroy=void 0,o!==void 0&&f5(e,r,o)}i=i.next}while(i!==n)}}function VR(t,e){if(e=e.updateQueue,e=e!==null?e.lastEffect:null,e!==null){var r=e=e.next;do{if((r.tag&t)===t){var n=r.create;r.destroy=n()}r=r.next}while(r!==e)}}function p5(t){var e=t.ref;if(e!==null){var r=t.stateNode;switch(t.tag){case 5:t=r;break;default:t=r}typeof e=="function"?e(t):e.current=t}}function lae(t){var e=t.alternate;e!==null&&(t.alternate=null,lae(e)),t.child=null,t.deletions=null,t.sibling=null,t.tag===5&&(e=t.stateNode,e!==null&&(delete e[cp],delete e[F2],delete e[e5],delete e[qNe],delete e[HNe])),t.stateNode=null,t.return=null,t.dependencies=null,t.memoizedProps=null,t.memoizedState=null,t.pendingProps=null,t.stateNode=null,t.updateQueue=null}function cae(t){return t.tag===5||t.tag===3||t.tag===4}function kZ(t){e:for(;;){for(;t.sibling===null;){if(t.return===null||cae(t.return))return null;t=t.return}for(t.sibling.return=t.return,t=t.sibling;t.tag!==5&&t.tag!==6&&t.tag!==18;){if(t.flags&2||t.child===null||t.tag===4)continue e;t.child.return=t,t=t.child}if(!(t.flags&2))return t.stateNode}}function m5(t,e,r){var n=t.tag;if(n===5||n===6)t=t.stateNode,e?r.nodeType===8?r.parentNode.insertBefore(t,e):r.insertBefore(t,e):(r.nodeType===8?(e=r.parentNode,e.insertBefore(t,r)):(e=r,e.appendChild(t)),r=r._reactRootContainer,r!=null||e.onclick!==null||(e.onclick=KI));else if(n!==4&&(t=t.child,t!==null))for(m5(t,e,r),t=t.sibling;t!==null;)m5(t,e,r),t=t.sibling}function g5(t,e,r){var n=t.tag;if(n===5||n===6)t=t.stateNode,e?r.insertBefore(t,e):r.appendChild(t);else if(n!==4&&(t=t.child,t!==null))for(g5(t,e,r),t=t.sibling;t!==null;)g5(t,e,r),t=t.sibling}var uc=null,af=!1;function Wg(t,e,r){for(r=r.child;r!==null;)uae(t,e,r),r=r.sibling}function uae(t,e,r){if(pp&&typeof pp.onCommitFiberUnmount=="function")try{pp.onCommitFiberUnmount(RR,r)}catch{}switch(r.tag){case 5:Pc||Lw(r,e);case 6:var n=uc,i=af;uc=null,Wg(t,e,r),uc=n,af=i,uc!==null&&(af?(t=uc,r=r.stateNode,t.nodeType===8?t.parentNode.removeChild(r):t.removeChild(r)):uc.removeChild(r.stateNode));break;case 18:uc!==null&&(af?(t=uc,r=r.stateNode,t.nodeType===8?bF(t.parentNode,r):t.nodeType===1&&bF(t,r),M2(t)):bF(uc,r.stateNode));break;case 4:n=uc,i=af,uc=r.stateNode.containerInfo,af=!0,Wg(t,e,r),uc=n,af=i;break;case 0:case 11:case 14:case 15:if(!Pc&&(n=r.updateQueue,n!==null&&(n=n.lastEffect,n!==null))){i=n=n.next;do{var o=i,c=o.destroy;o=o.tag,c!==void 0&&(o&2||o&4)&&f5(r,e,c),i=i.next}while(i!==n)}Wg(t,e,r);break;case 1:if(!Pc&&(Lw(r,e),n=r.stateNode,typeof n.componentWillUnmount=="function"))try{n.props=r.memoizedProps,n.state=r.memoizedState,n.componentWillUnmount()}catch(a){Po(r,e,a)}Wg(t,e,r);break;case 21:Wg(t,e,r);break;case 22:r.mode&1?(Pc=(n=Pc)||r.memoizedState!==null,Wg(t,e,r),Pc=n):Wg(t,e,r);break;default:Wg(t,e,r)}}function TZ(t){var e=t.updateQueue;if(e!==null){t.updateQueue=null;var r=t.stateNode;r===null&&(r=t.stateNode=new oCe),e.forEach(function(n){var i=yCe.bind(null,t,n);r.has(n)||(r.add(n),n.then(i,i))})}}function Kh(t,e){var r=e.deletions;if(r!==null)for(var n=0;ni&&(i=c),n&=~o}if(n=i,n=Ho()-n,n=(120>n?120:480>n?480:1080>n?1080:1920>n?1920:3e3>n?3e3:4320>n?4320:1960*uCe(n/1960))-n,10t?16:t,Ey===null)var n=!1;else{if(t=Ey,Ey=null,oM=0,aa&6)throw Error(sn(331));var i=aa;for(aa|=4,Gn=t.current;Gn!==null;){var o=Gn,c=o.child;if(Gn.flags&16){var a=o.deletions;if(a!==null){for(var m=0;mHo()-P6?p_(t,0):A6|=r),Fu(t,e)}function xae(t,e){e===0&&(t.mode&1?(e=eP,eP<<=1,!(eP&130023424)&&(eP=4194304)):e=1);var r=au();t=Um(t,e),t!==null&&(lT(t,e,r),Fu(t,r))}function gCe(t){var e=t.memoizedState,r=0;e!==null&&(r=e.retryLane),xae(t,r)}function yCe(t,e){var r=0;switch(t.tag){case 13:var n=t.stateNode,i=t.memoizedState;i!==null&&(r=i.retryLane);break;case 19:n=t.stateNode;break;default:throw Error(sn(314))}n!==null&&n.delete(e),xae(t,r)}var vae;vae=function(t,e,r){if(t!==null)if(t.memoizedProps!==e.pendingProps||Du.current)Ou=!0;else{if(!(t.lanes&r)&&!(e.flags&128))return Ou=!1,sCe(t,e,r);Ou=!!(t.flags&131072)}else Ou=!1,po&&e.flags&1048576&&jie(e,QI,e.index);switch(e.lanes=0,e.tag){case 2:var n=e.type;yI(t,e),t=e.pendingProps;var i=C1(e,Oc.current);Yw(e,r),i=S6(null,e,n,t,i,r);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,Lu(n)?(o=!0,YI(e)):o=!1,e.memoizedState=i.state!==null&&i.state!==void 0?i.state:null,v6(e),i.updater=UR,e.stateNode=i,i._reactInternals=e,a5(e,n,t,r),e=c5(null,e,n,!0,o,r)):(e.tag=0,po&&o&&h6(e),Qc(null,e,i,r),e=e.child),e;case 16:n=e.elementType;e:{switch(yI(t,e),t=e.pendingProps,i=n._init,n=i(n._payload),e.type=n,i=e.tag=vCe(n),t=tf(n,t),i){case 0:e=l5(null,e,n,t,r);break e;case 1:e=jZ(null,e,n,t,r);break e;case 11:e=bZ(null,e,n,t,r);break e;case 14:e=wZ(null,e,n,tf(n.type,t),r);break e}throw Error(sn(306,n,""))}return e;case 0:return n=e.type,i=e.pendingProps,i=e.elementType===n?i:tf(n,i),l5(t,e,n,i,r);case 1:return n=e.type,i=e.pendingProps,i=e.elementType===n?i:tf(n,i),jZ(t,e,n,i,r);case 3:e:{if(rae(e),t===null)throw Error(sn(387));n=e.pendingProps,o=e.memoizedState,i=o.element,Eie(t,e),tM(e,n,null,r);var c=e.memoizedState;if(n=c.element,o.isDehydrated)if(o={element:n,isDehydrated:!1,cache:c.cache,pendingSuspenseBoundaries:c.pendingSuspenseBoundaries,transitions:c.transitions},e.updateQueue.baseState=o,e.memoizedState=o,e.flags&256){i=A1(Error(sn(423)),e),e=SZ(t,e,n,r,i);break e}else if(n!==i){i=A1(Error(sn(424)),e),e=SZ(t,e,n,r,i);break e}else for(md=By(e.stateNode.containerInfo.firstChild),gd=e,po=!0,uf=null,r=kie(e,null,n,r),e.child=r;r;)r.flags=r.flags&-3|4096,r=r.sibling;else{if(k1(),n===i){e=Vm(t,e,r);break e}Qc(t,e,n,r)}e=e.child}return e;case 5:return Aie(e),t===null&&n5(e),n=e.type,i=e.pendingProps,o=t!==null?t.memoizedProps:null,c=i.children,QB(n,i)?c=null:o!==null&&QB(n,o)&&(e.flags|=32),tae(t,e),Qc(t,e,c,r),e.child;case 6:return t===null&&n5(e),null;case 13:return nae(t,e,r);case 4:return _6(e,e.stateNode.containerInfo),n=e.pendingProps,t===null?e.child=T1(e,null,n,r):Qc(t,e,n,r),e.child;case 11:return n=e.type,i=e.pendingProps,i=e.elementType===n?i:tf(n,i),bZ(t,e,n,i,r);case 7:return Qc(t,e,e.pendingProps,r),e.child;case 8:return Qc(t,e,e.pendingProps.children,r),e.child;case 12:return Qc(t,e,e.pendingProps.children,r),e.child;case 10:e:{if(n=e.type._context,i=e.pendingProps,o=e.memoizedProps,c=i.value,Wa(JI,n._currentValue),n._currentValue=c,o!==null)if(jf(o.value,c)){if(o.children===i.children&&!Du.current){e=Vm(t,e,r);break e}}else for(o=e.child,o!==null&&(o.return=e);o!==null;){var a=o.dependencies;if(a!==null){c=o.child;for(var m=a.firstContext;m!==null;){if(m.context===n){if(o.tag===1){m=Om(-1,r&-r),m.tag=2;var g=o.updateQueue;if(g!==null){g=g.shared;var _=g.pending;_===null?m.next=m:(m.next=_.next,_.next=m),g.pending=m}}o.lanes|=r,m=o.alternate,m!==null&&(m.lanes|=r),s5(o.return,r,e),a.lanes|=r;break}m=m.next}}else if(o.tag===10)c=o.type===e.type?null:o.child;else if(o.tag===18){if(c=o.return,c===null)throw Error(sn(341));c.lanes|=r,a=c.alternate,a!==null&&(a.lanes|=r),s5(c,r,e),c=o.sibling}else c=o.child;if(c!==null)c.return=o;else for(c=o;c!==null;){if(c===e){c=null;break}if(o=c.sibling,o!==null){o.return=c.return,c=o;break}c=c.return}o=c}Qc(t,e,i.children,r),e=e.child}return e;case 9:return i=e.type,n=e.pendingProps.children,Yw(e,r),i=hh(i),n=n(i),e.flags|=1,Qc(t,e,n,r),e.child;case 14:return n=e.type,i=tf(n,e.pendingProps),i=tf(n.type,i),wZ(t,e,n,i,r);case 15:return Jie(t,e,e.type,e.pendingProps,r);case 17:return n=e.type,i=e.pendingProps,i=e.elementType===n?i:tf(n,i),yI(t,e),e.tag=1,Lu(n)?(t=!0,YI(e)):t=!1,Yw(e,r),Yie(e,n,i),a5(e,n,i,r),c5(null,e,n,!0,t,r);case 19:return sae(t,e,r);case 22:return eae(t,e,r)}throw Error(sn(156,e.tag))};function _ae(t,e){return Gse(t,e)}function xCe(t,e,r,n){this.tag=t,this.key=r,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=e,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=n,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function sh(t,e,r,n){return new xCe(t,e,r,n)}function R6(t){return t=t.prototype,!(!t||!t.isReactComponent)}function vCe(t){if(typeof t=="function")return R6(t)?1:0;if(t!=null){if(t=t.$$typeof,t===e6)return 11;if(t===t6)return 14}return 2}function qy(t,e){var r=t.alternate;return r===null?(r=sh(t.tag,e,t.key,t.mode),r.elementType=t.elementType,r.type=t.type,r.stateNode=t.stateNode,r.alternate=t,t.alternate=r):(r.pendingProps=e,r.type=t.type,r.flags=0,r.subtreeFlags=0,r.deletions=null),r.flags=t.flags&14680064,r.childLanes=t.childLanes,r.lanes=t.lanes,r.child=t.child,r.memoizedProps=t.memoizedProps,r.memoizedState=t.memoizedState,r.updateQueue=t.updateQueue,e=t.dependencies,r.dependencies=e===null?null:{lanes:e.lanes,firstContext:e.firstContext},r.sibling=t.sibling,r.index=t.index,r.ref=t.ref,r}function _I(t,e,r,n,i,o){var c=2;if(n=t,typeof t=="function")R6(t)&&(c=1);else if(typeof t=="string")c=5;else e:switch(t){case Tw:return m_(r.children,i,o,e);case JV:c=8,i|=8;break;case AB:return t=sh(12,r,e,i|2),t.elementType=AB,t.lanes=o,t;case PB:return t=sh(13,r,e,i),t.elementType=PB,t.lanes=o,t;case IB:return t=sh(19,r,e,i),t.elementType=IB,t.lanes=o,t;case Ase:return HR(r,i,o,e);default:if(typeof t=="object"&&t!==null)switch(t.$$typeof){case Tse:c=10;break e;case Ese:c=9;break e;case e6:c=11;break e;case t6:c=14;break e;case ry:c=16,n=null;break e}throw Error(sn(130,t==null?t:typeof t,""))}return e=sh(c,r,e,i),e.elementType=t,e.type=n,e.lanes=o,e}function m_(t,e,r,n){return t=sh(7,t,n,e),t.lanes=r,t}function HR(t,e,r,n){return t=sh(22,t,n,e),t.elementType=Ase,t.lanes=r,t.stateNode={isHidden:!1},t}function EF(t,e,r){return t=sh(6,t,null,e),t.lanes=r,t}function AF(t,e,r){return e=sh(4,t.children!==null?t.children:[],t.key,e),e.lanes=r,e.stateNode={containerInfo:t.containerInfo,pendingChildren:null,implementation:t.implementation},e}function _Ce(t,e,r,n,i){this.tag=e,this.containerInfo=t,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=uF(0),this.expirationTimes=uF(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=uF(0),this.identifierPrefix=n,this.onRecoverableError=i,this.mutableSourceEagerHydrationData=null}function D6(t,e,r,n,i,o,c,a,m){return t=new _Ce(t,e,r,a,m),e===1?(e=1,o===!0&&(e|=8)):e=0,o=sh(3,null,null,e),t.current=o,o.stateNode=t,o.memoizedState={element:n,isDehydrated:r,cache:null,transitions:null,pendingSuspenseBoundaries:null},v6(o),t}function bCe(t,e,r){var n=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(Sae)}catch(t){console.error(t)}}Sae(),Sse.exports=Nd;var e0=Sse.exports;const B6=sa(e0);var Nae,DZ=e0;Nae=DZ.createRoot,DZ.hydrateRoot;const CCe=1,kCe=1e6;let PF=0;function TCe(){return PF=(PF+1)%Number.MAX_SAFE_INTEGER,PF.toString()}const IF=new Map,LZ=t=>{if(IF.has(t))return;const e=setTimeout(()=>{IF.delete(t),r2({type:"REMOVE_TOAST",toastId:t})},kCe);IF.set(t,e)},ECe=(t,e)=>{switch(e.type){case"ADD_TOAST":return{...t,toasts:[e.toast,...t.toasts].slice(0,CCe)};case"UPDATE_TOAST":return{...t,toasts:t.toasts.map(r=>r.id===e.toast.id?{...r,...e.toast}:r)};case"DISMISS_TOAST":{const{toastId:r}=e;return r?LZ(r):t.toasts.forEach(n=>{LZ(n.id)}),{...t,toasts:t.toasts.map(n=>n.id===r||r===void 0?{...n,open:!1}:n)}}case"REMOVE_TOAST":return e.toastId===void 0?{...t,toasts:[]}:{...t,toasts:t.toasts.filter(r=>r.id!==e.toastId)}}},bI=[];let wI={toasts:[]};function r2(t){wI=ECe(wI,t),bI.forEach(e=>{e(wI)})}function na({...t}){const e=TCe(),r=i=>r2({type:"UPDATE_TOAST",toast:{...i,id:e}}),n=()=>r2({type:"DISMISS_TOAST",toastId:e});return r2({type:"ADD_TOAST",toast:{...t,id:e,open:!0,onOpenChange:i=>{i||n()}}}),{id:e,dismiss:n,update:r}}function Ri(){const[t,e]=D.useState(wI);return D.useEffect(()=>(bI.push(e),()=>{const r=bI.indexOf(e);r>-1&&bI.splice(r,1)}),[t]),{...t,toast:na,dismiss:r=>r2({type:"DISMISS_TOAST",toastId:r})}}function Yr(t,e,{checkForDefaultPrevented:r=!0}={}){return function(i){if(t==null||t(i),r===!1||!i.defaultPrevented)return e==null?void 0:e(i)}}function FZ(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function qm(...t){return e=>{let r=!1;const n=t.map(i=>{const o=FZ(i,e);return!r&&typeof o=="function"&&(r=!0),o});if(r)return()=>{for(let i=0;i{const{children:c,...a}=o,m=D.useMemo(()=>a,Object.values(a));return s.jsx(r.Provider,{value:m,children:c})};n.displayName=t+"Provider";function i(o){const c=D.useContext(r);if(c)return c;if(e!==void 0)return e;throw new Error(`\`${o}\` must be used within \`${t}\``)}return[n,i]}function Yo(t,e=[]){let r=[];function n(o,c){const a=D.createContext(c),m=r.length;r=[...r,c];const g=j=>{var O;const{scope:N,children:C,...P}=j,A=((O=N==null?void 0:N[t])==null?void 0:O[m])||a,I=D.useMemo(()=>P,Object.values(P));return s.jsx(A.Provider,{value:I,children:C})};g.displayName=o+"Provider";function _(j,N){var A;const C=((A=N==null?void 0:N[t])==null?void 0:A[m])||a,P=D.useContext(C);if(P)return P;if(c!==void 0)return c;throw new Error(`\`${j}\` must be used within \`${o}\``)}return[g,_]}const i=()=>{const o=r.map(c=>D.createContext(c));return function(a){const m=(a==null?void 0:a[t])||o;return D.useMemo(()=>({[`__scope${t}`]:{...a,[t]:m}}),[a,m])}};return i.scopeName=t,[n,PCe(i,...e)]}function PCe(...t){const e=t[0];if(t.length===1)return e;const r=()=>{const n=t.map(i=>({useScope:i(),scopeName:i.scopeName}));return function(o){const c=n.reduce((a,{useScope:m,scopeName:g})=>{const j=m(o)[`__scope${g}`];return{...a,...j}},{});return D.useMemo(()=>({[`__scope${e.scopeName}`]:c}),[c])}};return r.scopeName=e.scopeName,r}function nx(t){const e=ICe(t),r=D.forwardRef((n,i)=>{const{children:o,...c}=n,a=D.Children.toArray(o),m=a.find(MCe);if(m){const g=m.props.children,_=a.map(j=>j===m?D.Children.count(g)>1?D.Children.only(null):D.isValidElement(g)?g.props.children:null:j);return s.jsx(e,{...c,ref:i,children:D.isValidElement(g)?D.cloneElement(g,void 0,_):null})}return s.jsx(e,{...c,ref:i,children:o})});return r.displayName=`${t}.Slot`,r}var Cae=nx("Slot");function ICe(t){const e=D.forwardRef((r,n)=>{const{children:i,...o}=r;if(D.isValidElement(i)){const c=RCe(i),a=OCe(o,i.props);return i.type!==D.Fragment&&(a.ref=n?qm(n,c):c),D.cloneElement(i,a)}return D.Children.count(i)>1?D.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}var kae=Symbol("radix.slottable");function Tae(t){const e=({children:r})=>s.jsx(s.Fragment,{children:r});return e.displayName=`${t}.Slottable`,e.__radixId=kae,e}function MCe(t){return D.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===kae}function OCe(t,e){const r={...e};for(const n in e){const i=t[n],o=e[n];/^on[A-Z]/.test(n)?i&&o?r[n]=(...a)=>{const m=o(...a);return i(...a),m}:i&&(r[n]=i):n==="style"?r[n]={...i,...o}:n==="className"&&(r[n]=[i,o].filter(Boolean).join(" "))}return{...t,...r}}function RCe(t){var n,i;let e=(n=Object.getOwnPropertyDescriptor(t.props,"ref"))==null?void 0:n.get,r=e&&"isReactWarning"in e&&e.isReactWarning;return r?t.ref:(e=(i=Object.getOwnPropertyDescriptor(t,"ref"))==null?void 0:i.get,r=e&&"isReactWarning"in e&&e.isReactWarning,r?t.props.ref:t.props.ref||t.ref)}function hT(t){const e=t+"CollectionProvider",[r,n]=Yo(e),[i,o]=r(e,{collectionRef:{current:null},itemMap:new Map}),c=A=>{const{scope:I,children:O}=A,R=Ve.useRef(null),z=Ve.useRef(new Map).current;return s.jsx(i,{scope:I,itemMap:z,collectionRef:R,children:O})};c.displayName=e;const a=t+"CollectionSlot",m=nx(a),g=Ve.forwardRef((A,I)=>{const{scope:O,children:R}=A,z=o(a,O),W=vs(I,z.collectionRef);return s.jsx(m,{ref:W,children:R})});g.displayName=a;const _=t+"CollectionItemSlot",j="data-radix-collection-item",N=nx(_),C=Ve.forwardRef((A,I)=>{const{scope:O,children:R,...z}=A,W=Ve.useRef(null),V=vs(I,W),K=o(_,O);return Ve.useEffect(()=>(K.itemMap.set(W,{ref:W,...z}),()=>void K.itemMap.delete(W))),s.jsx(N,{[j]:"",ref:V,children:R})});C.displayName=_;function P(A){const I=o(t+"CollectionConsumer",A);return Ve.useCallback(()=>{const R=I.collectionRef.current;if(!R)return[];const z=Array.from(R.querySelectorAll(`[${j}]`));return Array.from(I.itemMap.values()).sort((K,Q)=>z.indexOf(K.ref.current)-z.indexOf(Q.ref.current))},[I.collectionRef,I.itemMap])}return[{Provider:c,Slot:g,ItemSlot:C},P,n]}var DCe=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],yn=DCe.reduce((t,e)=>{const r=nx(`Primitive.${e}`),n=D.forwardRef((i,o)=>{const{asChild:c,...a}=i,m=c?r:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),s.jsx(m,{...a,ref:o})});return n.displayName=`Primitive.${e}`,{...t,[e]:n}},{});function $6(t,e){t&&e0.flushSync(()=>t.dispatchEvent(e))}function Oo(t){const e=D.useRef(t);return D.useEffect(()=>{e.current=t}),D.useMemo(()=>(...r)=>{var n;return(n=e.current)==null?void 0:n.call(e,...r)},[])}function LCe(t,e=globalThis==null?void 0:globalThis.document){const r=Oo(t);D.useEffect(()=>{const n=i=>{i.key==="Escape"&&r(i)};return e.addEventListener("keydown",n,{capture:!0}),()=>e.removeEventListener("keydown",n,{capture:!0})},[r,e])}var FCe="DismissableLayer",b5="dismissableLayer.update",zCe="dismissableLayer.pointerDownOutside",BCe="dismissableLayer.focusOutside",zZ,Eae=D.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),t0=D.forwardRef((t,e)=>{const{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:n,onPointerDownOutside:i,onFocusOutside:o,onInteractOutside:c,onDismiss:a,...m}=t,g=D.useContext(Eae),[_,j]=D.useState(null),N=(_==null?void 0:_.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,C]=D.useState({}),P=vs(e,Q=>j(Q)),A=Array.from(g.layers),[I]=[...g.layersWithOutsidePointerEventsDisabled].slice(-1),O=A.indexOf(I),R=_?A.indexOf(_):-1,z=g.layersWithOutsidePointerEventsDisabled.size>0,W=R>=O,V=UCe(Q=>{const te=Q.target,X=[...g.branches].some(ie=>ie.contains(te));!W||X||(i==null||i(Q),c==null||c(Q),Q.defaultPrevented||a==null||a())},N),K=VCe(Q=>{const te=Q.target;[...g.branches].some(ie=>ie.contains(te))||(o==null||o(Q),c==null||c(Q),Q.defaultPrevented||a==null||a())},N);return LCe(Q=>{R===g.layers.size-1&&(n==null||n(Q),!Q.defaultPrevented&&a&&(Q.preventDefault(),a()))},N),D.useEffect(()=>{if(_)return r&&(g.layersWithOutsidePointerEventsDisabled.size===0&&(zZ=N.body.style.pointerEvents,N.body.style.pointerEvents="none"),g.layersWithOutsidePointerEventsDisabled.add(_)),g.layers.add(_),BZ(),()=>{r&&g.layersWithOutsidePointerEventsDisabled.size===1&&(N.body.style.pointerEvents=zZ)}},[_,N,r,g]),D.useEffect(()=>()=>{_&&(g.layers.delete(_),g.layersWithOutsidePointerEventsDisabled.delete(_),BZ())},[_,g]),D.useEffect(()=>{const Q=()=>C({});return document.addEventListener(b5,Q),()=>document.removeEventListener(b5,Q)},[]),s.jsx(yn.div,{...m,ref:P,style:{pointerEvents:z?W?"auto":"none":void 0,...t.style},onFocusCapture:Yr(t.onFocusCapture,K.onFocusCapture),onBlurCapture:Yr(t.onBlurCapture,K.onBlurCapture),onPointerDownCapture:Yr(t.onPointerDownCapture,V.onPointerDownCapture)})});t0.displayName=FCe;var $Ce="DismissableLayerBranch",Aae=D.forwardRef((t,e)=>{const r=D.useContext(Eae),n=D.useRef(null),i=vs(e,n);return D.useEffect(()=>{const o=n.current;if(o)return r.branches.add(o),()=>{r.branches.delete(o)}},[r.branches]),s.jsx(yn.div,{...t,ref:i})});Aae.displayName=$Ce;function UCe(t,e=globalThis==null?void 0:globalThis.document){const r=Oo(t),n=D.useRef(!1),i=D.useRef(()=>{});return D.useEffect(()=>{const o=a=>{if(a.target&&!n.current){let m=function(){Pae(zCe,r,g,{discrete:!0})};const g={originalEvent:a};a.pointerType==="touch"?(e.removeEventListener("click",i.current),i.current=m,e.addEventListener("click",i.current,{once:!0})):m()}else e.removeEventListener("click",i.current);n.current=!1},c=window.setTimeout(()=>{e.addEventListener("pointerdown",o)},0);return()=>{window.clearTimeout(c),e.removeEventListener("pointerdown",o),e.removeEventListener("click",i.current)}},[e,r]),{onPointerDownCapture:()=>n.current=!0}}function VCe(t,e=globalThis==null?void 0:globalThis.document){const r=Oo(t),n=D.useRef(!1);return D.useEffect(()=>{const i=o=>{o.target&&!n.current&&Pae(BCe,r,{originalEvent:o},{discrete:!1})};return e.addEventListener("focusin",i),()=>e.removeEventListener("focusin",i)},[e,r]),{onFocusCapture:()=>n.current=!0,onBlurCapture:()=>n.current=!1}}function BZ(){const t=new CustomEvent(b5);document.dispatchEvent(t)}function Pae(t,e,r,{discrete:n}){const i=r.originalEvent.target,o=new CustomEvent(t,{bubbles:!1,cancelable:!0,detail:r});e&&i.addEventListener(t,e,{once:!0}),n?$6(i,o):i.dispatchEvent(o)}var qCe=t0,HCe=Aae,Lo=globalThis!=null&&globalThis.document?D.useLayoutEffect:()=>{},WCe="Portal",Tj=D.forwardRef((t,e)=>{var a;const{container:r,...n}=t,[i,o]=D.useState(!1);Lo(()=>o(!0),[]);const c=r||i&&((a=globalThis==null?void 0:globalThis.document)==null?void 0:a.body);return c?B6.createPortal(s.jsx(yn.div,{...n,ref:e}),c):null});Tj.displayName=WCe;function GCe(t,e){return D.useReducer((r,n)=>e[r][n]??r,t)}var gl=t=>{const{present:e,children:r}=t,n=KCe(e),i=typeof r=="function"?r({present:n.isPresent}):D.Children.only(r),o=vs(n.ref,ZCe(i));return typeof r=="function"||n.isPresent?D.cloneElement(i,{ref:o}):null};gl.displayName="Presence";function KCe(t){const[e,r]=D.useState(),n=D.useRef(null),i=D.useRef(t),o=D.useRef("none"),c=t?"mounted":"unmounted",[a,m]=GCe(c,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return D.useEffect(()=>{const g=hP(n.current);o.current=a==="mounted"?g:"none"},[a]),Lo(()=>{const g=n.current,_=i.current;if(_!==t){const N=o.current,C=hP(g);t?m("MOUNT"):C==="none"||(g==null?void 0:g.display)==="none"?m("UNMOUNT"):m(_&&N!==C?"ANIMATION_OUT":"UNMOUNT"),i.current=t}},[t,m]),Lo(()=>{if(e){let g;const _=e.ownerDocument.defaultView??window,j=C=>{const A=hP(n.current).includes(C.animationName);if(C.target===e&&A&&(m("ANIMATION_END"),!i.current)){const I=e.style.animationFillMode;e.style.animationFillMode="forwards",g=_.setTimeout(()=>{e.style.animationFillMode==="forwards"&&(e.style.animationFillMode=I)})}},N=C=>{C.target===e&&(o.current=hP(n.current))};return e.addEventListener("animationstart",N),e.addEventListener("animationcancel",j),e.addEventListener("animationend",j),()=>{_.clearTimeout(g),e.removeEventListener("animationstart",N),e.removeEventListener("animationcancel",j),e.removeEventListener("animationend",j)}}else m("ANIMATION_END")},[e,m]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:D.useCallback(g=>{n.current=g?getComputedStyle(g):null,r(g)},[])}}function hP(t){return(t==null?void 0:t.animationName)||"none"}function ZCe(t){var n,i;let e=(n=Object.getOwnPropertyDescriptor(t.props,"ref"))==null?void 0:n.get,r=e&&"isReactWarning"in e&&e.isReactWarning;return r?t.ref:(e=(i=Object.getOwnPropertyDescriptor(t,"ref"))==null?void 0:i.get,r=e&&"isReactWarning"in e&&e.isReactWarning,r?t.props.ref:t.props.ref||t.ref)}var YCe=ZV[" useInsertionEffect ".trim().toString()]||Lo;function Uu({prop:t,defaultProp:e,onChange:r=()=>{},caller:n}){const[i,o,c]=XCe({defaultProp:e,onChange:r}),a=t!==void 0,m=a?t:i;{const _=D.useRef(t!==void 0);D.useEffect(()=>{const j=_.current;j!==a&&console.warn(`${n} is changing from ${j?"controlled":"uncontrolled"} to ${a?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),_.current=a},[a,n])}const g=D.useCallback(_=>{var j;if(a){const N=QCe(_)?_(t):_;N!==t&&((j=c.current)==null||j.call(c,N))}else o(_)},[a,t,o,c]);return[m,g]}function XCe({defaultProp:t,onChange:e}){const[r,n]=D.useState(t),i=D.useRef(r),o=D.useRef(e);return YCe(()=>{o.current=e},[e]),D.useEffect(()=>{var c;i.current!==r&&((c=o.current)==null||c.call(o,r),i.current=r)},[r,i]),[r,n,o]}function QCe(t){return typeof t=="function"}var Iae=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),JCe="VisuallyHidden",YR=D.forwardRef((t,e)=>s.jsx(yn.span,{...t,ref:e,style:{...Iae,...t.style}}));YR.displayName=JCe;var e2e=YR,U6="ToastProvider",[V6,t2e,r2e]=hT("Toast"),[Mae]=Yo("Toast",[r2e]),[n2e,XR]=Mae(U6),Oae=t=>{const{__scopeToast:e,label:r="Notification",duration:n=5e3,swipeDirection:i="right",swipeThreshold:o=50,children:c}=t,[a,m]=D.useState(null),[g,_]=D.useState(0),j=D.useRef(!1),N=D.useRef(!1);return r.trim()||console.error(`Invalid prop \`label\` supplied to \`${U6}\`. Expected non-empty \`string\`.`),s.jsx(V6.Provider,{scope:e,children:s.jsx(n2e,{scope:e,label:r,duration:n,swipeDirection:i,swipeThreshold:o,toastCount:g,viewport:a,onViewportChange:m,onToastAdd:D.useCallback(()=>_(C=>C+1),[]),onToastRemove:D.useCallback(()=>_(C=>C-1),[]),isFocusedToastEscapeKeyDownRef:j,isClosePausedRef:N,children:c})})};Oae.displayName=U6;var Rae="ToastViewport",s2e=["F8"],w5="toast.viewportPause",j5="toast.viewportResume",Dae=D.forwardRef((t,e)=>{const{__scopeToast:r,hotkey:n=s2e,label:i="Notifications ({hotkey})",...o}=t,c=XR(Rae,r),a=t2e(r),m=D.useRef(null),g=D.useRef(null),_=D.useRef(null),j=D.useRef(null),N=vs(e,j,c.onViewportChange),C=n.join("+").replace(/Key/g,"").replace(/Digit/g,""),P=c.toastCount>0;D.useEffect(()=>{const I=O=>{var z;n.length!==0&&n.every(W=>O[W]||O.code===W)&&((z=j.current)==null||z.focus())};return document.addEventListener("keydown",I),()=>document.removeEventListener("keydown",I)},[n]),D.useEffect(()=>{const I=m.current,O=j.current;if(P&&I&&O){const R=()=>{if(!c.isClosePausedRef.current){const K=new CustomEvent(w5);O.dispatchEvent(K),c.isClosePausedRef.current=!0}},z=()=>{if(c.isClosePausedRef.current){const K=new CustomEvent(j5);O.dispatchEvent(K),c.isClosePausedRef.current=!1}},W=K=>{!I.contains(K.relatedTarget)&&z()},V=()=>{I.contains(document.activeElement)||z()};return I.addEventListener("focusin",R),I.addEventListener("focusout",W),I.addEventListener("pointermove",R),I.addEventListener("pointerleave",V),window.addEventListener("blur",R),window.addEventListener("focus",z),()=>{I.removeEventListener("focusin",R),I.removeEventListener("focusout",W),I.removeEventListener("pointermove",R),I.removeEventListener("pointerleave",V),window.removeEventListener("blur",R),window.removeEventListener("focus",z)}}},[P,c.isClosePausedRef]);const A=D.useCallback(({tabbingDirection:I})=>{const R=a().map(z=>{const W=z.ref.current,V=[W,...y2e(W)];return I==="forwards"?V:V.reverse()});return(I==="forwards"?R.reverse():R).flat()},[a]);return D.useEffect(()=>{const I=j.current;if(I){const O=R=>{var V,K,Q;const z=R.altKey||R.ctrlKey||R.metaKey;if(R.key==="Tab"&&!z){const te=document.activeElement,X=R.shiftKey;if(R.target===I&&X){(V=g.current)==null||V.focus();return}const xe=A({tabbingDirection:X?"backwards":"forwards"}),pe=xe.findIndex(ve=>ve===te);MF(xe.slice(pe+1))?R.preventDefault():X?(K=g.current)==null||K.focus():(Q=_.current)==null||Q.focus()}};return I.addEventListener("keydown",O),()=>I.removeEventListener("keydown",O)}},[a,A]),s.jsxs(HCe,{ref:m,role:"region","aria-label":i.replace("{hotkey}",C),tabIndex:-1,style:{pointerEvents:P?void 0:"none"},children:[P&&s.jsx(S5,{ref:g,onFocusFromOutsideViewport:()=>{const I=A({tabbingDirection:"forwards"});MF(I)}}),s.jsx(V6.Slot,{scope:r,children:s.jsx(yn.ol,{tabIndex:-1,...o,ref:N})}),P&&s.jsx(S5,{ref:_,onFocusFromOutsideViewport:()=>{const I=A({tabbingDirection:"backwards"});MF(I)}})]})});Dae.displayName=Rae;var Lae="ToastFocusProxy",S5=D.forwardRef((t,e)=>{const{__scopeToast:r,onFocusFromOutsideViewport:n,...i}=t,o=XR(Lae,r);return s.jsx(YR,{"aria-hidden":!0,tabIndex:0,...i,ref:e,style:{position:"fixed"},onFocus:c=>{var g;const a=c.relatedTarget;!((g=o.viewport)!=null&&g.contains(a))&&n()}})});S5.displayName=Lae;var fT="Toast",i2e="toast.swipeStart",a2e="toast.swipeMove",o2e="toast.swipeCancel",l2e="toast.swipeEnd",Fae=D.forwardRef((t,e)=>{const{forceMount:r,open:n,defaultOpen:i,onOpenChange:o,...c}=t,[a,m]=Uu({prop:n,defaultProp:i??!0,onChange:o,caller:fT});return s.jsx(gl,{present:r||a,children:s.jsx(d2e,{open:a,...c,ref:e,onClose:()=>m(!1),onPause:Oo(t.onPause),onResume:Oo(t.onResume),onSwipeStart:Yr(t.onSwipeStart,g=>{g.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:Yr(t.onSwipeMove,g=>{const{x:_,y:j}=g.detail.delta;g.currentTarget.setAttribute("data-swipe","move"),g.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${_}px`),g.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${j}px`)}),onSwipeCancel:Yr(t.onSwipeCancel,g=>{g.currentTarget.setAttribute("data-swipe","cancel"),g.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),g.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),g.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"),g.currentTarget.style.removeProperty("--radix-toast-swipe-end-y")}),onSwipeEnd:Yr(t.onSwipeEnd,g=>{const{x:_,y:j}=g.detail.delta;g.currentTarget.setAttribute("data-swipe","end"),g.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),g.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),g.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${_}px`),g.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${j}px`),m(!1)})})})});Fae.displayName=fT;var[c2e,u2e]=Mae(fT,{onClose(){}}),d2e=D.forwardRef((t,e)=>{const{__scopeToast:r,type:n="foreground",duration:i,open:o,onClose:c,onEscapeKeyDown:a,onPause:m,onResume:g,onSwipeStart:_,onSwipeMove:j,onSwipeCancel:N,onSwipeEnd:C,...P}=t,A=XR(fT,r),[I,O]=D.useState(null),R=vs(e,ve=>O(ve)),z=D.useRef(null),W=D.useRef(null),V=i||A.duration,K=D.useRef(0),Q=D.useRef(V),te=D.useRef(0),{onToastAdd:X,onToastRemove:ie}=A,he=Oo(()=>{var ge;(I==null?void 0:I.contains(document.activeElement))&&((ge=A.viewport)==null||ge.focus()),c()}),xe=D.useCallback(ve=>{!ve||ve===1/0||(window.clearTimeout(te.current),K.current=new Date().getTime(),te.current=window.setTimeout(he,ve))},[he]);D.useEffect(()=>{const ve=A.viewport;if(ve){const ge=()=>{xe(Q.current),g==null||g()},ke=()=>{const Ce=new Date().getTime()-K.current;Q.current=Q.current-Ce,window.clearTimeout(te.current),m==null||m()};return ve.addEventListener(w5,ke),ve.addEventListener(j5,ge),()=>{ve.removeEventListener(w5,ke),ve.removeEventListener(j5,ge)}}},[A.viewport,V,m,g,xe]),D.useEffect(()=>{o&&!A.isClosePausedRef.current&&xe(V)},[o,V,A.isClosePausedRef,xe]),D.useEffect(()=>(X(),()=>ie()),[X,ie]);const pe=D.useMemo(()=>I?Hae(I):null,[I]);return A.viewport?s.jsxs(s.Fragment,{children:[pe&&s.jsx(h2e,{__scopeToast:r,role:"status","aria-live":n==="foreground"?"assertive":"polite","aria-atomic":!0,children:pe}),s.jsx(c2e,{scope:r,onClose:he,children:e0.createPortal(s.jsx(V6.ItemSlot,{scope:r,children:s.jsx(qCe,{asChild:!0,onEscapeKeyDown:Yr(a,()=>{A.isFocusedToastEscapeKeyDownRef.current||he(),A.isFocusedToastEscapeKeyDownRef.current=!1}),children:s.jsx(yn.li,{role:"status","aria-live":"off","aria-atomic":!0,tabIndex:0,"data-state":o?"open":"closed","data-swipe-direction":A.swipeDirection,...P,ref:R,style:{userSelect:"none",touchAction:"none",...t.style},onKeyDown:Yr(t.onKeyDown,ve=>{ve.key==="Escape"&&(a==null||a(ve.nativeEvent),ve.nativeEvent.defaultPrevented||(A.isFocusedToastEscapeKeyDownRef.current=!0,he()))}),onPointerDown:Yr(t.onPointerDown,ve=>{ve.button===0&&(z.current={x:ve.clientX,y:ve.clientY})}),onPointerMove:Yr(t.onPointerMove,ve=>{if(!z.current)return;const ge=ve.clientX-z.current.x,ke=ve.clientY-z.current.y,Ce=!!W.current,Se=["left","right"].includes(A.swipeDirection),je=["left","up"].includes(A.swipeDirection)?Math.min:Math.max,et=Se?je(0,ge):0,bt=Se?0:je(0,ke),_e=ve.pointerType==="touch"?10:2,Ye={x:et,y:bt},pt={originalEvent:ve,delta:Ye};Ce?(W.current=Ye,fP(a2e,j,pt,{discrete:!1})):$Z(Ye,A.swipeDirection,_e)?(W.current=Ye,fP(i2e,_,pt,{discrete:!1}),ve.target.setPointerCapture(ve.pointerId)):(Math.abs(ge)>_e||Math.abs(ke)>_e)&&(z.current=null)}),onPointerUp:Yr(t.onPointerUp,ve=>{const ge=W.current,ke=ve.target;if(ke.hasPointerCapture(ve.pointerId)&&ke.releasePointerCapture(ve.pointerId),W.current=null,z.current=null,ge){const Ce=ve.currentTarget,Se={originalEvent:ve,delta:ge};$Z(ge,A.swipeDirection,A.swipeThreshold)?fP(l2e,C,Se,{discrete:!0}):fP(o2e,N,Se,{discrete:!0}),Ce.addEventListener("click",je=>je.preventDefault(),{once:!0})}})})})}),A.viewport)})]}):null}),h2e=t=>{const{__scopeToast:e,children:r,...n}=t,i=XR(fT,e),[o,c]=D.useState(!1),[a,m]=D.useState(!1);return m2e(()=>c(!0)),D.useEffect(()=>{const g=window.setTimeout(()=>m(!0),1e3);return()=>window.clearTimeout(g)},[]),a?null:s.jsx(Tj,{asChild:!0,children:s.jsx(YR,{...n,children:o&&s.jsxs(s.Fragment,{children:[i.label," ",r]})})})},f2e="ToastTitle",zae=D.forwardRef((t,e)=>{const{__scopeToast:r,...n}=t;return s.jsx(yn.div,{...n,ref:e})});zae.displayName=f2e;var p2e="ToastDescription",Bae=D.forwardRef((t,e)=>{const{__scopeToast:r,...n}=t;return s.jsx(yn.div,{...n,ref:e})});Bae.displayName=p2e;var $ae="ToastAction",Uae=D.forwardRef((t,e)=>{const{altText:r,...n}=t;return r.trim()?s.jsx(qae,{altText:r,asChild:!0,children:s.jsx(q6,{...n,ref:e})}):(console.error(`Invalid prop \`altText\` supplied to \`${$ae}\`. Expected non-empty \`string\`.`),null)});Uae.displayName=$ae;var Vae="ToastClose",q6=D.forwardRef((t,e)=>{const{__scopeToast:r,...n}=t,i=u2e(Vae,r);return s.jsx(qae,{asChild:!0,children:s.jsx(yn.button,{type:"button",...n,ref:e,onClick:Yr(t.onClick,i.onClose)})})});q6.displayName=Vae;var qae=D.forwardRef((t,e)=>{const{__scopeToast:r,altText:n,...i}=t;return s.jsx(yn.div,{"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":n||void 0,...i,ref:e})});function Hae(t){const e=[];return Array.from(t.childNodes).forEach(n=>{if(n.nodeType===n.TEXT_NODE&&n.textContent&&e.push(n.textContent),g2e(n)){const i=n.ariaHidden||n.hidden||n.style.display==="none",o=n.dataset.radixToastAnnounceExclude==="";if(!i)if(o){const c=n.dataset.radixToastAnnounceAlt;c&&e.push(c)}else e.push(...Hae(n))}}),e}function fP(t,e,r,{discrete:n}){const i=r.originalEvent.currentTarget,o=new CustomEvent(t,{bubbles:!0,cancelable:!0,detail:r});e&&i.addEventListener(t,e,{once:!0}),n?$6(i,o):i.dispatchEvent(o)}var $Z=(t,e,r=0)=>{const n=Math.abs(t.x),i=Math.abs(t.y),o=n>i;return e==="left"||e==="right"?o&&n>r:!o&&i>r};function m2e(t=()=>{}){const e=Oo(t);Lo(()=>{let r=0,n=0;return r=window.requestAnimationFrame(()=>n=window.requestAnimationFrame(e)),()=>{window.cancelAnimationFrame(r),window.cancelAnimationFrame(n)}},[e])}function g2e(t){return t.nodeType===t.ELEMENT_NODE}function y2e(t){const e=[],r=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode:n=>{const i=n.tagName==="INPUT"&&n.type==="hidden";return n.disabled||n.hidden||i?NodeFilter.FILTER_SKIP:n.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;r.nextNode();)e.push(r.currentNode);return e}function MF(t){const e=document.activeElement;return t.some(r=>r===e?!0:(r.focus(),document.activeElement!==e))}var x2e=Oae,Wae=Dae,Gae=Fae,Kae=zae,Zae=Bae,Yae=Uae,Xae=q6;function Qae(t){var e,r,n="";if(typeof t=="string"||typeof t=="number")n+=t;else if(typeof t=="object")if(Array.isArray(t)){var i=t.length;for(e=0;etypeof t=="boolean"?`${t}`:t===0?"0":t,VZ=Ci,Ej=(t,e)=>r=>{var n;if((e==null?void 0:e.variants)==null)return VZ(t,r==null?void 0:r.class,r==null?void 0:r.className);const{variants:i,defaultVariants:o}=e,c=Object.keys(i).map(g=>{const _=r==null?void 0:r[g],j=o==null?void 0:o[g];if(_===null)return null;const N=UZ(_)||UZ(j);return i[g][N]}),a=r&&Object.entries(r).reduce((g,_)=>{let[j,N]=_;return N===void 0||(g[j]=N),g},{}),m=e==null||(n=e.compoundVariants)===null||n===void 0?void 0:n.reduce((g,_)=>{let{class:j,className:N,...C}=_;return Object.entries(C).every(P=>{let[A,I]=P;return Array.isArray(I)?I.includes({...o,...a}[A]):{...o,...a}[A]===I})?[...g,j,N]:g},[]);return VZ(t,c,m,r==null?void 0:r.class,r==null?void 0:r.className)};/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const v2e=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Jae=(...t)=>t.filter((e,r,n)=>!!e&&e.trim()!==""&&n.indexOf(e)===r).join(" ").trim();/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */var _2e={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.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const b2e=D.forwardRef(({color:t="currentColor",size:e=24,strokeWidth:r=2,absoluteStrokeWidth:n,className:i="",children:o,iconNode:c,...a},m)=>D.createElement("svg",{ref:m,..._2e,width:e,height:e,stroke:t,strokeWidth:n?Number(r)*24/Number(e):r,className:Jae("lucide",i),...a},[...c.map(([g,_])=>D.createElement(g,_)),...Array.isArray(o)?o:[o]]));/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vr=(t,e)=>{const r=D.forwardRef(({className:n,...i},o)=>D.createElement(b2e,{ref:o,iconNode:e,className:Jae(`lucide-${v2e(t)}`,n),...i}));return r.displayName=`${t}`,r};/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Qw=vr("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.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const eoe=vr("AlignCenter",[["path",{d:"M17 12H7",key:"16if0g"}],["path",{d:"M19 18H5",key:"18s9l3"}],["path",{d:"M21 6H3",key:"1jwq7v"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const toe=vr("AlignLeft",[["path",{d:"M15 12H3",key:"6jk70r"}],["path",{d:"M17 18H3",key:"1amg6g"}],["path",{d:"M21 6H3",key:"1jwq7v"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const roe=vr("AlignRight",[["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M21 18H7",key:"1ygte8"}],["path",{d:"M21 6H3",key:"1jwq7v"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const w2e=vr("AppWindow",[["rect",{x:"2",y:"4",width:"20",height:"16",rx:"2",key:"izxlao"}],["path",{d:"M10 4v4",key:"pp8u80"}],["path",{d:"M2 8h20",key:"d11cs7"}],["path",{d:"M6 4v4",key:"1svtjw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ka=vr("ArrowLeft",[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cd=vr("ArrowRight",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const noe=vr("ArrowUp",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Jw=vr("Award",[["path",{d:"m15.477 12.89 1.515 8.526a.5.5 0 0 1-.81.47l-3.58-2.687a1 1 0 0 0-1.197 0l-3.586 2.686a.5.5 0 0 1-.81-.469l1.514-8.526",key:"1yiouv"}],["circle",{cx:"12",cy:"8",r:"6",key:"1vp47v"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const soe=vr("Bath",[["path",{d:"M10 4 8 6",key:"1rru8s"}],["path",{d:"M17 19v2",key:"ts1sot"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"M7 19v2",key:"12npes"}],["path",{d:"M9 5 7.621 3.621A2.121 2.121 0 0 0 4 5v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-5",key:"14ym8i"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ioe=vr("Bed",[["path",{d:"M2 4v16",key:"vw9hq8"}],["path",{d:"M2 8h18a2 2 0 0 1 2 2v10",key:"1dgv2r"}],["path",{d:"M2 17h20",key:"18nfp3"}],["path",{d:"M6 8v9",key:"1yriud"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const H6=vr("BellOff",[["path",{d:"M8.7 3A6 6 0 0 1 18 8a21.3 21.3 0 0 0 .6 5",key:"o7mx20"}],["path",{d:"M17 17H3s3-2 3-9a4.67 4.67 0 0 1 .3-1.7",key:"16f1lm"}],["path",{d:"M10.3 21a1.94 1.94 0 0 0 3.4 0",key:"qgo35s"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const QR=vr("Bell",[["path",{d:"M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9",key:"1qo2s2"}],["path",{d:"M10.3 21a1.94 1.94 0 0 0 3.4 0",key:"qgo35s"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const aoe=vr("Bold",[["path",{d:"M6 12h9a4 4 0 0 1 0 8H7a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1h7a4 4 0 0 1 0 8",key:"mg9rjx"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const j2e=vr("BookOpen",[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const g_=vr("Bookmark",[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z",key:"1fy3hk"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const N5=vr("Bot",[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Hm=vr("Briefcase",[["path",{d:"M16 20V4a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16",key:"jecpp"}],["rect",{width:"20",height:"14",x:"2",y:"6",rx:"2",key:"i6l2r4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yc=vr("Building2",[["path",{d:"M6 22V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v18Z",key:"1b4qmf"}],["path",{d:"M6 12H4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h2",key:"i71pzd"}],["path",{d:"M18 9h2a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2",key:"10jefs"}],["path",{d:"M10 6h4",key:"1itunk"}],["path",{d:"M10 10h4",key:"tcdvrf"}],["path",{d:"M10 14h4",key:"kelpxr"}],["path",{d:"M10 18h4",key:"1ulq68"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qZ=vr("Building",[["rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",ry:"2",key:"76otgf"}],["path",{d:"M9 22v-4h6v4",key:"r93iot"}],["path",{d:"M8 6h.01",key:"1dz90k"}],["path",{d:"M16 6h.01",key:"1x0f13"}],["path",{d:"M12 6h.01",key:"1vi96p"}],["path",{d:"M12 10h.01",key:"1nrarc"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M16 10h.01",key:"1m94wz"}],["path",{d:"M16 14h.01",key:"1gbofw"}],["path",{d:"M8 10h.01",key:"19clt8"}],["path",{d:"M8 14h.01",key:"6423bh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const uM=vr("Cake",[["path",{d:"M20 21v-8a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8",key:"1w3rig"}],["path",{d:"M4 16s.5-1 2-1 2.5 2 4 2 2.5-2 4-2 2.5 2 4 2 2-1 2-1",key:"n2jgmb"}],["path",{d:"M2 21h20",key:"1nyx9w"}],["path",{d:"M7 8v3",key:"1qtyvj"}],["path",{d:"M12 8v3",key:"hwp4zt"}],["path",{d:"M17 8v3",key:"1i6e5u"}],["path",{d:"M7 4h.01",key:"1bh4kh"}],["path",{d:"M12 4h.01",key:"1ujb9j"}],["path",{d:"M17 4h.01",key:"1upcoc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const H2=vr("CalendarDays",[["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"}],["path",{d:"M8 14h.01",key:"6423bh"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M16 14h.01",key:"1gbofw"}],["path",{d:"M8 18h.01",key:"lrp35t"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M16 18h.01",key:"kzsmim"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const OF=vr("CalendarPlus",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M21 13V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h8",key:"3spt84"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M16 19h6",key:"xwg31i"}],["path",{d:"M19 16v6",key:"tddt3s"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ko=vr("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.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _p=vr("ChartColumn",[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M18 17V9",key:"2bz60n"}],["path",{d:"M13 17V5",key:"1frdt8"}],["path",{d:"M8 17v-3",key:"17ska0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ru=vr("Check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pT=vr("ChevronDown",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const I1=vr("ChevronLeft",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wd=vr("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const W6=vr("ChevronUp",[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const S2e=vr("ChevronsUpDown",[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sx=vr("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.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gc=vr("CircleCheckBig",[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const E_=vr("CircleCheck",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ooe=vr("CircleHelp",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const dM=vr("CirclePlay",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polygon",{points:"10 8 16 12 10 16 10 8",key:"1cimsy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const W2=vr("CircleX",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hM=vr("Circle",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const N2e=vr("ClipboardCheck",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}],["path",{d:"m9 14 2 2 4-4",key:"df797q"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const No=vr("Clock",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 16 14",key:"68esgv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const loe=vr("Code",[["polyline",{points:"16 18 22 12 16 6",key:"z7tu5w"}],["polyline",{points:"8 6 2 12 8 18",key:"1eg1df"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ix=vr("Copy",[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fM=vr("CreditCard",[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const G6=vr("Crown",[["path",{d:"M11.562 3.266a.5.5 0 0 1 .876 0L15.39 8.87a1 1 0 0 0 1.516.294L21.183 5.5a.5.5 0 0 1 .798.519l-2.834 10.246a1 1 0 0 1-.956.734H5.81a1 1 0 0 1-.957-.734L2.02 6.02a.5.5 0 0 1 .798-.519l4.276 3.664a1 1 0 0 0 1.516-.294z",key:"1vdc57"}],["path",{d:"M5 21h14",key:"11awu3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const M1=vr("DollarSign",[["line",{x1:"12",x2:"12",y1:"2",y2:"22",key:"7eqyqh"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6",key:"1b0p4s"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Pp=vr("Download",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"7 10 12 15 17 10",key:"2ggqvy"}],["line",{x1:"12",x2:"12",y1:"15",y2:"3",key:"1vk2je"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const coe=vr("EllipsisVertical",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const K6=vr("Ellipsis",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const oa=vr("ExternalLink",[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Z6=vr("EyeOff",[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Rc=vr("Eye",[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const C2e=vr("Facebook",[["path",{d:"M18 2h-3a5 5 0 0 0-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 0 1 1-1h3z",key:"1jg4f8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const HZ=vr("FileImage",[["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"}],["circle",{cx:"10",cy:"12",r:"2",key:"737tya"}],["path",{d:"m20 17-1.296-1.296a2.41 2.41 0 0 0-3.408 0L9 22",key:"wt3hpn"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const JR=vr("FileSpreadsheet",[["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:"M8 13h2",key:"yr2amv"}],["path",{d:"M14 13h2",key:"un5t4a"}],["path",{d:"M8 17h2",key:"2yhykz"}],["path",{d:"M14 17h2",key:"10kma7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ii=vr("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.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const uoe=vr("Film",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M7 3v18",key:"bbkbws"}],["path",{d:"M3 7.5h4",key:"zfgn84"}],["path",{d:"M3 12h18",key:"1i2n21"}],["path",{d:"M3 16.5h4",key:"1230mu"}],["path",{d:"M17 3v18",key:"in4fa5"}],["path",{d:"M17 7.5h4",key:"myr1c1"}],["path",{d:"M17 16.5h4",key:"go4c1d"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const k2e=vr("Filter",[["polygon",{points:"22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3",key:"1yg77f"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const T2e=vr("Flag",[["path",{d:"M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1z",key:"i9b6wo"}],["line",{x1:"4",x2:"4",y1:"22",y2:"15",key:"1cm3nv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const doe=vr("Flame",[["path",{d:"M8.5 14.5A2.5 2.5 0 0 0 11 12c0-1.38-.5-2-1-3-1.072-2.143-.224-4.054 2-6 .5 2.5 2 4.9 4 6.5 2 1.6 3 3.5 3 5.5a7 7 0 1 1-14 0c0-1.153.433-2.294 1-3a2.5 2.5 0 0 0 2.5 2.5z",key:"96xj49"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const WZ=vr("FolderOpen",[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yd=vr("Gift",[["rect",{x:"3",y:"8",width:"18",height:"4",rx:"1",key:"bkv52"}],["path",{d:"M12 8v13",key:"1c76mn"}],["path",{d:"M19 12v7a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2v-7",key:"6wjy6b"}],["path",{d:"M7.5 8a2.5 2.5 0 0 1 0-5A4.8 8 0 0 1 12 8a4.8 8 0 0 1 4.5-5 2.5 2.5 0 0 1 0 5",key:"1ihvrl"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hoe=vr("Globe",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const eD=vr("GraduationCap",[["path",{d:"M21.42 10.922a1 1 0 0 0-.019-1.838L12.83 5.18a2 2 0 0 0-1.66 0L2.6 9.08a1 1 0 0 0 0 1.832l8.57 3.908a2 2 0 0 0 1.66 0z",key:"j76jl0"}],["path",{d:"M22 10v6",key:"1lu8f3"}],["path",{d:"M6 12.5V16a6 3 0 0 0 12 0v-3.5",key:"1r8lef"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const C5=vr("Grid3x3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"M3 15h18",key:"5xshup"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const foe=vr("GripVertical",[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const E2e=vr("HardDrive",[["line",{x1:"22",x2:"2",y1:"12",y2:"12",key:"1y58io"}],["path",{d:"M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"oot6mr"}],["line",{x1:"6",x2:"6.01",y1:"16",y2:"16",key:"sgf278"}],["line",{x1:"10",x2:"10.01",y1:"16",y2:"16",key:"1l4acy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const A2e=vr("Heading1",[["path",{d:"M4 12h8",key:"17cfdx"}],["path",{d:"M4 18V6",key:"1rz3zl"}],["path",{d:"M12 18V6",key:"zqpxq5"}],["path",{d:"m17 12 3-2v8",key:"1hhhft"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const P2e=vr("Heading2",[["path",{d:"M4 12h8",key:"17cfdx"}],["path",{d:"M4 18V6",key:"1rz3zl"}],["path",{d:"M12 18V6",key:"zqpxq5"}],["path",{d:"M21 18h-4c0-4 4-3 4-6 0-1.5-2-2.5-4-1",key:"9jr5yi"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bp=vr("Heart",[["path",{d:"M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z",key:"c3ymky"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ou=vr("House",[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8",key:"5wwlr5"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-5.999a2 2 0 0 1 2.582 0l7 5.999A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",key:"1d0kgt"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Wm=vr("Image",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const poe=vr("Italic",[["line",{x1:"19",x2:"10",y1:"4",y2:"4",key:"15jd3p"}],["line",{x1:"14",x2:"5",y1:"20",y2:"20",key:"bu0au3"}],["line",{x1:"15",x2:"9",y1:"4",y2:"20",key:"uljnxc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const moe=vr("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.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tD=vr("LayoutGrid",[["rect",{width:"7",height:"7",x:"3",y:"3",rx:"1",key:"1g98yp"}],["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["rect",{width:"7",height:"7",x:"14",y:"14",rx:"1",key:"nxv5o0"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const goe=vr("LifeBuoy",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m4.93 4.93 4.24 4.24",key:"1ymg45"}],["path",{d:"m14.83 9.17 4.24-4.24",key:"1cb5xl"}],["path",{d:"m14.83 14.83 4.24 4.24",key:"q42g0n"}],["path",{d:"m9.17 14.83-4.24 4.24",key:"bqpfvv"}],["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pM=vr("Lightbulb",[["path",{d:"M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5",key:"1gvzjb"}],["path",{d:"M9 18h6",key:"x1upvd"}],["path",{d:"M10 22h4",key:"ceow96"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Go=vr("Link",[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71",key:"1cjeqo"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71",key:"19qd67"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yoe=vr("ListOrdered",[["path",{d:"M10 12h11",key:"6m4ad9"}],["path",{d:"M10 18h11",key:"11hvi2"}],["path",{d:"M10 6h11",key:"c7qv1k"}],["path",{d:"M4 10h2",key:"16xx2s"}],["path",{d:"M4 6h1v4",key:"cnovpq"}],["path",{d:"M6 18H4c0-1 2-2 2-3s-1-1.5-2-1",key:"m9a95d"}]]);/** * @license lucide-react v0.462.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=vr("List",[["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M3 18h.01",key:"1tta3j"}],["path",{d:"M3 6h.01",key:"1rqtza"}],["path",{d:"M8 12h13",key:"1za7za"}],["path",{d:"M8 18h13",key:"1lx6n3"}],["path",{d:"M8 6h13",key:"ik3vkj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ps=vr("LoaderCircle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const I2e=vr("Locate",[["line",{x1:"2",x2:"5",y1:"12",y2:"12",key:"bvdh0s"}],["line",{x1:"19",x2:"22",y1:"12",y2:"12",key:"1tbv5k"}],["line",{x1:"12",x2:"12",y1:"2",y2:"5",key:"11lu5j"}],["line",{x1:"12",x2:"12",y1:"19",y2:"22",key:"x3vr5v"}],["circle",{cx:"12",cy:"12",r:"7",key:"fim9np"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mM=vr("Lock",[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const GZ=vr("LogOut",[["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}],["polyline",{points:"16 17 21 12 16 7",key:"1gabdz"}],["line",{x1:"21",x2:"9",y1:"12",y2:"12",key:"1uyos4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const M2e=vr("MailX",[["path",{d:"M22 13V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v12c0 1.1.9 2 2 2h9",key:"1j9vog"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}],["path",{d:"m17 17 4 4",key:"1b3523"}],["path",{d:"m21 17-4 4",key:"uinynz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Fo=vr("Mail",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wp=vr("MapPin",[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0",key:"1r0f0z"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const KZ=vr("Medal",[["path",{d:"M7.21 15 2.66 7.14a2 2 0 0 1 .13-2.2L4.4 2.8A2 2 0 0 1 6 2h12a2 2 0 0 1 1.6.8l1.6 2.14a2 2 0 0 1 .14 2.2L16.79 15",key:"143lza"}],["path",{d:"M11 12 5.12 2.2",key:"qhuxz6"}],["path",{d:"m13 12 5.88-9.8",key:"hbye0f"}],["path",{d:"M8 7h8",key:"i86dvs"}],["circle",{cx:"12",cy:"17",r:"5",key:"qbz8iq"}],["path",{d:"M12 18v-2h-.5",key:"fawc4q"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mT=vr("Megaphone",[["path",{d:"m3 11 18-5v12L3 14v-3z",key:"n962bs"}],["path",{d:"M11.6 16.8a3 3 0 1 1-5.8-1.6",key:"1yl0tm"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const O2e=vr("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.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const R2e=vr("MessageCircleQuestion",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lu=vr("MessageCircle",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Tf=vr("MessageSquare",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const D2e=vr("Mic",[["path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z",key:"131961"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2",key:"1vc78b"}],["line",{x1:"12",x2:"12",y1:"19",y2:"22",key:"x3vr5v"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xoe=vr("Minus",[["path",{d:"M5 12h14",key:"1ays0h"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const voe=vr("Monitor",[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21",key:"1svkeh"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21",key:"vw1qmm"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const L2e=vr("Navigation",[["polygon",{points:"3 11 22 2 13 21 11 13 3 11",key:"1ltx0t"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gT=vr("Newspaper",[["path",{d:"M4 22h16a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2H8a2 2 0 0 0-2 2v16a2 2 0 0 1-2 2Zm0 0a2 2 0 0 1-2-2v-9c0-1.1.9-2 2-2h2",key:"7pis2x"}],["path",{d:"M18 14h-8",key:"sponae"}],["path",{d:"M15 18h-5",key:"95g1m2"}],["path",{d:"M10 6h8v4h-8V6Z",key:"smlsk5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const O1=vr("Package",[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 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.73z",key:"1a0edw"}],["path",{d:"M12 22V12",key:"d0xqtd"}],["path",{d:"m3.3 7 7.703 4.734a2 2 0 0 0 1.994 0L20.7 7",key:"yx3hmr"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const A_=vr("Palette",[["circle",{cx:"13.5",cy:"6.5",r:".5",fill:"currentColor",key:"1okk4w"}],["circle",{cx:"17.5",cy:"10.5",r:".5",fill:"currentColor",key:"f64h9f"}],["circle",{cx:"8.5",cy:"7.5",r:".5",fill:"currentColor",key:"fotxhn"}],["circle",{cx:"6.5",cy:"12.5",r:".5",fill:"currentColor",key:"qy21gx"}],["path",{d:"M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10c.926 0 1.648-.746 1.648-1.688 0-.437-.18-.835-.437-1.125-.29-.289-.438-.652-.438-1.125a1.64 1.64 0 0 1 1.668-1.668h1.996c3.051 0 5.555-2.503 5.555-5.554C21.965 6.012 17.461 2 12 2z",key:"12rzf8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const F2e=vr("PanelsTopLeft",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"M9 21V9",key:"1oto5p"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const k5=vr("Pause",[["rect",{x:"14",y:"4",width:"4",height:"16",rx:"1",key:"zuxfzm"}],["rect",{x:"6",y:"4",width:"4",height:"16",rx:"1",key:"1okwgv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _oe=vr("PenTool",[["path",{d:"M15.707 21.293a1 1 0 0 1-1.414 0l-1.586-1.586a1 1 0 0 1 0-1.414l5.586-5.586a1 1 0 0 1 1.414 0l1.586 1.586a1 1 0 0 1 0 1.414z",key:"nt11vn"}],["path",{d:"m18 13-1.375-6.874a1 1 0 0 0-.746-.776L3.235 2.028a1 1 0 0 0-1.207 1.207L5.35 15.879a1 1 0 0 0 .776.746L13 18",key:"15qc1e"}],["path",{d:"m2.3 2.3 7.286 7.286",key:"1wuzzi"}],["circle",{cx:"11",cy:"11",r:"2",key:"xmgehs"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const io=vr("Pencil",[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const z2e=vr("Percent",[["line",{x1:"19",x2:"5",y1:"5",y2:"19",key:"1x9vlm"}],["circle",{cx:"6.5",cy:"6.5",r:"2.5",key:"4mh3h7"}],["circle",{cx:"17.5",cy:"17.5",r:"2.5",key:"1mdrzq"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Yl=vr("Phone",[["path",{d:"M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z",key:"foiqr5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Sf=vr("Play",[["polygon",{points:"6 3 20 12 6 21 6 3",key:"1oa8hb"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Qn=vr("Plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Y6=vr("Radio",[["path",{d:"M4.9 19.1C1 15.2 1 8.8 4.9 4.9",key:"1vaf9d"}],["path",{d:"M7.8 16.2c-2.3-2.3-2.3-6.1 0-8.5",key:"u1ii0m"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}],["path",{d:"M16.2 7.8c2.3 2.3 2.3 6.1 0 8.5",key:"1j5fej"}],["path",{d:"M19.1 4.9C23 8.8 23 15.1 19.1 19",key:"10b0cb"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const boe=vr("Redo",[["path",{d:"M21 7v6h-6",key:"3ptur4"}],["path",{d:"M3 17a9 9 0 0 1 9-9 9 9 0 0 1 6 2.3l3 2.7",key:"1kgawr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const R1=vr("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.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const G2=vr("Rocket",[["path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z",key:"m3kijz"}],["path",{d:"m12 15-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z",key:"1fmvmk"}],["path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0",key:"1f8sc4"}],["path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5",key:"qeys4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const woe=vr("RotateCcw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const B2e=vr("RotateCw",[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8",key:"1p45f6"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const K2=vr("Save",[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ba=vr("Search",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Dc=vr("Send",[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const eg=vr("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.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ph=vr("Share2",[["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}],["circle",{cx:"6",cy:"12",r:"3",key:"w7nqdw"}],["circle",{cx:"18",cy:"19",r:"3",key:"1xt0gg"}],["line",{x1:"8.59",x2:"15.42",y1:"13.51",y2:"17.49",key:"47mynk"}],["line",{x1:"15.41",x2:"8.59",y1:"6.51",y2:"10.49",key:"1n3mei"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $2e=vr("Share",[["path",{d:"M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8",key:"1b2hhj"}],["polyline",{points:"16 6 12 2 8 6",key:"m901s6"}],["line",{x1:"12",x2:"12",y1:"2",y2:"15",key:"1p0rca"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const U2e=vr("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.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const n2=vr("Shield",[["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"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const V2e=vr("Smartphone",[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2",key:"1yt0o3"}],["path",{d:"M12 18h.01",key:"mhygvu"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cu=vr("Sparkles",[["path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z",key:"4pj2yx"}],["path",{d:"M20 3v4",key:"1olli1"}],["path",{d:"M22 5h-4",key:"1gvqau"}],["path",{d:"M4 17v2",key:"vumght"}],["path",{d:"M5 18H3",key:"zchphs"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const P_=vr("SquarePen",[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z",key:"ohrbg2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gM=vr("Square",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mh=vr("Star",[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z",key:"r04s7s"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const joe=vr("Tag",[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z",key:"vktsd0"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rD=vr("Target",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"6",key:"1vlfrh"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ip=vr("ThumbsUp",[["path",{d:"M7 10v12",key:"1qc93n"}],["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z",key:"emmmcr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const q2e=vr("Ticket",[["path",{d:"M2 9a3 3 0 0 1 0 6v2a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-2a3 3 0 0 1 0-6V7a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z",key:"qn84l0"}],["path",{d:"M13 5v2",key:"dyzc3o"}],["path",{d:"M13 17v2",key:"1ont0d"}],["path",{d:"M13 11v2",key:"1wjjxi"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const oi=vr("Trash2",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}],["line",{x1:"10",x2:"10",y1:"11",y2:"17",key:"1uufr5"}],["line",{x1:"14",x2:"14",y1:"11",y2:"17",key:"xtxkd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Soe=vr("TrendingDown",[["polyline",{points:"22 17 13.5 8.5 8.5 13.5 2 7",key:"1r2t7k"}],["polyline",{points:"16 17 22 17 22 11",key:"11uiuu"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const r0=vr("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.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yT=vr("TriangleAlert",[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const RF=vr("Trophy",[["path",{d:"M6 9H4.5a2.5 2.5 0 0 1 0-5H6",key:"17hqa7"}],["path",{d:"M18 9h1.5a2.5 2.5 0 0 0 0-5H18",key:"lmptdp"}],["path",{d:"M4 22h16",key:"57wxv0"}],["path",{d:"M10 14.66V17c0 .55-.47.98-.97 1.21C7.85 18.75 7 20.24 7 22",key:"1nw9bq"}],["path",{d:"M14 14.66V17c0 .55.47.98.97 1.21C16.15 18.75 17 20.24 17 22",key:"1np0yb"}],["path",{d:"M18 2H6v7a6 6 0 0 0 12 0V2Z",key:"u46fv3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Noe=vr("Undo",[["path",{d:"M3 7v6h6",key:"1v2h90"}],["path",{d:"M21 17a9 9 0 0 0-9-9 9 9 0 0 0-6 2.3L3 13",key:"1r6uu6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Vu=vr("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.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Coe=vr("UserCheck",[["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"}],["polyline",{points:"16 11 18 13 22 9",key:"1pwet4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yM=vr("UserPlus",[["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"}],["line",{x1:"19",x2:"19",y1:"8",y2:"14",key:"1bvyxn"}],["line",{x1:"22",x2:"16",y1:"11",y2:"11",key:"1shjgl"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bf=vr("User",[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _i=vr("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.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const H2e=vr("Variable",[["path",{d:"M8 21s-4-3-4-9 4-9 4-9",key:"uto9ud"}],["path",{d:"M16 3s4 3 4 9-4 9-4 9",key:"4w2vsq"}],["line",{x1:"15",x2:"9",y1:"9",y2:"15",key:"f7djnv"}],["line",{x1:"9",x2:"15",y1:"9",y2:"15",key:"1shsy8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ia=vr("Video",[["path",{d:"m16 13 5.223 3.482a.5.5 0 0 0 .777-.416V7.87a.5.5 0 0 0-.752-.432L16 10.5",key:"ftymec"}],["rect",{x:"2",y:"6",width:"14",height:"12",rx:"2",key:"158x01"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xT=vr("Wrench",[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z",key:"cbrjhi"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ni=vr("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const koe=vr("Zap",[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const W2e=vr("ZoomIn",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"11",x2:"11",y1:"8",y2:"14",key:"1vmskp"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const G2e=vr("ZoomOut",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]]),X6="-",K2e=t=>{const e=Y2e(t),{conflictingClassGroups:r,conflictingClassGroupModifiers:n}=t;return{getClassGroupId:c=>{const a=c.split(X6);return a[0]===""&&a.length!==1&&a.shift(),Toe(a,e)||Z2e(c)},getConflictingClassGroupIds:(c,a)=>{const m=r[c]||[];return a&&n[c]?[...m,...n[c]]:m}}},Toe=(t,e)=>{var c;if(t.length===0)return e.classGroupId;const r=t[0],n=e.nextPart.get(r),i=n?Toe(t.slice(1),n):void 0;if(i)return i;if(e.validators.length===0)return;const o=t.join(X6);return(c=e.validators.find(({validator:a})=>a(o)))==null?void 0:c.classGroupId},ZZ=/^\[(.+)\]$/,Z2e=t=>{if(ZZ.test(t)){const e=ZZ.exec(t)[1],r=e==null?void 0:e.substring(0,e.indexOf(":"));if(r)return"arbitrary.."+r}},Y2e=t=>{const{theme:e,prefix:r}=t,n={nextPart:new Map,validators:[]};return Q2e(Object.entries(t.classGroups),r).forEach(([o,c])=>{T5(c,n,o,e)}),n},T5=(t,e,r,n)=>{t.forEach(i=>{if(typeof i=="string"){const o=i===""?e:YZ(e,i);o.classGroupId=r;return}if(typeof i=="function"){if(X2e(i)){T5(i(n),e,r,n);return}e.validators.push({validator:i,classGroupId:r});return}Object.entries(i).forEach(([o,c])=>{T5(c,YZ(e,o),r,n)})})},YZ=(t,e)=>{let r=t;return e.split(X6).forEach(n=>{r.nextPart.has(n)||r.nextPart.set(n,{nextPart:new Map,validators:[]}),r=r.nextPart.get(n)}),r},X2e=t=>t.isThemeGetter,Q2e=(t,e)=>e?t.map(([r,n])=>{const i=n.map(o=>typeof o=="string"?e+o:typeof o=="object"?Object.fromEntries(Object.entries(o).map(([c,a])=>[e+c,a])):o);return[r,i]}):t,J2e=t=>{if(t<1)return{get:()=>{},set:()=>{}};let e=0,r=new Map,n=new Map;const i=(o,c)=>{r.set(o,c),e++,e>t&&(e=0,n=r,r=new Map)};return{get(o){let c=r.get(o);if(c!==void 0)return c;if((c=n.get(o))!==void 0)return i(o,c),c},set(o,c){r.has(o)?r.set(o,c):i(o,c)}}},Eoe="!",eke=t=>{const{separator:e,experimentalParseClassName:r}=t,n=e.length===1,i=e[0],o=e.length,c=a=>{const m=[];let g=0,_=0,j;for(let I=0;I_?j-_:void 0;return{modifiers:m,hasImportantModifier:C,baseClassName:P,maybePostfixModifierPosition:A}};return r?a=>r({className:a,parseClassName:c}):c},tke=t=>{if(t.length<=1)return t;const e=[];let r=[];return t.forEach(n=>{n[0]==="["?(e.push(...r.sort(),n),r=[]):r.push(n)}),e.push(...r.sort()),e},rke=t=>({cache:J2e(t.cacheSize),parseClassName:eke(t),...K2e(t)}),nke=/\s+/,ske=(t,e)=>{const{parseClassName:r,getClassGroupId:n,getConflictingClassGroupIds:i}=e,o=[],c=t.trim().split(nke);let a="";for(let m=c.length-1;m>=0;m-=1){const g=c[m],{modifiers:_,hasImportantModifier:j,baseClassName:N,maybePostfixModifierPosition:C}=r(g);let P=!!C,A=n(P?N.substring(0,C):N);if(!A){if(!P){a=g+(a.length>0?" "+a:a);continue}if(A=n(N),!A){a=g+(a.length>0?" "+a:a);continue}P=!1}const I=tke(_).join(":"),O=j?I+Eoe:I,R=O+A;if(o.includes(R))continue;o.push(R);const z=i(A,P);for(let W=0;W0?" "+a:a)}return a};function ike(){let t=0,e,r,n="";for(;t{if(typeof t=="string")return t;let e,r="";for(let n=0;nj(_),t());return r=rke(g),n=r.cache.get,i=r.cache.set,o=a,a(m)}function a(m){const g=n(m);if(g)return g;const _=ske(m,r);return i(m,_),_}return function(){return o(ike.apply(null,arguments))}}const Ja=t=>{const e=r=>r[t]||[];return e.isThemeGetter=!0,e},Poe=/^\[(?:([a-z-]+):)?(.+)\]$/i,oke=/^\d+\/\d+$/,lke=new Set(["px","full","screen"]),cke=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,uke=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,dke=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,hke=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,fke=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,dm=t=>e1(t)||lke.has(t)||oke.test(t),Gg=t=>Pj(t,"length",bke),e1=t=>!!t&&!Number.isNaN(Number(t)),DF=t=>Pj(t,"number",e1),cC=t=>!!t&&Number.isInteger(Number(t)),pke=t=>t.endsWith("%")&&e1(t.slice(0,-1)),Si=t=>Poe.test(t),Kg=t=>cke.test(t),mke=new Set(["length","size","percentage"]),gke=t=>Pj(t,mke,Ioe),yke=t=>Pj(t,"position",Ioe),xke=new Set(["image","url"]),vke=t=>Pj(t,xke,jke),_ke=t=>Pj(t,"",wke),uC=()=>!0,Pj=(t,e,r)=>{const n=Poe.exec(t);return n?n[1]?typeof e=="string"?n[1]===e:e.has(n[1]):r(n[2]):!1},bke=t=>uke.test(t)&&!dke.test(t),Ioe=()=>!1,wke=t=>hke.test(t),jke=t=>fke.test(t),Ske=()=>{const t=Ja("colors"),e=Ja("spacing"),r=Ja("blur"),n=Ja("brightness"),i=Ja("borderColor"),o=Ja("borderRadius"),c=Ja("borderSpacing"),a=Ja("borderWidth"),m=Ja("contrast"),g=Ja("grayscale"),_=Ja("hueRotate"),j=Ja("invert"),N=Ja("gap"),C=Ja("gradientColorStops"),P=Ja("gradientColorStopPositions"),A=Ja("inset"),I=Ja("margin"),O=Ja("opacity"),R=Ja("padding"),z=Ja("saturate"),W=Ja("scale"),V=Ja("sepia"),K=Ja("skew"),Q=Ja("space"),te=Ja("translate"),X=()=>["auto","contain","none"],ie=()=>["auto","hidden","clip","visible","scroll"],he=()=>["auto",Si,e],xe=()=>[Si,e],pe=()=>["",dm,Gg],ve=()=>["auto",e1,Si],ge=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],ke=()=>["solid","dashed","dotted","double","none"],Ce=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],Se=()=>["start","end","center","between","around","evenly","stretch"],je=()=>["","0",Si],et=()=>["auto","avoid","all","avoid-page","page","left","right","column"],bt=()=>[e1,Si];return{cacheSize:500,separator:":",theme:{colors:[uC],spacing:[dm,Gg],blur:["none","",Kg,Si],brightness:bt(),borderColor:[t],borderRadius:["none","","full",Kg,Si],borderSpacing:xe(),borderWidth:pe(),contrast:bt(),grayscale:je(),hueRotate:bt(),invert:je(),gap:xe(),gradientColorStops:[t],gradientColorStopPositions:[pke,Gg],inset:he(),margin:he(),opacity:bt(),padding:xe(),saturate:bt(),scale:bt(),sepia:je(),skew:bt(),space:xe(),translate:xe()},classGroups:{aspect:[{aspect:["auto","square","video",Si]}],container:["container"],columns:[{columns:[Kg]}],"break-after":[{"break-after":et()}],"break-before":[{"break-before":et()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...ge(),Si]}],overflow:[{overflow:ie()}],"overflow-x":[{"overflow-x":ie()}],"overflow-y":[{"overflow-y":ie()}],overscroll:[{overscroll:X()}],"overscroll-x":[{"overscroll-x":X()}],"overscroll-y":[{"overscroll-y":X()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[A]}],"inset-x":[{"inset-x":[A]}],"inset-y":[{"inset-y":[A]}],start:[{start:[A]}],end:[{end:[A]}],top:[{top:[A]}],right:[{right:[A]}],bottom:[{bottom:[A]}],left:[{left:[A]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",cC,Si]}],basis:[{basis:he()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",Si]}],grow:[{grow:je()}],shrink:[{shrink:je()}],order:[{order:["first","last","none",cC,Si]}],"grid-cols":[{"grid-cols":[uC]}],"col-start-end":[{col:["auto",{span:["full",cC,Si]},Si]}],"col-start":[{"col-start":ve()}],"col-end":[{"col-end":ve()}],"grid-rows":[{"grid-rows":[uC]}],"row-start-end":[{row:["auto",{span:[cC,Si]},Si]}],"row-start":[{"row-start":ve()}],"row-end":[{"row-end":ve()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",Si]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",Si]}],gap:[{gap:[N]}],"gap-x":[{"gap-x":[N]}],"gap-y":[{"gap-y":[N]}],"justify-content":[{justify:["normal",...Se()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...Se(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...Se(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[R]}],px:[{px:[R]}],py:[{py:[R]}],ps:[{ps:[R]}],pe:[{pe:[R]}],pt:[{pt:[R]}],pr:[{pr:[R]}],pb:[{pb:[R]}],pl:[{pl:[R]}],m:[{m:[I]}],mx:[{mx:[I]}],my:[{my:[I]}],ms:[{ms:[I]}],me:[{me:[I]}],mt:[{mt:[I]}],mr:[{mr:[I]}],mb:[{mb:[I]}],ml:[{ml:[I]}],"space-x":[{"space-x":[Q]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[Q]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",Si,e]}],"min-w":[{"min-w":[Si,e,"min","max","fit"]}],"max-w":[{"max-w":[Si,e,"none","full","min","max","fit","prose",{screen:[Kg]},Kg]}],h:[{h:[Si,e,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[Si,e,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[Si,e,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[Si,e,"auto","min","max","fit"]}],"font-size":[{text:["base",Kg,Gg]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",DF]}],"font-family":[{font:[uC]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",Si]}],"line-clamp":[{"line-clamp":["none",e1,DF]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",dm,Si]}],"list-image":[{"list-image":["none",Si]}],"list-style-type":[{list:["none","disc","decimal",Si]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[t]}],"placeholder-opacity":[{"placeholder-opacity":[O]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[t]}],"text-opacity":[{"text-opacity":[O]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...ke(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",dm,Gg]}],"underline-offset":[{"underline-offset":["auto",dm,Si]}],"text-decoration-color":[{decoration:[t]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:xe()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Si]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Si]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[O]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...ge(),yke]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",gke]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},vke]}],"bg-color":[{bg:[t]}],"gradient-from-pos":[{from:[P]}],"gradient-via-pos":[{via:[P]}],"gradient-to-pos":[{to:[P]}],"gradient-from":[{from:[C]}],"gradient-via":[{via:[C]}],"gradient-to":[{to:[C]}],rounded:[{rounded:[o]}],"rounded-s":[{"rounded-s":[o]}],"rounded-e":[{"rounded-e":[o]}],"rounded-t":[{"rounded-t":[o]}],"rounded-r":[{"rounded-r":[o]}],"rounded-b":[{"rounded-b":[o]}],"rounded-l":[{"rounded-l":[o]}],"rounded-ss":[{"rounded-ss":[o]}],"rounded-se":[{"rounded-se":[o]}],"rounded-ee":[{"rounded-ee":[o]}],"rounded-es":[{"rounded-es":[o]}],"rounded-tl":[{"rounded-tl":[o]}],"rounded-tr":[{"rounded-tr":[o]}],"rounded-br":[{"rounded-br":[o]}],"rounded-bl":[{"rounded-bl":[o]}],"border-w":[{border:[a]}],"border-w-x":[{"border-x":[a]}],"border-w-y":[{"border-y":[a]}],"border-w-s":[{"border-s":[a]}],"border-w-e":[{"border-e":[a]}],"border-w-t":[{"border-t":[a]}],"border-w-r":[{"border-r":[a]}],"border-w-b":[{"border-b":[a]}],"border-w-l":[{"border-l":[a]}],"border-opacity":[{"border-opacity":[O]}],"border-style":[{border:[...ke(),"hidden"]}],"divide-x":[{"divide-x":[a]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[a]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[O]}],"divide-style":[{divide:ke()}],"border-color":[{border:[i]}],"border-color-x":[{"border-x":[i]}],"border-color-y":[{"border-y":[i]}],"border-color-s":[{"border-s":[i]}],"border-color-e":[{"border-e":[i]}],"border-color-t":[{"border-t":[i]}],"border-color-r":[{"border-r":[i]}],"border-color-b":[{"border-b":[i]}],"border-color-l":[{"border-l":[i]}],"divide-color":[{divide:[i]}],"outline-style":[{outline:["",...ke()]}],"outline-offset":[{"outline-offset":[dm,Si]}],"outline-w":[{outline:[dm,Gg]}],"outline-color":[{outline:[t]}],"ring-w":[{ring:pe()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[t]}],"ring-opacity":[{"ring-opacity":[O]}],"ring-offset-w":[{"ring-offset":[dm,Gg]}],"ring-offset-color":[{"ring-offset":[t]}],shadow:[{shadow:["","inner","none",Kg,_ke]}],"shadow-color":[{shadow:[uC]}],opacity:[{opacity:[O]}],"mix-blend":[{"mix-blend":[...Ce(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":Ce()}],filter:[{filter:["","none"]}],blur:[{blur:[r]}],brightness:[{brightness:[n]}],contrast:[{contrast:[m]}],"drop-shadow":[{"drop-shadow":["","none",Kg,Si]}],grayscale:[{grayscale:[g]}],"hue-rotate":[{"hue-rotate":[_]}],invert:[{invert:[j]}],saturate:[{saturate:[z]}],sepia:[{sepia:[V]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[r]}],"backdrop-brightness":[{"backdrop-brightness":[n]}],"backdrop-contrast":[{"backdrop-contrast":[m]}],"backdrop-grayscale":[{"backdrop-grayscale":[g]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[_]}],"backdrop-invert":[{"backdrop-invert":[j]}],"backdrop-opacity":[{"backdrop-opacity":[O]}],"backdrop-saturate":[{"backdrop-saturate":[z]}],"backdrop-sepia":[{"backdrop-sepia":[V]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[c]}],"border-spacing-x":[{"border-spacing-x":[c]}],"border-spacing-y":[{"border-spacing-y":[c]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",Si]}],duration:[{duration:bt()}],ease:[{ease:["linear","in","out","in-out",Si]}],delay:[{delay:bt()}],animate:[{animate:["none","spin","ping","pulse","bounce",Si]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[W]}],"scale-x":[{"scale-x":[W]}],"scale-y":[{"scale-y":[W]}],rotate:[{rotate:[cC,Si]}],"translate-x":[{"translate-x":[te]}],"translate-y":[{"translate-y":[te]}],"skew-x":[{"skew-x":[K]}],"skew-y":[{"skew-y":[K]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",Si]}],accent:[{accent:["auto",t]}],appearance:[{appearance:["none","auto"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Si]}],"caret-color":[{caret:[t]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":xe()}],"scroll-mx":[{"scroll-mx":xe()}],"scroll-my":[{"scroll-my":xe()}],"scroll-ms":[{"scroll-ms":xe()}],"scroll-me":[{"scroll-me":xe()}],"scroll-mt":[{"scroll-mt":xe()}],"scroll-mr":[{"scroll-mr":xe()}],"scroll-mb":[{"scroll-mb":xe()}],"scroll-ml":[{"scroll-ml":xe()}],"scroll-p":[{"scroll-p":xe()}],"scroll-px":[{"scroll-px":xe()}],"scroll-py":[{"scroll-py":xe()}],"scroll-ps":[{"scroll-ps":xe()}],"scroll-pe":[{"scroll-pe":xe()}],"scroll-pt":[{"scroll-pt":xe()}],"scroll-pr":[{"scroll-pr":xe()}],"scroll-pb":[{"scroll-pb":xe()}],"scroll-pl":[{"scroll-pl":xe()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Si]}],fill:[{fill:[t,"none"]}],"stroke-w":[{stroke:[dm,Gg,DF]}],stroke:[{stroke:[t,"none"]}],sr:["sr-only","not-sr-only"],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]}}},Nke=ake(Ske);function ar(...t){return Nke(Ci(t))}function fc(t,e=!1){return e&&t>=1e6?`$${(t/1e6).toFixed(1)}M`:e&&t>=1e3?`$${(t/1e3).toFixed(0)}K`:new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:0}).format(t)}function XZ(t){const e=new Date(t);return new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(e)}const Cke=x2e,Moe=D.forwardRef(({className:t,...e},r)=>s.jsx(Wae,{ref:r,className:ar("fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",t),...e}));Moe.displayName=Wae.displayName;const kke=Ej("group pointer-events-auto relative flex w-full items-center justify-between space-x-4 overflow-hidden rounded-md border p-6 pr-8 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",{variants:{variant:{default:"border bg-background text-foreground",destructive:"destructive group border-destructive bg-destructive text-destructive-foreground"}},defaultVariants:{variant:"default"}}),Ooe=D.forwardRef(({className:t,variant:e,...r},n)=>s.jsx(Gae,{ref:n,className:ar(kke({variant:e}),t),...r}));Ooe.displayName=Gae.displayName;const Tke=D.forwardRef(({className:t,...e},r)=>s.jsx(Yae,{ref:r,className:ar("inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium ring-offset-background transition-colors group-[.destructive]:border-muted/40 hover:bg-secondary group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 group-[.destructive]:focus:ring-destructive disabled:pointer-events-none disabled:opacity-50",t),...e}));Tke.displayName=Yae.displayName;const Roe=D.forwardRef(({className:t,...e},r)=>s.jsx(Xae,{ref:r,className:ar("absolute right-2 top-2 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity group-hover:opacity-100 group-[.destructive]:text-red-300 hover:text-foreground group-[.destructive]:hover:text-red-50 focus:opacity-100 focus:outline-none focus:ring-2 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",t),"toast-close":"",...e,children:s.jsx(Ni,{className:"h-4 w-4"})}));Roe.displayName=Xae.displayName;const Doe=D.forwardRef(({className:t,...e},r)=>s.jsx(Kae,{ref:r,className:ar("text-sm font-semibold",t),...e}));Doe.displayName=Kae.displayName;const Loe=D.forwardRef(({className:t,...e},r)=>s.jsx(Zae,{ref:r,className:ar("text-sm opacity-90",t),...e}));Loe.displayName=Zae.displayName;function Eke(){const{toasts:t}=Ri();return s.jsxs(Cke,{children:[t.map(function({id:e,title:r,description:n,action:i,...o}){return s.jsxs(Ooe,{...o,children:[s.jsxs("div",{className:"grid gap-1",children:[r&&s.jsx(Doe,{children:r}),n&&s.jsx(Loe,{children:n})]}),i,s.jsx(Roe,{})]},e)}),s.jsx(Moe,{})]})}var QZ=["light","dark"],Ake="(prefers-color-scheme: dark)",Pke=D.createContext(void 0),Ike={setTheme:t=>{},themes:[]},Mke=()=>{var t;return(t=D.useContext(Pke))!=null?t:Ike};D.memo(({forcedTheme:t,storageKey:e,attribute:r,enableSystem:n,enableColorScheme:i,defaultTheme:o,value:c,attrs:a,nonce:m})=>{let g=o==="system",_=r==="class"?`var d=document.documentElement,c=d.classList;${`c.remove(${a.map(P=>`'${P}'`).join(",")})`};`:`var d=document.documentElement,n='${r}',s='setAttribute';`,j=i?QZ.includes(o)&&o?`if(e==='light'||e==='dark'||!e)d.style.colorScheme=e||'${o}'`:"if(e==='light'||e==='dark')d.style.colorScheme=e":"",N=(P,A=!1,I=!0)=>{let O=c?c[P]:P,R=A?P+"|| ''":`'${O}'`,z="";return i&&I&&!A&&QZ.includes(P)&&(z+=`d.style.colorScheme = '${P}';`),r==="class"?A||O?z+=`c.add(${R})`:z+="null":O&&(z+=`d[s](n,${R})`),z},C=t?`!function(){${_}${N(t)}}()`:n?`!function(){try{${_}var e=localStorage.getItem('${e}');if('system'===e||(!e&&${g})){var t='${Ake}',m=window.matchMedia(t);if(m.media!==t||m.matches){${N("dark")}}else{${N("light")}}}else if(e){${c?`var x=${JSON.stringify(c)};`:""}${N(c?"x[e]":"e",!0)}}${g?"":"else{"+N(o,!1,!1)+"}"}${j}}catch(e){}}()`:`!function(){try{${_}var e=localStorage.getItem('${e}');if(e){${c?`var x=${JSON.stringify(c)};`:""}${N(c?"x[e]":"e",!0)}}else{${N(o,!1,!1)};}${j}}catch(t){}}();`;return D.createElement("script",{nonce:m,dangerouslySetInnerHTML:{__html:C}})});var Oke=t=>{switch(t){case"success":return Lke;case"info":return zke;case"warning":return Fke;case"error":return Bke;default:return null}},Rke=Array(12).fill(0),Dke=({visible:t,className:e})=>Ve.createElement("div",{className:["sonner-loading-wrapper",e].filter(Boolean).join(" "),"data-visible":t},Ve.createElement("div",{className:"sonner-spinner"},Rke.map((r,n)=>Ve.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${n}`})))),Lke=Ve.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Ve.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),Fke=Ve.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},Ve.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),zke=Ve.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Ve.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),Bke=Ve.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Ve.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),$ke=Ve.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},Ve.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),Ve.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),Uke=()=>{let[t,e]=Ve.useState(document.hidden);return Ve.useEffect(()=>{let r=()=>{e(document.hidden)};return document.addEventListener("visibilitychange",r),()=>window.removeEventListener("visibilitychange",r)},[]),t},E5=1,Vke=class{constructor(){this.subscribe=t=>(this.subscribers.push(t),()=>{let e=this.subscribers.indexOf(t);this.subscribers.splice(e,1)}),this.publish=t=>{this.subscribers.forEach(e=>e(t))},this.addToast=t=>{this.publish(t),this.toasts=[...this.toasts,t]},this.create=t=>{var e;let{message:r,...n}=t,i=typeof(t==null?void 0:t.id)=="number"||((e=t.id)==null?void 0:e.length)>0?t.id:E5++,o=this.toasts.find(a=>a.id===i),c=t.dismissible===void 0?!0:t.dismissible;return this.dismissedToasts.has(i)&&this.dismissedToasts.delete(i),o?this.toasts=this.toasts.map(a=>a.id===i?(this.publish({...a,...t,id:i,title:r}),{...a,...t,id:i,dismissible:c,title:r}):a):this.addToast({title:r,...n,dismissible:c,id:i}),i},this.dismiss=t=>(this.dismissedToasts.add(t),t||this.toasts.forEach(e=>{this.subscribers.forEach(r=>r({id:e.id,dismiss:!0}))}),this.subscribers.forEach(e=>e({id:t,dismiss:!0})),t),this.message=(t,e)=>this.create({...e,message:t}),this.error=(t,e)=>this.create({...e,message:t,type:"error"}),this.success=(t,e)=>this.create({...e,type:"success",message:t}),this.info=(t,e)=>this.create({...e,type:"info",message:t}),this.warning=(t,e)=>this.create({...e,type:"warning",message:t}),this.loading=(t,e)=>this.create({...e,type:"loading",message:t}),this.promise=(t,e)=>{if(!e)return;let r;e.loading!==void 0&&(r=this.create({...e,promise:t,type:"loading",message:e.loading,description:typeof e.description!="function"?e.description:void 0}));let n=t instanceof Promise?t:t(),i=r!==void 0,o,c=n.then(async m=>{if(o=["resolve",m],Ve.isValidElement(m))i=!1,this.create({id:r,type:"default",message:m});else if(Hke(m)&&!m.ok){i=!1;let g=typeof e.error=="function"?await e.error(`HTTP error! status: ${m.status}`):e.error,_=typeof e.description=="function"?await e.description(`HTTP error! status: ${m.status}`):e.description;this.create({id:r,type:"error",message:g,description:_})}else if(e.success!==void 0){i=!1;let g=typeof e.success=="function"?await e.success(m):e.success,_=typeof e.description=="function"?await e.description(m):e.description;this.create({id:r,type:"success",message:g,description:_})}}).catch(async m=>{if(o=["reject",m],e.error!==void 0){i=!1;let g=typeof e.error=="function"?await e.error(m):e.error,_=typeof e.description=="function"?await e.description(m):e.description;this.create({id:r,type:"error",message:g,description:_})}}).finally(()=>{var m;i&&(this.dismiss(r),r=void 0),(m=e.finally)==null||m.call(e)}),a=()=>new Promise((m,g)=>c.then(()=>o[0]==="reject"?g(o[1]):m(o[1])).catch(g));return typeof r!="string"&&typeof r!="number"?{unwrap:a}:Object.assign(r,{unwrap:a})},this.custom=(t,e)=>{let r=(e==null?void 0:e.id)||E5++;return this.create({jsx:t(r),id:r,...e}),r},this.getActiveToasts=()=>this.toasts.filter(t=>!this.dismissedToasts.has(t.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}},Pu=new Vke,qke=(t,e)=>{let r=(e==null?void 0:e.id)||E5++;return Pu.addToast({title:t,...e,id:r}),r},Hke=t=>t&&typeof t=="object"&&"ok"in t&&typeof t.ok=="boolean"&&"status"in t&&typeof t.status=="number",Wke=qke,Gke=()=>Pu.toasts,Kke=()=>Pu.getActiveToasts(),Dt=Object.assign(Wke,{success:Pu.success,info:Pu.info,warning:Pu.warning,error:Pu.error,custom:Pu.custom,message:Pu.message,promise:Pu.promise,dismiss:Pu.dismiss,loading:Pu.loading},{getHistory:Gke,getToasts:Kke});function Zke(t,{insertAt:e}={}){if(typeof document>"u")return;let r=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.type="text/css",e==="top"&&r.firstChild?r.insertBefore(n,r.firstChild):r.appendChild(n),n.styleSheet?n.styleSheet.cssText=t:n.appendChild(document.createTextNode(t))}Zke(`:where(html[dir="ltr"]),:where([data-sonner-toaster][dir="ltr"]){--toast-icon-margin-start: -3px;--toast-icon-margin-end: 4px;--toast-svg-margin-start: -1px;--toast-svg-margin-end: 0px;--toast-button-margin-start: auto;--toast-button-margin-end: 0;--toast-close-button-start: 0;--toast-close-button-end: unset;--toast-close-button-transform: translate(-35%, -35%)}:where(html[dir="rtl"]),:where([data-sonner-toaster][dir="rtl"]){--toast-icon-margin-start: 4px;--toast-icon-margin-end: -3px;--toast-svg-margin-start: 0px;--toast-svg-margin-end: -1px;--toast-button-margin-start: 0;--toast-button-margin-end: auto;--toast-close-button-start: unset;--toast-close-button-end: 0;--toast-close-button-transform: translate(35%, -35%)}:where([data-sonner-toaster]){position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1: hsl(0, 0%, 99%);--gray2: hsl(0, 0%, 97.3%);--gray3: hsl(0, 0%, 95.1%);--gray4: hsl(0, 0%, 93%);--gray5: hsl(0, 0%, 90.9%);--gray6: hsl(0, 0%, 88.7%);--gray7: hsl(0, 0%, 85.8%);--gray8: hsl(0, 0%, 78%);--gray9: hsl(0, 0%, 56.1%);--gray10: hsl(0, 0%, 52.3%);--gray11: hsl(0, 0%, 43.5%);--gray12: hsl(0, 0%, 9%);--border-radius: 8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:none;z-index:999999999;transition:transform .4s ease}:where([data-sonner-toaster][data-lifted="true"]){transform:translateY(-10px)}@media (hover: none) and (pointer: coarse){:where([data-sonner-toaster][data-lifted="true"]){transform:none}}:where([data-sonner-toaster][data-x-position="right"]){right:var(--offset-right)}:where([data-sonner-toaster][data-x-position="left"]){left:var(--offset-left)}:where([data-sonner-toaster][data-x-position="center"]){left:50%;transform:translate(-50%)}:where([data-sonner-toaster][data-y-position="top"]){top:var(--offset-top)}:where([data-sonner-toaster][data-y-position="bottom"]){bottom:var(--offset-bottom)}:where([data-sonner-toast]){--y: translateY(100%);--lift-amount: calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);filter:blur(0);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:none;overflow-wrap:anywhere}:where([data-sonner-toast][data-styled="true"]){padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px #0000001a;width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}:where([data-sonner-toast]:focus-visible){box-shadow:0 4px 12px #0000001a,0 0 0 2px #0003}:where([data-sonner-toast][data-y-position="top"]){top:0;--y: translateY(-100%);--lift: 1;--lift-amount: calc(1 * var(--gap))}:where([data-sonner-toast][data-y-position="bottom"]){bottom:0;--y: translateY(100%);--lift: -1;--lift-amount: calc(var(--lift) * var(--gap))}:where([data-sonner-toast]) :where([data-description]){font-weight:400;line-height:1.4;color:inherit}:where([data-sonner-toast]) :where([data-title]){font-weight:500;line-height:1.5;color:inherit}:where([data-sonner-toast]) :where([data-icon]){display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}:where([data-sonner-toast][data-promise="true"]) :where([data-icon])>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}:where([data-sonner-toast]) :where([data-icon])>*{flex-shrink:0}:where([data-sonner-toast]) :where([data-icon]) svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}:where([data-sonner-toast]) :where([data-content]){display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;cursor:pointer;outline:none;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}:where([data-sonner-toast]) :where([data-button]):focus-visible{box-shadow:0 0 0 2px #0006}:where([data-sonner-toast]) :where([data-button]):first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}:where([data-sonner-toast]) :where([data-cancel]){color:var(--normal-text);background:rgba(0,0,0,.08)}:where([data-sonner-toast][data-theme="dark"]) :where([data-cancel]){background:rgba(255,255,255,.3)}:where([data-sonner-toast]) :where([data-close-button]){position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast] [data-close-button]{background:var(--gray1)}:where([data-sonner-toast]) :where([data-close-button]):focus-visible{box-shadow:0 4px 12px #0000001a,0 0 0 2px #0003}:where([data-sonner-toast]) :where([data-disabled="true"]){cursor:not-allowed}:where([data-sonner-toast]):hover :where([data-close-button]):hover{background:var(--gray2);border-color:var(--gray5)}:where([data-sonner-toast][data-swiping="true"]):before{content:"";position:absolute;left:-50%;right:-50%;height:100%;z-index:-1}:where([data-sonner-toast][data-y-position="top"][data-swiping="true"]):before{bottom:50%;transform:scaleY(3) translateY(50%)}:where([data-sonner-toast][data-y-position="bottom"][data-swiping="true"]):before{top:50%;transform:scaleY(3) translateY(-50%)}:where([data-sonner-toast][data-swiping="false"][data-removed="true"]):before{content:"";position:absolute;inset:0;transform:scaleY(2)}:where([data-sonner-toast]):after{content:"";position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}:where([data-sonner-toast][data-mounted="true"]){--y: translateY(0);opacity:1}:where([data-sonner-toast][data-expanded="false"][data-front="false"]){--scale: var(--toasts-before) * .05 + 1;--y: translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}:where([data-sonner-toast])>*{transition:opacity .4s}:where([data-sonner-toast][data-expanded="false"][data-front="false"][data-styled="true"])>*{opacity:0}:where([data-sonner-toast][data-visible="false"]){opacity:0;pointer-events:none}:where([data-sonner-toast][data-mounted="true"][data-expanded="true"]){--y: translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}:where([data-sonner-toast][data-removed="true"][data-front="true"][data-swipe-out="false"]){--y: translateY(calc(var(--lift) * -100%));opacity:0}:where([data-sonner-toast][data-removed="true"][data-front="false"][data-swipe-out="false"][data-expanded="true"]){--y: translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}:where([data-sonner-toast][data-removed="true"][data-front="false"][data-swipe-out="false"][data-expanded="false"]){--y: translateY(40%);opacity:0;transition:transform .5s,opacity .2s}:where([data-sonner-toast][data-removed="true"][data-front="false"]):before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y, 0px)) translate(var(--swipe-amount-x, 0px));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{0%{transform:var(--y) translate(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translate(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{0%{transform:var(--y) translate(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translate(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{0%{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{0%{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width: 600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-theme=light]{--normal-bg: #fff;--normal-border: var(--gray4);--normal-text: var(--gray12);--success-bg: hsl(143, 85%, 96%);--success-border: hsl(145, 92%, 91%);--success-text: hsl(140, 100%, 27%);--info-bg: hsl(208, 100%, 97%);--info-border: hsl(221, 91%, 91%);--info-text: hsl(210, 92%, 45%);--warning-bg: hsl(49, 100%, 97%);--warning-border: hsl(49, 91%, 91%);--warning-text: hsl(31, 92%, 45%);--error-bg: hsl(359, 100%, 97%);--error-border: hsl(359, 100%, 94%);--error-text: hsl(360, 100%, 45%)}[data-sonner-toaster][data-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg: #000;--normal-border: hsl(0, 0%, 20%);--normal-text: var(--gray1)}[data-sonner-toaster][data-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg: #fff;--normal-border: var(--gray3);--normal-text: var(--gray12)}[data-sonner-toaster][data-theme=dark]{--normal-bg: #000;--normal-bg-hover: hsl(0, 0%, 12%);--normal-border: hsl(0, 0%, 20%);--normal-border-hover: hsl(0, 0%, 25%);--normal-text: var(--gray1);--success-bg: hsl(150, 100%, 6%);--success-border: hsl(147, 100%, 12%);--success-text: hsl(150, 86%, 65%);--info-bg: hsl(215, 100%, 6%);--info-border: hsl(223, 100%, 12%);--info-text: hsl(216, 87%, 65%);--warning-bg: hsl(64, 100%, 6%);--warning-border: hsl(60, 100%, 12%);--warning-text: hsl(46, 87%, 65%);--error-bg: hsl(358, 76%, 10%);--error-border: hsl(357, 89%, 16%);--error-text: hsl(358, 100%, 81%)}[data-sonner-toaster][data-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success],[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info],[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning],[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error],[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size: 16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:nth-child(1){animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}to{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}to{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}to{opacity:.15}}@media (prefers-reduced-motion){[data-sonner-toast],[data-sonner-toast]>*,.sonner-loading-bar{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)} `);function pP(t){return t.label!==void 0}var Yke=3,Xke="32px",Qke="16px",JZ=4e3,Jke=356,eTe=14,tTe=20,rTe=200;function Zh(...t){return t.filter(Boolean).join(" ")}function nTe(t){let[e,r]=t.split("-"),n=[];return e&&n.push(e),r&&n.push(r),n}var sTe=t=>{var e,r,n,i,o,c,a,m,g,_,j;let{invert:N,toast:C,unstyled:P,interacting:A,setHeights:I,visibleToasts:O,heights:R,index:z,toasts:W,expanded:V,removeToast:K,defaultRichColors:Q,closeButton:te,style:X,cancelButtonStyle:ie,actionButtonStyle:he,className:xe="",descriptionClassName:pe="",duration:ve,position:ge,gap:ke,loadingIcon:Ce,expandByDefault:Se,classNames:je,icons:et,closeButtonAriaLabel:bt="Close toast",pauseWhenPageIsHidden:_e}=t,[Ye,pt]=Ve.useState(null),[nt,Qt]=Ve.useState(null),[gt,Me]=Ve.useState(!1),[Oe,Ie]=Ve.useState(!1),[Be,Pe]=Ve.useState(!1),[ut,jt]=Ve.useState(!1),[$t,Ht]=Ve.useState(!1),[Lt,Kt]=Ve.useState(0),[Ar,rt]=Ve.useState(0),We=Ve.useRef(C.duration||ve||JZ),_t=Ve.useRef(null),Gt=Ve.useRef(null),rr=z===0,pr=z+1<=O,kr=C.type,Hr=C.dismissible!==!1,Fn=C.className||"",Os=C.descriptionClassName||"",ia=Ve.useMemo(()=>R.findIndex(Ss=>Ss.toastId===C.id)||0,[R,C.id]),pa=Ve.useMemo(()=>{var Ss;return(Ss=C.closeButton)!=null?Ss:te},[C.closeButton,te]),zo=Ve.useMemo(()=>C.duration||ve||JZ,[C.duration,ve]),Xo=Ve.useRef(0),Xs=Ve.useRef(0),Ma=Ve.useRef(0),Qo=Ve.useRef(null),[ec,yl]=ge.split("-"),tc=Ve.useMemo(()=>R.reduce((Ss,bi,ki)=>ki>=ia?Ss:Ss+bi.height,0),[R,ia]),Jo=Uke(),wh=C.invert||N,xa=kr==="loading";Xs.current=Ve.useMemo(()=>ia*ke+tc,[ia,tc]),Ve.useEffect(()=>{We.current=zo},[zo]),Ve.useEffect(()=>{Me(!0)},[]),Ve.useEffect(()=>{let Ss=Gt.current;if(Ss){let bi=Ss.getBoundingClientRect().height;return rt(bi),I(ki=>[{toastId:C.id,height:bi,position:C.position},...ki]),()=>I(ki=>ki.filter(yo=>yo.toastId!==C.id))}},[I,C.id]),Ve.useLayoutEffect(()=>{if(!gt)return;let Ss=Gt.current,bi=Ss.style.height;Ss.style.height="auto";let ki=Ss.getBoundingClientRect().height;Ss.style.height=bi,rt(ki),I(yo=>yo.find(Wt=>Wt.toastId===C.id)?yo.map(Wt=>Wt.toastId===C.id?{...Wt,height:ki}:Wt):[{toastId:C.id,height:ki,position:C.position},...yo])},[gt,C.title,C.description,I,C.id]);let Qs=Ve.useCallback(()=>{Ie(!0),Kt(Xs.current),I(Ss=>Ss.filter(bi=>bi.toastId!==C.id)),setTimeout(()=>{K(C)},rTe)},[C,K,I,Xs]);Ve.useEffect(()=>{if(C.promise&&kr==="loading"||C.duration===1/0||C.type==="loading")return;let Ss;return V||A||_e&&Jo?(()=>{if(Ma.current{var bi;(bi=C.onAutoClose)==null||bi.call(C,C),Qs()},We.current)),()=>clearTimeout(Ss)},[V,A,C,kr,_e,Jo,Qs]),Ve.useEffect(()=>{C.delete&&Qs()},[Qs,C.delete]);function La(){var Ss,bi,ki;return et!=null&&et.loading?Ve.createElement("div",{className:Zh(je==null?void 0:je.loader,(Ss=C==null?void 0:C.classNames)==null?void 0:Ss.loader,"sonner-loader"),"data-visible":kr==="loading"},et.loading):Ce?Ve.createElement("div",{className:Zh(je==null?void 0:je.loader,(bi=C==null?void 0:C.classNames)==null?void 0:bi.loader,"sonner-loader"),"data-visible":kr==="loading"},Ce):Ve.createElement(Dke,{className:Zh(je==null?void 0:je.loader,(ki=C==null?void 0:C.classNames)==null?void 0:ki.loader),visible:kr==="loading"})}return Ve.createElement("li",{tabIndex:0,ref:Gt,className:Zh(xe,Fn,je==null?void 0:je.toast,(e=C==null?void 0:C.classNames)==null?void 0:e.toast,je==null?void 0:je.default,je==null?void 0:je[kr],(r=C==null?void 0:C.classNames)==null?void 0:r[kr]),"data-sonner-toast":"","data-rich-colors":(n=C.richColors)!=null?n:Q,"data-styled":!(C.jsx||C.unstyled||P),"data-mounted":gt,"data-promise":!!C.promise,"data-swiped":$t,"data-removed":Oe,"data-visible":pr,"data-y-position":ec,"data-x-position":yl,"data-index":z,"data-front":rr,"data-swiping":Be,"data-dismissible":Hr,"data-type":kr,"data-invert":wh,"data-swipe-out":ut,"data-swipe-direction":nt,"data-expanded":!!(V||Se&>),style:{"--index":z,"--toasts-before":z,"--z-index":W.length-z,"--offset":`${Oe?Lt:Xs.current}px`,"--initial-height":Se?"auto":`${Ar}px`,...X,...C.style},onDragEnd:()=>{Pe(!1),pt(null),Qo.current=null},onPointerDown:Ss=>{xa||!Hr||(_t.current=new Date,Kt(Xs.current),Ss.target.setPointerCapture(Ss.pointerId),Ss.target.tagName!=="BUTTON"&&(Pe(!0),Qo.current={x:Ss.clientX,y:Ss.clientY}))},onPointerUp:()=>{var Ss,bi,ki,yo;if(ut||!Hr)return;Qo.current=null;let Wt=Number(((Ss=Gt.current)==null?void 0:Ss.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),xo=Number(((bi=Gt.current)==null?void 0:bi.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),zc=new Date().getTime()-((ki=_t.current)==null?void 0:ki.getTime()),oo=Ye==="x"?Wt:xo,Xn=Math.abs(oo)/zc;if(Math.abs(oo)>=tTe||Xn>.11){Kt(Xs.current),(yo=C.onDismiss)==null||yo.call(C,C),Qt(Ye==="x"?Wt>0?"right":"left":xo>0?"down":"up"),Qs(),jt(!0),Ht(!1);return}Pe(!1),pt(null)},onPointerMove:Ss=>{var bi,ki,yo,Wt;if(!Qo.current||!Hr||((bi=window.getSelection())==null?void 0:bi.toString().length)>0)return;let xo=Ss.clientY-Qo.current.y,zc=Ss.clientX-Qo.current.x,oo=(ki=t.swipeDirections)!=null?ki:nTe(ge);!Ye&&(Math.abs(zc)>1||Math.abs(xo)>1)&&pt(Math.abs(zc)>Math.abs(xo)?"x":"y");let Xn={x:0,y:0};Ye==="y"?(oo.includes("top")||oo.includes("bottom"))&&(oo.includes("top")&&xo<0||oo.includes("bottom")&&xo>0)&&(Xn.y=xo):Ye==="x"&&(oo.includes("left")||oo.includes("right"))&&(oo.includes("left")&&zc<0||oo.includes("right")&&zc>0)&&(Xn.x=zc),(Math.abs(Xn.x)>0||Math.abs(Xn.y)>0)&&Ht(!0),(yo=Gt.current)==null||yo.style.setProperty("--swipe-amount-x",`${Xn.x}px`),(Wt=Gt.current)==null||Wt.style.setProperty("--swipe-amount-y",`${Xn.y}px`)}},pa&&!C.jsx?Ve.createElement("button",{"aria-label":bt,"data-disabled":xa,"data-close-button":!0,onClick:xa||!Hr?()=>{}:()=>{var Ss;Qs(),(Ss=C.onDismiss)==null||Ss.call(C,C)},className:Zh(je==null?void 0:je.closeButton,(i=C==null?void 0:C.classNames)==null?void 0:i.closeButton)},(o=et==null?void 0:et.close)!=null?o:$ke):null,C.jsx||D.isValidElement(C.title)?C.jsx?C.jsx:typeof C.title=="function"?C.title():C.title:Ve.createElement(Ve.Fragment,null,kr||C.icon||C.promise?Ve.createElement("div",{"data-icon":"",className:Zh(je==null?void 0:je.icon,(c=C==null?void 0:C.classNames)==null?void 0:c.icon)},C.promise||C.type==="loading"&&!C.icon?C.icon||La():null,C.type!=="loading"?C.icon||(et==null?void 0:et[kr])||Oke(kr):null):null,Ve.createElement("div",{"data-content":"",className:Zh(je==null?void 0:je.content,(a=C==null?void 0:C.classNames)==null?void 0:a.content)},Ve.createElement("div",{"data-title":"",className:Zh(je==null?void 0:je.title,(m=C==null?void 0:C.classNames)==null?void 0:m.title)},typeof C.title=="function"?C.title():C.title),C.description?Ve.createElement("div",{"data-description":"",className:Zh(pe,Os,je==null?void 0:je.description,(g=C==null?void 0:C.classNames)==null?void 0:g.description)},typeof C.description=="function"?C.description():C.description):null),D.isValidElement(C.cancel)?C.cancel:C.cancel&&pP(C.cancel)?Ve.createElement("button",{"data-button":!0,"data-cancel":!0,style:C.cancelButtonStyle||ie,onClick:Ss=>{var bi,ki;pP(C.cancel)&&Hr&&((ki=(bi=C.cancel).onClick)==null||ki.call(bi,Ss),Qs())},className:Zh(je==null?void 0:je.cancelButton,(_=C==null?void 0:C.classNames)==null?void 0:_.cancelButton)},C.cancel.label):null,D.isValidElement(C.action)?C.action:C.action&&pP(C.action)?Ve.createElement("button",{"data-button":!0,"data-action":!0,style:C.actionButtonStyle||he,onClick:Ss=>{var bi,ki;pP(C.action)&&((ki=(bi=C.action).onClick)==null||ki.call(bi,Ss),!Ss.defaultPrevented&&Qs())},className:Zh(je==null?void 0:je.actionButton,(j=C==null?void 0:C.classNames)==null?void 0:j.actionButton)},C.action.label):null))};function eY(){if(typeof window>"u"||typeof document>"u")return"ltr";let t=document.documentElement.getAttribute("dir");return t==="auto"||!t?window.getComputedStyle(document.documentElement).direction:t}function iTe(t,e){let r={};return[t,e].forEach((n,i)=>{let o=i===1,c=o?"--mobile-offset":"--offset",a=o?Qke:Xke;function m(g){["top","right","bottom","left"].forEach(_=>{r[`${c}-${_}`]=typeof g=="number"?`${g}px`:g})}typeof n=="number"||typeof n=="string"?m(n):typeof n=="object"?["top","right","bottom","left"].forEach(g=>{n[g]===void 0?r[`${c}-${g}`]=a:r[`${c}-${g}`]=typeof n[g]=="number"?`${n[g]}px`:n[g]}):m(a)}),r}var aTe=D.forwardRef(function(t,e){let{invert:r,position:n="bottom-right",hotkey:i=["altKey","KeyT"],expand:o,closeButton:c,className:a,offset:m,mobileOffset:g,theme:_="light",richColors:j,duration:N,style:C,visibleToasts:P=Yke,toastOptions:A,dir:I=eY(),gap:O=eTe,loadingIcon:R,icons:z,containerAriaLabel:W="Notifications",pauseWhenPageIsHidden:V}=t,[K,Q]=Ve.useState([]),te=Ve.useMemo(()=>Array.from(new Set([n].concat(K.filter(_e=>_e.position).map(_e=>_e.position)))),[K,n]),[X,ie]=Ve.useState([]),[he,xe]=Ve.useState(!1),[pe,ve]=Ve.useState(!1),[ge,ke]=Ve.useState(_!=="system"?_:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),Ce=Ve.useRef(null),Se=i.join("+").replace(/Key/g,"").replace(/Digit/g,""),je=Ve.useRef(null),et=Ve.useRef(!1),bt=Ve.useCallback(_e=>{Q(Ye=>{var pt;return(pt=Ye.find(nt=>nt.id===_e.id))!=null&&pt.delete||Pu.dismiss(_e.id),Ye.filter(({id:nt})=>nt!==_e.id)})},[]);return Ve.useEffect(()=>Pu.subscribe(_e=>{if(_e.dismiss){Q(Ye=>Ye.map(pt=>pt.id===_e.id?{...pt,delete:!0}:pt));return}setTimeout(()=>{B6.flushSync(()=>{Q(Ye=>{let pt=Ye.findIndex(nt=>nt.id===_e.id);return pt!==-1?[...Ye.slice(0,pt),{...Ye[pt],..._e},...Ye.slice(pt+1)]:[_e,...Ye]})})})}),[]),Ve.useEffect(()=>{if(_!=="system"){ke(_);return}if(_==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?ke("dark"):ke("light")),typeof window>"u")return;let _e=window.matchMedia("(prefers-color-scheme: dark)");try{_e.addEventListener("change",({matches:Ye})=>{ke(Ye?"dark":"light")})}catch{_e.addListener(({matches:pt})=>{try{ke(pt?"dark":"light")}catch(nt){console.error(nt)}})}},[_]),Ve.useEffect(()=>{K.length<=1&&xe(!1)},[K]),Ve.useEffect(()=>{let _e=Ye=>{var pt,nt;i.every(Qt=>Ye[Qt]||Ye.code===Qt)&&(xe(!0),(pt=Ce.current)==null||pt.focus()),Ye.code==="Escape"&&(document.activeElement===Ce.current||(nt=Ce.current)!=null&&nt.contains(document.activeElement))&&xe(!1)};return document.addEventListener("keydown",_e),()=>document.removeEventListener("keydown",_e)},[i]),Ve.useEffect(()=>{if(Ce.current)return()=>{je.current&&(je.current.focus({preventScroll:!0}),je.current=null,et.current=!1)}},[Ce.current]),Ve.createElement("section",{ref:e,"aria-label":`${W} ${Se}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},te.map((_e,Ye)=>{var pt;let[nt,Qt]=_e.split("-");return K.length?Ve.createElement("ol",{key:_e,dir:I==="auto"?eY():I,tabIndex:-1,ref:Ce,className:a,"data-sonner-toaster":!0,"data-theme":ge,"data-y-position":nt,"data-lifted":he&&K.length>1&&!o,"data-x-position":Qt,style:{"--front-toast-height":`${((pt=X[0])==null?void 0:pt.height)||0}px`,"--width":`${Jke}px`,"--gap":`${O}px`,...C,...iTe(m,g)},onBlur:gt=>{et.current&&!gt.currentTarget.contains(gt.relatedTarget)&&(et.current=!1,je.current&&(je.current.focus({preventScroll:!0}),je.current=null))},onFocus:gt=>{gt.target instanceof HTMLElement&>.target.dataset.dismissible==="false"||et.current||(et.current=!0,je.current=gt.relatedTarget)},onMouseEnter:()=>xe(!0),onMouseMove:()=>xe(!0),onMouseLeave:()=>{pe||xe(!1)},onDragEnd:()=>xe(!1),onPointerDown:gt=>{gt.target instanceof HTMLElement&>.target.dataset.dismissible==="false"||ve(!0)},onPointerUp:()=>ve(!1)},K.filter(gt=>!gt.position&&Ye===0||gt.position===_e).map((gt,Me)=>{var Oe,Ie;return Ve.createElement(sTe,{key:gt.id,icons:z,index:Me,toast:gt,defaultRichColors:j,duration:(Oe=A==null?void 0:A.duration)!=null?Oe:N,className:A==null?void 0:A.className,descriptionClassName:A==null?void 0:A.descriptionClassName,invert:r,visibleToasts:P,closeButton:(Ie=A==null?void 0:A.closeButton)!=null?Ie:c,interacting:pe,position:_e,style:A==null?void 0:A.style,unstyled:A==null?void 0:A.unstyled,classNames:A==null?void 0:A.classNames,cancelButtonStyle:A==null?void 0:A.cancelButtonStyle,actionButtonStyle:A==null?void 0:A.actionButtonStyle,removeToast:bt,toasts:K.filter(Be=>Be.position==gt.position),heights:X.filter(Be=>Be.position==gt.position),setHeights:ie,expandByDefault:o,gap:O,loadingIcon:R,expanded:he,pauseWhenPageIsHidden:V,swipeDirections:t.swipeDirections})})):null}))});const oTe=({...t})=>{const{theme:e="system"}=Mke();return s.jsx(aTe,{theme:e,className:"toaster group",toastOptions:{classNames:{toast:"group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",description:"group-[.toast]:text-muted-foreground",actionButton:"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",cancelButton:"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground"}},...t})};var lTe=ZV[" useId ".trim().toString()]||(()=>{}),cTe=0;function Al(t){const[e,r]=D.useState(lTe());return Lo(()=>{r(n=>n??String(cTe++))},[t]),e?`radix-${e}`:""}const uTe=["top","right","bottom","left"],ax=Math.min,ud=Math.max,xM=Math.round,mP=Math.floor,gp=t=>({x:t,y:t}),dTe={left:"right",right:"left",bottom:"top",top:"bottom"},hTe={start:"end",end:"start"};function A5(t,e,r){return ud(t,ax(e,r))}function Gm(t,e){return typeof t=="function"?t(e):t}function Km(t){return t.split("-")[0]}function Ij(t){return t.split("-")[1]}function Q6(t){return t==="x"?"y":"x"}function J6(t){return t==="y"?"height":"width"}const fTe=new Set(["top","bottom"]);function up(t){return fTe.has(Km(t))?"y":"x"}function e8(t){return Q6(up(t))}function pTe(t,e,r){r===void 0&&(r=!1);const n=Ij(t),i=e8(t),o=J6(i);let c=i==="x"?n===(r?"end":"start")?"right":"left":n==="start"?"bottom":"top";return e.reference[o]>e.floating[o]&&(c=vM(c)),[c,vM(c)]}function mTe(t){const e=vM(t);return[P5(t),e,P5(e)]}function P5(t){return t.replace(/start|end/g,e=>hTe[e])}const tY=["left","right"],rY=["right","left"],gTe=["top","bottom"],yTe=["bottom","top"];function xTe(t,e,r){switch(t){case"top":case"bottom":return r?e?rY:tY:e?tY:rY;case"left":case"right":return e?gTe:yTe;default:return[]}}function vTe(t,e,r,n){const i=Ij(t);let o=xTe(Km(t),r==="start",n);return i&&(o=o.map(c=>c+"-"+i),e&&(o=o.concat(o.map(P5)))),o}function vM(t){return t.replace(/left|right|bottom|top/g,e=>dTe[e])}function _Te(t){return{top:0,right:0,bottom:0,left:0,...t}}function Foe(t){return typeof t!="number"?_Te(t):{top:t,right:t,bottom:t,left:t}}function _M(t){const{x:e,y:r,width:n,height:i}=t;return{width:n,height:i,top:r,left:e,right:e+n,bottom:r+i,x:e,y:r}}function nY(t,e,r){let{reference:n,floating:i}=t;const o=up(e),c=e8(e),a=J6(c),m=Km(e),g=o==="y",_=n.x+n.width/2-i.width/2,j=n.y+n.height/2-i.height/2,N=n[a]/2-i[a]/2;let C;switch(m){case"top":C={x:_,y:n.y-i.height};break;case"bottom":C={x:_,y:n.y+n.height};break;case"right":C={x:n.x+n.width,y:j};break;case"left":C={x:n.x-i.width,y:j};break;default:C={x:n.x,y:n.y}}switch(Ij(e)){case"start":C[c]-=N*(r&&g?-1:1);break;case"end":C[c]+=N*(r&&g?-1:1);break}return C}const bTe=async(t,e,r)=>{const{placement:n="bottom",strategy:i="absolute",middleware:o=[],platform:c}=r,a=o.filter(Boolean),m=await(c.isRTL==null?void 0:c.isRTL(e));let g=await c.getElementRects({reference:t,floating:e,strategy:i}),{x:_,y:j}=nY(g,n,m),N=n,C={},P=0;for(let A=0;A({name:"arrow",options:t,async fn(e){const{x:r,y:n,placement:i,rects:o,platform:c,elements:a,middlewareData:m}=e,{element:g,padding:_=0}=Gm(t,e)||{};if(g==null)return{};const j=Foe(_),N={x:r,y:n},C=e8(i),P=J6(C),A=await c.getDimensions(g),I=C==="y",O=I?"top":"left",R=I?"bottom":"right",z=I?"clientHeight":"clientWidth",W=o.reference[P]+o.reference[C]-N[C]-o.floating[P],V=N[C]-o.reference[C],K=await(c.getOffsetParent==null?void 0:c.getOffsetParent(g));let Q=K?K[z]:0;(!Q||!await(c.isElement==null?void 0:c.isElement(K)))&&(Q=a.floating[z]||o.floating[P]);const te=W/2-V/2,X=Q/2-A[P]/2-1,ie=ax(j[O],X),he=ax(j[R],X),xe=ie,pe=Q-A[P]-he,ve=Q/2-A[P]/2+te,ge=A5(xe,ve,pe),ke=!m.arrow&&Ij(i)!=null&&ve!==ge&&o.reference[P]/2-(veve<=0)){var he,xe;const ve=(((he=o.flip)==null?void 0:he.index)||0)+1,ge=Q[ve];if(ge&&(!(j==="alignment"?R!==up(ge):!1)||ie.every(Se=>Se.overflows[0]>0&&up(Se.placement)===R)))return{data:{index:ve,overflows:ie},reset:{placement:ge}};let ke=(xe=ie.filter(Ce=>Ce.overflows[0]<=0).sort((Ce,Se)=>Ce.overflows[1]-Se.overflows[1])[0])==null?void 0:xe.placement;if(!ke)switch(C){case"bestFit":{var pe;const Ce=(pe=ie.filter(Se=>{if(K){const je=up(Se.placement);return je===R||je==="y"}return!0}).map(Se=>[Se.placement,Se.overflows.filter(je=>je>0).reduce((je,et)=>je+et,0)]).sort((Se,je)=>Se[1]-je[1])[0])==null?void 0:pe[0];Ce&&(ke=Ce);break}case"initialPlacement":ke=a;break}if(i!==ke)return{reset:{placement:ke}}}return{}}}};function sY(t,e){return{top:t.top-e.height,right:t.right-e.width,bottom:t.bottom-e.height,left:t.left-e.width}}function iY(t){return uTe.some(e=>t[e]>=0)}const STe=function(t){return t===void 0&&(t={}),{name:"hide",options:t,async fn(e){const{rects:r}=e,{strategy:n="referenceHidden",...i}=Gm(t,e);switch(n){case"referenceHidden":{const o=await Z2(e,{...i,elementContext:"reference"}),c=sY(o,r.reference);return{data:{referenceHiddenOffsets:c,referenceHidden:iY(c)}}}case"escaped":{const o=await Z2(e,{...i,altBoundary:!0}),c=sY(o,r.floating);return{data:{escapedOffsets:c,escaped:iY(c)}}}default:return{}}}}},zoe=new Set(["left","top"]);async function NTe(t,e){const{placement:r,platform:n,elements:i}=t,o=await(n.isRTL==null?void 0:n.isRTL(i.floating)),c=Km(r),a=Ij(r),m=up(r)==="y",g=zoe.has(c)?-1:1,_=o&&m?-1:1,j=Gm(e,t);let{mainAxis:N,crossAxis:C,alignmentAxis:P}=typeof j=="number"?{mainAxis:j,crossAxis:0,alignmentAxis:null}:{mainAxis:j.mainAxis||0,crossAxis:j.crossAxis||0,alignmentAxis:j.alignmentAxis};return a&&typeof P=="number"&&(C=a==="end"?P*-1:P),m?{x:C*_,y:N*g}:{x:N*g,y:C*_}}const CTe=function(t){return t===void 0&&(t=0),{name:"offset",options:t,async fn(e){var r,n;const{x:i,y:o,placement:c,middlewareData:a}=e,m=await NTe(e,t);return c===((r=a.offset)==null?void 0:r.placement)&&(n=a.arrow)!=null&&n.alignmentOffset?{}:{x:i+m.x,y:o+m.y,data:{...m,placement:c}}}}},kTe=function(t){return t===void 0&&(t={}),{name:"shift",options:t,async fn(e){const{x:r,y:n,placement:i}=e,{mainAxis:o=!0,crossAxis:c=!1,limiter:a={fn:I=>{let{x:O,y:R}=I;return{x:O,y:R}}},...m}=Gm(t,e),g={x:r,y:n},_=await Z2(e,m),j=up(Km(i)),N=Q6(j);let C=g[N],P=g[j];if(o){const I=N==="y"?"top":"left",O=N==="y"?"bottom":"right",R=C+_[I],z=C-_[O];C=A5(R,C,z)}if(c){const I=j==="y"?"top":"left",O=j==="y"?"bottom":"right",R=P+_[I],z=P-_[O];P=A5(R,P,z)}const A=a.fn({...e,[N]:C,[j]:P});return{...A,data:{x:A.x-r,y:A.y-n,enabled:{[N]:o,[j]:c}}}}}},TTe=function(t){return t===void 0&&(t={}),{options:t,fn(e){const{x:r,y:n,placement:i,rects:o,middlewareData:c}=e,{offset:a=0,mainAxis:m=!0,crossAxis:g=!0}=Gm(t,e),_={x:r,y:n},j=up(i),N=Q6(j);let C=_[N],P=_[j];const A=Gm(a,e),I=typeof A=="number"?{mainAxis:A,crossAxis:0}:{mainAxis:0,crossAxis:0,...A};if(m){const z=N==="y"?"height":"width",W=o.reference[N]-o.floating[z]+I.mainAxis,V=o.reference[N]+o.reference[z]-I.mainAxis;CV&&(C=V)}if(g){var O,R;const z=N==="y"?"width":"height",W=zoe.has(Km(i)),V=o.reference[j]-o.floating[z]+(W&&((O=c.offset)==null?void 0:O[j])||0)+(W?0:I.crossAxis),K=o.reference[j]+o.reference[z]+(W?0:((R=c.offset)==null?void 0:R[j])||0)-(W?I.crossAxis:0);PK&&(P=K)}return{[N]:C,[j]:P}}}},ETe=function(t){return t===void 0&&(t={}),{name:"size",options:t,async fn(e){var r,n;const{placement:i,rects:o,platform:c,elements:a}=e,{apply:m=()=>{},...g}=Gm(t,e),_=await Z2(e,g),j=Km(i),N=Ij(i),C=up(i)==="y",{width:P,height:A}=o.floating;let I,O;j==="top"||j==="bottom"?(I=j,O=N===(await(c.isRTL==null?void 0:c.isRTL(a.floating))?"start":"end")?"left":"right"):(O=j,I=N==="end"?"top":"bottom");const R=A-_.top-_.bottom,z=P-_.left-_.right,W=ax(A-_[I],R),V=ax(P-_[O],z),K=!e.middlewareData.shift;let Q=W,te=V;if((r=e.middlewareData.shift)!=null&&r.enabled.x&&(te=z),(n=e.middlewareData.shift)!=null&&n.enabled.y&&(Q=R),K&&!N){const ie=ud(_.left,0),he=ud(_.right,0),xe=ud(_.top,0),pe=ud(_.bottom,0);C?te=P-2*(ie!==0||he!==0?ie+he:ud(_.left,_.right)):Q=A-2*(xe!==0||pe!==0?xe+pe:ud(_.top,_.bottom))}await m({...e,availableWidth:te,availableHeight:Q});const X=await c.getDimensions(a.floating);return P!==X.width||A!==X.height?{reset:{rects:!0}}:{}}}};function nD(){return typeof window<"u"}function Mj(t){return Boe(t)?(t.nodeName||"").toLowerCase():"#document"}function xd(t){var e;return(t==null||(e=t.ownerDocument)==null?void 0:e.defaultView)||window}function Mp(t){var e;return(e=(Boe(t)?t.ownerDocument:t.document)||window.document)==null?void 0:e.documentElement}function Boe(t){return nD()?t instanceof Node||t instanceof xd(t).Node:!1}function Nf(t){return nD()?t instanceof Element||t instanceof xd(t).Element:!1}function jp(t){return nD()?t instanceof HTMLElement||t instanceof xd(t).HTMLElement:!1}function aY(t){return!nD()||typeof ShadowRoot>"u"?!1:t instanceof ShadowRoot||t instanceof xd(t).ShadowRoot}const ATe=new Set(["inline","contents"]);function vT(t){const{overflow:e,overflowX:r,overflowY:n,display:i}=Cf(t);return/auto|scroll|overlay|hidden|clip/.test(e+n+r)&&!ATe.has(i)}const PTe=new Set(["table","td","th"]);function ITe(t){return PTe.has(Mj(t))}const MTe=[":popover-open",":modal"];function sD(t){return MTe.some(e=>{try{return t.matches(e)}catch{return!1}})}const OTe=["transform","translate","scale","rotate","perspective"],RTe=["transform","translate","scale","rotate","perspective","filter"],DTe=["paint","layout","strict","content"];function t8(t){const e=r8(),r=Nf(t)?Cf(t):t;return OTe.some(n=>r[n]?r[n]!=="none":!1)||(r.containerType?r.containerType!=="normal":!1)||!e&&(r.backdropFilter?r.backdropFilter!=="none":!1)||!e&&(r.filter?r.filter!=="none":!1)||RTe.some(n=>(r.willChange||"").includes(n))||DTe.some(n=>(r.contain||"").includes(n))}function LTe(t){let e=ox(t);for(;jp(e)&&!D1(e);){if(t8(e))return e;if(sD(e))return null;e=ox(e)}return null}function r8(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const FTe=new Set(["html","body","#document"]);function D1(t){return FTe.has(Mj(t))}function Cf(t){return xd(t).getComputedStyle(t)}function iD(t){return Nf(t)?{scrollLeft:t.scrollLeft,scrollTop:t.scrollTop}:{scrollLeft:t.scrollX,scrollTop:t.scrollY}}function ox(t){if(Mj(t)==="html")return t;const e=t.assignedSlot||t.parentNode||aY(t)&&t.host||Mp(t);return aY(e)?e.host:e}function $oe(t){const e=ox(t);return D1(e)?t.ownerDocument?t.ownerDocument.body:t.body:jp(e)&&vT(e)?e:$oe(e)}function Y2(t,e,r){var n;e===void 0&&(e=[]),r===void 0&&(r=!0);const i=$oe(t),o=i===((n=t.ownerDocument)==null?void 0:n.body),c=xd(i);if(o){const a=I5(c);return e.concat(c,c.visualViewport||[],vT(i)?i:[],a&&r?Y2(a):[])}return e.concat(i,Y2(i,[],r))}function I5(t){return t.parent&&Object.getPrototypeOf(t.parent)?t.frameElement:null}function Uoe(t){const e=Cf(t);let r=parseFloat(e.width)||0,n=parseFloat(e.height)||0;const i=jp(t),o=i?t.offsetWidth:r,c=i?t.offsetHeight:n,a=xM(r)!==o||xM(n)!==c;return a&&(r=o,n=c),{width:r,height:n,$:a}}function n8(t){return Nf(t)?t:t.contextElement}function t1(t){const e=n8(t);if(!jp(e))return gp(1);const r=e.getBoundingClientRect(),{width:n,height:i,$:o}=Uoe(e);let c=(o?xM(r.width):r.width)/n,a=(o?xM(r.height):r.height)/i;return(!c||!Number.isFinite(c))&&(c=1),(!a||!Number.isFinite(a))&&(a=1),{x:c,y:a}}const zTe=gp(0);function Voe(t){const e=xd(t);return!r8()||!e.visualViewport?zTe:{x:e.visualViewport.offsetLeft,y:e.visualViewport.offsetTop}}function BTe(t,e,r){return e===void 0&&(e=!1),!r||e&&r!==xd(t)?!1:e}function I_(t,e,r,n){e===void 0&&(e=!1),r===void 0&&(r=!1);const i=t.getBoundingClientRect(),o=n8(t);let c=gp(1);e&&(n?Nf(n)&&(c=t1(n)):c=t1(t));const a=BTe(o,r,n)?Voe(o):gp(0);let m=(i.left+a.x)/c.x,g=(i.top+a.y)/c.y,_=i.width/c.x,j=i.height/c.y;if(o){const N=xd(o),C=n&&Nf(n)?xd(n):n;let P=N,A=I5(P);for(;A&&n&&C!==P;){const I=t1(A),O=A.getBoundingClientRect(),R=Cf(A),z=O.left+(A.clientLeft+parseFloat(R.paddingLeft))*I.x,W=O.top+(A.clientTop+parseFloat(R.paddingTop))*I.y;m*=I.x,g*=I.y,_*=I.x,j*=I.y,m+=z,g+=W,P=xd(A),A=I5(P)}}return _M({width:_,height:j,x:m,y:g})}function s8(t,e){const r=iD(t).scrollLeft;return e?e.left+r:I_(Mp(t)).left+r}function qoe(t,e,r){r===void 0&&(r=!1);const n=t.getBoundingClientRect(),i=n.left+e.scrollLeft-(r?0:s8(t,n)),o=n.top+e.scrollTop;return{x:i,y:o}}function $Te(t){let{elements:e,rect:r,offsetParent:n,strategy:i}=t;const o=i==="fixed",c=Mp(n),a=e?sD(e.floating):!1;if(n===c||a&&o)return r;let m={scrollLeft:0,scrollTop:0},g=gp(1);const _=gp(0),j=jp(n);if((j||!j&&!o)&&((Mj(n)!=="body"||vT(c))&&(m=iD(n)),jp(n))){const C=I_(n);g=t1(n),_.x=C.x+n.clientLeft,_.y=C.y+n.clientTop}const N=c&&!j&&!o?qoe(c,m,!0):gp(0);return{width:r.width*g.x,height:r.height*g.y,x:r.x*g.x-m.scrollLeft*g.x+_.x+N.x,y:r.y*g.y-m.scrollTop*g.y+_.y+N.y}}function UTe(t){return Array.from(t.getClientRects())}function VTe(t){const e=Mp(t),r=iD(t),n=t.ownerDocument.body,i=ud(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),o=ud(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight);let c=-r.scrollLeft+s8(t);const a=-r.scrollTop;return Cf(n).direction==="rtl"&&(c+=ud(e.clientWidth,n.clientWidth)-i),{width:i,height:o,x:c,y:a}}function qTe(t,e){const r=xd(t),n=Mp(t),i=r.visualViewport;let o=n.clientWidth,c=n.clientHeight,a=0,m=0;if(i){o=i.width,c=i.height;const g=r8();(!g||g&&e==="fixed")&&(a=i.offsetLeft,m=i.offsetTop)}return{width:o,height:c,x:a,y:m}}const HTe=new Set(["absolute","fixed"]);function WTe(t,e){const r=I_(t,!0,e==="fixed"),n=r.top+t.clientTop,i=r.left+t.clientLeft,o=jp(t)?t1(t):gp(1),c=t.clientWidth*o.x,a=t.clientHeight*o.y,m=i*o.x,g=n*o.y;return{width:c,height:a,x:m,y:g}}function oY(t,e,r){let n;if(e==="viewport")n=qTe(t,r);else if(e==="document")n=VTe(Mp(t));else if(Nf(e))n=WTe(e,r);else{const i=Voe(t);n={x:e.x-i.x,y:e.y-i.y,width:e.width,height:e.height}}return _M(n)}function Hoe(t,e){const r=ox(t);return r===e||!Nf(r)||D1(r)?!1:Cf(r).position==="fixed"||Hoe(r,e)}function GTe(t,e){const r=e.get(t);if(r)return r;let n=Y2(t,[],!1).filter(a=>Nf(a)&&Mj(a)!=="body"),i=null;const o=Cf(t).position==="fixed";let c=o?ox(t):t;for(;Nf(c)&&!D1(c);){const a=Cf(c),m=t8(c);!m&&a.position==="fixed"&&(i=null),(o?!m&&!i:!m&&a.position==="static"&&!!i&&HTe.has(i.position)||vT(c)&&!m&&Hoe(t,c))?n=n.filter(_=>_!==c):i=a,c=ox(c)}return e.set(t,n),n}function KTe(t){let{element:e,boundary:r,rootBoundary:n,strategy:i}=t;const c=[...r==="clippingAncestors"?sD(e)?[]:GTe(e,this._c):[].concat(r),n],a=c[0],m=c.reduce((g,_)=>{const j=oY(e,_,i);return g.top=ud(j.top,g.top),g.right=ax(j.right,g.right),g.bottom=ax(j.bottom,g.bottom),g.left=ud(j.left,g.left),g},oY(e,a,i));return{width:m.right-m.left,height:m.bottom-m.top,x:m.left,y:m.top}}function ZTe(t){const{width:e,height:r}=Uoe(t);return{width:e,height:r}}function YTe(t,e,r){const n=jp(e),i=Mp(e),o=r==="fixed",c=I_(t,!0,o,e);let a={scrollLeft:0,scrollTop:0};const m=gp(0);function g(){m.x=s8(i)}if(n||!n&&!o)if((Mj(e)!=="body"||vT(i))&&(a=iD(e)),n){const C=I_(e,!0,o,e);m.x=C.x+e.clientLeft,m.y=C.y+e.clientTop}else i&&g();o&&!n&&i&&g();const _=i&&!n&&!o?qoe(i,a):gp(0),j=c.left+a.scrollLeft-m.x-_.x,N=c.top+a.scrollTop-m.y-_.y;return{x:j,y:N,width:c.width,height:c.height}}function LF(t){return Cf(t).position==="static"}function lY(t,e){if(!jp(t)||Cf(t).position==="fixed")return null;if(e)return e(t);let r=t.offsetParent;return Mp(t)===r&&(r=r.ownerDocument.body),r}function Woe(t,e){const r=xd(t);if(sD(t))return r;if(!jp(t)){let i=ox(t);for(;i&&!D1(i);){if(Nf(i)&&!LF(i))return i;i=ox(i)}return r}let n=lY(t,e);for(;n&&ITe(n)&&LF(n);)n=lY(n,e);return n&&D1(n)&&LF(n)&&!t8(n)?r:n||LTe(t)||r}const XTe=async function(t){const e=this.getOffsetParent||Woe,r=this.getDimensions,n=await r(t.floating);return{reference:YTe(t.reference,await e(t.floating),t.strategy),floating:{x:0,y:0,width:n.width,height:n.height}}};function QTe(t){return Cf(t).direction==="rtl"}const JTe={convertOffsetParentRelativeRectToViewportRelativeRect:$Te,getDocumentElement:Mp,getClippingRect:KTe,getOffsetParent:Woe,getElementRects:XTe,getClientRects:UTe,getDimensions:ZTe,getScale:t1,isElement:Nf,isRTL:QTe};function Goe(t,e){return t.x===e.x&&t.y===e.y&&t.width===e.width&&t.height===e.height}function eEe(t,e){let r=null,n;const i=Mp(t);function o(){var a;clearTimeout(n),(a=r)==null||a.disconnect(),r=null}function c(a,m){a===void 0&&(a=!1),m===void 0&&(m=1),o();const g=t.getBoundingClientRect(),{left:_,top:j,width:N,height:C}=g;if(a||e(),!N||!C)return;const P=mP(j),A=mP(i.clientWidth-(_+N)),I=mP(i.clientHeight-(j+C)),O=mP(_),z={rootMargin:-P+"px "+-A+"px "+-I+"px "+-O+"px",threshold:ud(0,ax(1,m))||1};let W=!0;function V(K){const Q=K[0].intersectionRatio;if(Q!==m){if(!W)return c();Q?c(!1,Q):n=setTimeout(()=>{c(!1,1e-7)},1e3)}Q===1&&!Goe(g,t.getBoundingClientRect())&&c(),W=!1}try{r=new IntersectionObserver(V,{...z,root:i.ownerDocument})}catch{r=new IntersectionObserver(V,z)}r.observe(t)}return c(!0),o}function tEe(t,e,r,n){n===void 0&&(n={});const{ancestorScroll:i=!0,ancestorResize:o=!0,elementResize:c=typeof ResizeObserver=="function",layoutShift:a=typeof IntersectionObserver=="function",animationFrame:m=!1}=n,g=n8(t),_=i||o?[...g?Y2(g):[],...Y2(e)]:[];_.forEach(O=>{i&&O.addEventListener("scroll",r,{passive:!0}),o&&O.addEventListener("resize",r)});const j=g&&a?eEe(g,r):null;let N=-1,C=null;c&&(C=new ResizeObserver(O=>{let[R]=O;R&&R.target===g&&C&&(C.unobserve(e),cancelAnimationFrame(N),N=requestAnimationFrame(()=>{var z;(z=C)==null||z.observe(e)})),r()}),g&&!m&&C.observe(g),C.observe(e));let P,A=m?I_(t):null;m&&I();function I(){const O=I_(t);A&&!Goe(A,O)&&r(),A=O,P=requestAnimationFrame(I)}return r(),()=>{var O;_.forEach(R=>{i&&R.removeEventListener("scroll",r),o&&R.removeEventListener("resize",r)}),j==null||j(),(O=C)==null||O.disconnect(),C=null,m&&cancelAnimationFrame(P)}}const rEe=CTe,nEe=kTe,sEe=jTe,iEe=ETe,aEe=STe,cY=wTe,oEe=TTe,lEe=(t,e,r)=>{const n=new Map,i={platform:JTe,...r},o={...i.platform,_c:n};return bTe(t,e,{...i,platform:o})};var cEe=typeof document<"u",uEe=function(){},jI=cEe?D.useLayoutEffect:uEe;function bM(t,e){if(t===e)return!0;if(typeof t!=typeof e)return!1;if(typeof t=="function"&&t.toString()===e.toString())return!0;let r,n,i;if(t&&e&&typeof t=="object"){if(Array.isArray(t)){if(r=t.length,r!==e.length)return!1;for(n=r;n--!==0;)if(!bM(t[n],e[n]))return!1;return!0}if(i=Object.keys(t),r=i.length,r!==Object.keys(e).length)return!1;for(n=r;n--!==0;)if(!{}.hasOwnProperty.call(e,i[n]))return!1;for(n=r;n--!==0;){const o=i[n];if(!(o==="_owner"&&t.$$typeof)&&!bM(t[o],e[o]))return!1}return!0}return t!==t&&e!==e}function Koe(t){return typeof window>"u"?1:(t.ownerDocument.defaultView||window).devicePixelRatio||1}function uY(t,e){const r=Koe(t);return Math.round(e*r)/r}function FF(t){const e=D.useRef(t);return jI(()=>{e.current=t}),e}function dEe(t){t===void 0&&(t={});const{placement:e="bottom",strategy:r="absolute",middleware:n=[],platform:i,elements:{reference:o,floating:c}={},transform:a=!0,whileElementsMounted:m,open:g}=t,[_,j]=D.useState({x:0,y:0,strategy:r,placement:e,middlewareData:{},isPositioned:!1}),[N,C]=D.useState(n);bM(N,n)||C(n);const[P,A]=D.useState(null),[I,O]=D.useState(null),R=D.useCallback(Se=>{Se!==K.current&&(K.current=Se,A(Se))},[]),z=D.useCallback(Se=>{Se!==Q.current&&(Q.current=Se,O(Se))},[]),W=o||P,V=c||I,K=D.useRef(null),Q=D.useRef(null),te=D.useRef(_),X=m!=null,ie=FF(m),he=FF(i),xe=FF(g),pe=D.useCallback(()=>{if(!K.current||!Q.current)return;const Se={placement:e,strategy:r,middleware:N};he.current&&(Se.platform=he.current),lEe(K.current,Q.current,Se).then(je=>{const et={...je,isPositioned:xe.current!==!1};ve.current&&!bM(te.current,et)&&(te.current=et,e0.flushSync(()=>{j(et)}))})},[N,e,r,he,xe]);jI(()=>{g===!1&&te.current.isPositioned&&(te.current.isPositioned=!1,j(Se=>({...Se,isPositioned:!1})))},[g]);const ve=D.useRef(!1);jI(()=>(ve.current=!0,()=>{ve.current=!1}),[]),jI(()=>{if(W&&(K.current=W),V&&(Q.current=V),W&&V){if(ie.current)return ie.current(W,V,pe);pe()}},[W,V,pe,ie,X]);const ge=D.useMemo(()=>({reference:K,floating:Q,setReference:R,setFloating:z}),[R,z]),ke=D.useMemo(()=>({reference:W,floating:V}),[W,V]),Ce=D.useMemo(()=>{const Se={position:r,left:0,top:0};if(!ke.floating)return Se;const je=uY(ke.floating,_.x),et=uY(ke.floating,_.y);return a?{...Se,transform:"translate("+je+"px, "+et+"px)",...Koe(ke.floating)>=1.5&&{willChange:"transform"}}:{position:r,left:je,top:et}},[r,a,ke.floating,_.x,_.y]);return D.useMemo(()=>({..._,update:pe,refs:ge,elements:ke,floatingStyles:Ce}),[_,pe,ge,ke,Ce])}const hEe=t=>{function e(r){return{}.hasOwnProperty.call(r,"current")}return{name:"arrow",options:t,fn(r){const{element:n,padding:i}=typeof t=="function"?t(r):t;return n&&e(n)?n.current!=null?cY({element:n.current,padding:i}).fn(r):{}:n?cY({element:n,padding:i}).fn(r):{}}}},fEe=(t,e)=>({...rEe(t),options:[t,e]}),pEe=(t,e)=>({...nEe(t),options:[t,e]}),mEe=(t,e)=>({...oEe(t),options:[t,e]}),gEe=(t,e)=>({...sEe(t),options:[t,e]}),yEe=(t,e)=>({...iEe(t),options:[t,e]}),xEe=(t,e)=>({...aEe(t),options:[t,e]}),vEe=(t,e)=>({...hEe(t),options:[t,e]});var _Ee="Arrow",Zoe=D.forwardRef((t,e)=>{const{children:r,width:n=10,height:i=5,...o}=t;return s.jsx(yn.svg,{...o,ref:e,width:n,height:i,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:t.asChild?r:s.jsx("polygon",{points:"0,0 30,0 15,10"})})});Zoe.displayName=_Ee;var bEe=Zoe;function _T(t){const[e,r]=D.useState(void 0);return Lo(()=>{if(t){r({width:t.offsetWidth,height:t.offsetHeight});const n=new ResizeObserver(i=>{if(!Array.isArray(i)||!i.length)return;const o=i[0];let c,a;if("borderBoxSize"in o){const m=o.borderBoxSize,g=Array.isArray(m)?m[0]:m;c=g.inlineSize,a=g.blockSize}else c=t.offsetWidth,a=t.offsetHeight;r({width:c,height:a})});return n.observe(t,{box:"border-box"}),()=>n.unobserve(t)}else r(void 0)},[t]),e}var i8="Popper",[Yoe,gx]=Yo(i8),[wEe,Xoe]=Yoe(i8),Qoe=t=>{const{__scopePopper:e,children:r}=t,[n,i]=D.useState(null);return s.jsx(wEe,{scope:e,anchor:n,onAnchorChange:i,children:r})};Qoe.displayName=i8;var Joe="PopperAnchor",ele=D.forwardRef((t,e)=>{const{__scopePopper:r,virtualRef:n,...i}=t,o=Xoe(Joe,r),c=D.useRef(null),a=vs(e,c);return D.useEffect(()=>{o.onAnchorChange((n==null?void 0:n.current)||c.current)}),n?null:s.jsx(yn.div,{...i,ref:a})});ele.displayName=Joe;var a8="PopperContent",[jEe,SEe]=Yoe(a8),tle=D.forwardRef((t,e)=>{var gt,Me,Oe,Ie,Be,Pe;const{__scopePopper:r,side:n="bottom",sideOffset:i=0,align:o="center",alignOffset:c=0,arrowPadding:a=0,avoidCollisions:m=!0,collisionBoundary:g=[],collisionPadding:_=0,sticky:j="partial",hideWhenDetached:N=!1,updatePositionStrategy:C="optimized",onPlaced:P,...A}=t,I=Xoe(a8,r),[O,R]=D.useState(null),z=vs(e,ut=>R(ut)),[W,V]=D.useState(null),K=_T(W),Q=(K==null?void 0:K.width)??0,te=(K==null?void 0:K.height)??0,X=n+(o!=="center"?"-"+o:""),ie=typeof _=="number"?_:{top:0,right:0,bottom:0,left:0,..._},he=Array.isArray(g)?g:[g],xe=he.length>0,pe={padding:ie,boundary:he.filter(CEe),altBoundary:xe},{refs:ve,floatingStyles:ge,placement:ke,isPositioned:Ce,middlewareData:Se}=dEe({strategy:"fixed",placement:X,whileElementsMounted:(...ut)=>tEe(...ut,{animationFrame:C==="always"}),elements:{reference:I.anchor},middleware:[fEe({mainAxis:i+te,alignmentAxis:c}),m&&pEe({mainAxis:!0,crossAxis:!1,limiter:j==="partial"?mEe():void 0,...pe}),m&&gEe({...pe}),yEe({...pe,apply:({elements:ut,rects:jt,availableWidth:$t,availableHeight:Ht})=>{const{width:Lt,height:Kt}=jt.reference,Ar=ut.floating.style;Ar.setProperty("--radix-popper-available-width",`${$t}px`),Ar.setProperty("--radix-popper-available-height",`${Ht}px`),Ar.setProperty("--radix-popper-anchor-width",`${Lt}px`),Ar.setProperty("--radix-popper-anchor-height",`${Kt}px`)}}),W&&vEe({element:W,padding:a}),kEe({arrowWidth:Q,arrowHeight:te}),N&&xEe({strategy:"referenceHidden",...pe})]}),[je,et]=sle(ke),bt=Oo(P);Lo(()=>{Ce&&(bt==null||bt())},[Ce,bt]);const _e=(gt=Se.arrow)==null?void 0:gt.x,Ye=(Me=Se.arrow)==null?void 0:Me.y,pt=((Oe=Se.arrow)==null?void 0:Oe.centerOffset)!==0,[nt,Qt]=D.useState();return Lo(()=>{O&&Qt(window.getComputedStyle(O).zIndex)},[O]),s.jsx("div",{ref:ve.setFloating,"data-radix-popper-content-wrapper":"",style:{...ge,transform:Ce?ge.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:nt,"--radix-popper-transform-origin":[(Ie=Se.transformOrigin)==null?void 0:Ie.x,(Be=Se.transformOrigin)==null?void 0:Be.y].join(" "),...((Pe=Se.hide)==null?void 0:Pe.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:t.dir,children:s.jsx(jEe,{scope:r,placedSide:je,onArrowChange:V,arrowX:_e,arrowY:Ye,shouldHideArrow:pt,children:s.jsx(yn.div,{"data-side":je,"data-align":et,...A,ref:z,style:{...A.style,animation:Ce?void 0:"none"}})})})});tle.displayName=a8;var rle="PopperArrow",NEe={top:"bottom",right:"left",bottom:"top",left:"right"},nle=D.forwardRef(function(e,r){const{__scopePopper:n,...i}=e,o=SEe(rle,n),c=NEe[o.placedSide];return s.jsx("span",{ref:o.onArrowChange,style:{position:"absolute",left:o.arrowX,top:o.arrowY,[c]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[o.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[o.placedSide],visibility:o.shouldHideArrow?"hidden":void 0},children:s.jsx(bEe,{...i,ref:r,style:{...i.style,display:"block"}})})});nle.displayName=rle;function CEe(t){return t!==null}var kEe=t=>({name:"transformOrigin",options:t,fn(e){var I,O,R;const{placement:r,rects:n,middlewareData:i}=e,c=((I=i.arrow)==null?void 0:I.centerOffset)!==0,a=c?0:t.arrowWidth,m=c?0:t.arrowHeight,[g,_]=sle(r),j={start:"0%",center:"50%",end:"100%"}[_],N=(((O=i.arrow)==null?void 0:O.x)??0)+a/2,C=(((R=i.arrow)==null?void 0:R.y)??0)+m/2;let P="",A="";return g==="bottom"?(P=c?j:`${N}px`,A=`${-m}px`):g==="top"?(P=c?j:`${N}px`,A=`${n.floating.height+m}px`):g==="right"?(P=`${-m}px`,A=c?j:`${C}px`):g==="left"&&(P=`${n.floating.width+m}px`,A=c?j:`${C}px`),{data:{x:P,y:A}}}});function sle(t){const[e,r="center"]=t.split("-");return[e,r]}var aD=Qoe,bT=ele,oD=tle,lD=nle,[cD]=Yo("Tooltip",[gx]),uD=gx(),ile="TooltipProvider",TEe=700,M5="tooltip.open",[EEe,o8]=cD(ile),ale=t=>{const{__scopeTooltip:e,delayDuration:r=TEe,skipDelayDuration:n=300,disableHoverableContent:i=!1,children:o}=t,c=D.useRef(!0),a=D.useRef(!1),m=D.useRef(0);return D.useEffect(()=>{const g=m.current;return()=>window.clearTimeout(g)},[]),s.jsx(EEe,{scope:e,isOpenDelayedRef:c,delayDuration:r,onOpen:D.useCallback(()=>{window.clearTimeout(m.current),c.current=!1},[]),onClose:D.useCallback(()=>{window.clearTimeout(m.current),m.current=window.setTimeout(()=>c.current=!0,n)},[n]),isPointerInTransitRef:a,onPointerInTransitChange:D.useCallback(g=>{a.current=g},[]),disableHoverableContent:i,children:o})};ale.displayName=ile;var X2="Tooltip",[AEe,dD]=cD(X2),ole=t=>{const{__scopeTooltip:e,children:r,open:n,defaultOpen:i,onOpenChange:o,disableHoverableContent:c,delayDuration:a}=t,m=o8(X2,t.__scopeTooltip),g=uD(e),[_,j]=D.useState(null),N=Al(),C=D.useRef(0),P=c??m.disableHoverableContent,A=a??m.delayDuration,I=D.useRef(!1),[O,R]=Uu({prop:n,defaultProp:i??!1,onChange:Q=>{Q?(m.onOpen(),document.dispatchEvent(new CustomEvent(M5))):m.onClose(),o==null||o(Q)},caller:X2}),z=D.useMemo(()=>O?I.current?"delayed-open":"instant-open":"closed",[O]),W=D.useCallback(()=>{window.clearTimeout(C.current),C.current=0,I.current=!1,R(!0)},[R]),V=D.useCallback(()=>{window.clearTimeout(C.current),C.current=0,R(!1)},[R]),K=D.useCallback(()=>{window.clearTimeout(C.current),C.current=window.setTimeout(()=>{I.current=!0,R(!0),C.current=0},A)},[A,R]);return D.useEffect(()=>()=>{C.current&&(window.clearTimeout(C.current),C.current=0)},[]),s.jsx(aD,{...g,children:s.jsx(AEe,{scope:e,contentId:N,open:O,stateAttribute:z,trigger:_,onTriggerChange:j,onTriggerEnter:D.useCallback(()=>{m.isOpenDelayedRef.current?K():W()},[m.isOpenDelayedRef,K,W]),onTriggerLeave:D.useCallback(()=>{P?V():(window.clearTimeout(C.current),C.current=0)},[V,P]),onOpen:W,onClose:V,disableHoverableContent:P,children:r})})};ole.displayName=X2;var O5="TooltipTrigger",lle=D.forwardRef((t,e)=>{const{__scopeTooltip:r,...n}=t,i=dD(O5,r),o=o8(O5,r),c=uD(r),a=D.useRef(null),m=vs(e,a,i.onTriggerChange),g=D.useRef(!1),_=D.useRef(!1),j=D.useCallback(()=>g.current=!1,[]);return D.useEffect(()=>()=>document.removeEventListener("pointerup",j),[j]),s.jsx(bT,{asChild:!0,...c,children:s.jsx(yn.button,{"aria-describedby":i.open?i.contentId:void 0,"data-state":i.stateAttribute,...n,ref:m,onPointerMove:Yr(t.onPointerMove,N=>{N.pointerType!=="touch"&&!_.current&&!o.isPointerInTransitRef.current&&(i.onTriggerEnter(),_.current=!0)}),onPointerLeave:Yr(t.onPointerLeave,()=>{i.onTriggerLeave(),_.current=!1}),onPointerDown:Yr(t.onPointerDown,()=>{i.open&&i.onClose(),g.current=!0,document.addEventListener("pointerup",j,{once:!0})}),onFocus:Yr(t.onFocus,()=>{g.current||i.onOpen()}),onBlur:Yr(t.onBlur,i.onClose),onClick:Yr(t.onClick,i.onClose)})})});lle.displayName=O5;var PEe="TooltipPortal",[ewt,IEe]=cD(PEe,{forceMount:void 0}),L1="TooltipContent",cle=D.forwardRef((t,e)=>{const r=IEe(L1,t.__scopeTooltip),{forceMount:n=r.forceMount,side:i="top",...o}=t,c=dD(L1,t.__scopeTooltip);return s.jsx(gl,{present:n||c.open,children:c.disableHoverableContent?s.jsx(ule,{side:i,...o,ref:e}):s.jsx(MEe,{side:i,...o,ref:e})})}),MEe=D.forwardRef((t,e)=>{const r=dD(L1,t.__scopeTooltip),n=o8(L1,t.__scopeTooltip),i=D.useRef(null),o=vs(e,i),[c,a]=D.useState(null),{trigger:m,onClose:g}=r,_=i.current,{onPointerInTransitChange:j}=n,N=D.useCallback(()=>{a(null),j(!1)},[j]),C=D.useCallback((P,A)=>{const I=P.currentTarget,O={x:P.clientX,y:P.clientY},R=FEe(O,I.getBoundingClientRect()),z=zEe(O,R),W=BEe(A.getBoundingClientRect()),V=UEe([...z,...W]);a(V),j(!0)},[j]);return D.useEffect(()=>()=>N(),[N]),D.useEffect(()=>{if(m&&_){const P=I=>C(I,_),A=I=>C(I,m);return m.addEventListener("pointerleave",P),_.addEventListener("pointerleave",A),()=>{m.removeEventListener("pointerleave",P),_.removeEventListener("pointerleave",A)}}},[m,_,C,N]),D.useEffect(()=>{if(c){const P=A=>{const I=A.target,O={x:A.clientX,y:A.clientY},R=(m==null?void 0:m.contains(I))||(_==null?void 0:_.contains(I)),z=!$Ee(O,c);R?N():z&&(N(),g())};return document.addEventListener("pointermove",P),()=>document.removeEventListener("pointermove",P)}},[m,_,c,g,N]),s.jsx(ule,{...t,ref:o})}),[OEe,REe]=cD(X2,{isInside:!1}),DEe=Tae("TooltipContent"),ule=D.forwardRef((t,e)=>{const{__scopeTooltip:r,children:n,"aria-label":i,onEscapeKeyDown:o,onPointerDownOutside:c,...a}=t,m=dD(L1,r),g=uD(r),{onClose:_}=m;return D.useEffect(()=>(document.addEventListener(M5,_),()=>document.removeEventListener(M5,_)),[_]),D.useEffect(()=>{if(m.trigger){const j=N=>{const C=N.target;C!=null&&C.contains(m.trigger)&&_()};return window.addEventListener("scroll",j,{capture:!0}),()=>window.removeEventListener("scroll",j,{capture:!0})}},[m.trigger,_]),s.jsx(t0,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:o,onPointerDownOutside:c,onFocusOutside:j=>j.preventDefault(),onDismiss:_,children:s.jsxs(oD,{"data-state":m.stateAttribute,...g,...a,ref:e,style:{...a.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[s.jsx(DEe,{children:n}),s.jsx(OEe,{scope:r,isInside:!0,children:s.jsx(e2e,{id:m.contentId,role:"tooltip",children:i||n})})]})})});cle.displayName=L1;var dle="TooltipArrow",LEe=D.forwardRef((t,e)=>{const{__scopeTooltip:r,...n}=t,i=uD(r);return REe(dle,r).isInside?null:s.jsx(lD,{...i,...n,ref:e})});LEe.displayName=dle;function FEe(t,e){const r=Math.abs(e.top-t.y),n=Math.abs(e.bottom-t.y),i=Math.abs(e.right-t.x),o=Math.abs(e.left-t.x);switch(Math.min(r,n,i,o)){case o:return"left";case i:return"right";case r:return"top";case n:return"bottom";default:throw new Error("unreachable")}}function zEe(t,e,r=5){const n=[];switch(e){case"top":n.push({x:t.x-r,y:t.y+r},{x:t.x+r,y:t.y+r});break;case"bottom":n.push({x:t.x-r,y:t.y-r},{x:t.x+r,y:t.y-r});break;case"left":n.push({x:t.x+r,y:t.y-r},{x:t.x+r,y:t.y+r});break;case"right":n.push({x:t.x-r,y:t.y-r},{x:t.x-r,y:t.y+r});break}return n}function BEe(t){const{top:e,right:r,bottom:n,left:i}=t;return[{x:i,y:e},{x:r,y:e},{x:r,y:n},{x:i,y:n}]}function $Ee(t,e){const{x:r,y:n}=t;let i=!1;for(let o=0,c=e.length-1;on!=N>n&&r<(j-g)*(n-_)/(N-_)+g&&(i=!i)}return i}function UEe(t){const e=t.slice();return e.sort((r,n)=>r.xn.x?1:r.yn.y?1:0),VEe(e)}function VEe(t){if(t.length<=1)return t.slice();const e=[];for(let n=0;n=2;){const o=e[e.length-1],c=e[e.length-2];if((o.x-c.x)*(i.y-c.y)>=(o.y-c.y)*(i.x-c.x))e.pop();else break}e.push(i)}e.pop();const r=[];for(let n=t.length-1;n>=0;n--){const i=t[n];for(;r.length>=2;){const o=r[r.length-1],c=r[r.length-2];if((o.x-c.x)*(i.y-c.y)>=(o.y-c.y)*(i.x-c.x))r.pop();else break}r.push(i)}return r.pop(),e.length===1&&r.length===1&&e[0].x===r[0].x&&e[0].y===r[0].y?e:e.concat(r)}var qEe=ale,HEe=ole,WEe=lle,hle=cle;const fle=qEe,ple=HEe,mle=WEe,l8=D.forwardRef(({className:t,sideOffset:e=4,...r},n)=>s.jsx(hle,{ref:n,sideOffset:e,className:ar("z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...r}));l8.displayName=hle.displayName;var Oj=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(t){return this.listeners.add(t),this.onSubscribe(),()=>{this.listeners.delete(t),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},M_=typeof window>"u"||"Deno"in globalThis;function Jc(){}function GEe(t,e){return typeof t=="function"?t(e):t}function R5(t){return typeof t=="number"&&t>=0&&t!==1/0}function gle(t,e){return Math.max(t+(e||0)-Date.now(),0)}function Hy(t,e){return typeof t=="function"?t(e):t}function Xd(t,e){return typeof t=="function"?t(e):t}function dY(t,e){const{type:r="all",exact:n,fetchStatus:i,predicate:o,queryKey:c,stale:a}=t;if(c){if(n){if(e.queryHash!==c8(c,e.options))return!1}else if(!Q2(e.queryKey,c))return!1}if(r!=="all"){const m=e.isActive();if(r==="active"&&!m||r==="inactive"&&m)return!1}return!(typeof a=="boolean"&&e.isStale()!==a||i&&i!==e.state.fetchStatus||o&&!o(e))}function hY(t,e){const{exact:r,status:n,predicate:i,mutationKey:o}=t;if(o){if(!e.options.mutationKey)return!1;if(r){if(O_(e.options.mutationKey)!==O_(o))return!1}else if(!Q2(e.options.mutationKey,o))return!1}return!(n&&e.state.status!==n||i&&!i(e))}function c8(t,e){return((e==null?void 0:e.queryKeyHashFn)||O_)(t)}function O_(t){return JSON.stringify(t,(e,r)=>D5(r)?Object.keys(r).sort().reduce((n,i)=>(n[i]=r[i],n),{}):r)}function Q2(t,e){return t===e?!0:typeof t!=typeof e?!1:t&&e&&typeof t=="object"&&typeof e=="object"?Object.keys(e).every(r=>Q2(t[r],e[r])):!1}function yle(t,e){if(t===e)return t;const r=fY(t)&&fY(e);if(r||D5(t)&&D5(e)){const n=r?t:Object.keys(t),i=n.length,o=r?e:Object.keys(e),c=o.length,a=r?[]:{},m=new Set(n);let g=0;for(let _=0;_{setTimeout(e,t)})}function L5(t,e,r){return typeof r.structuralSharing=="function"?r.structuralSharing(t,e):r.structuralSharing!==!1?yle(t,e):e}function ZEe(t,e,r=0){const n=[...t,e];return r&&n.length>r?n.slice(1):n}function YEe(t,e,r=0){const n=[e,...t];return r&&n.length>r?n.slice(0,-1):n}var u8=Symbol();function xle(t,e){return!t.queryFn&&(e!=null&&e.initialPromise)?()=>e.initialPromise:!t.queryFn||t.queryFn===u8?()=>Promise.reject(new Error(`Missing queryFn: '${t.queryHash}'`)):t.queryFn}function vle(t,e){return typeof t=="function"?t(...e):!!t}var s_,xy,f1,tse,XEe=(tse=class extends Oj{constructor(){super();Es(this,s_);Es(this,xy);Es(this,f1);On(this,f1,e=>{if(!M_&&window.addEventListener){const r=()=>e();return window.addEventListener("visibilitychange",r,!1),()=>{window.removeEventListener("visibilitychange",r)}}})}onSubscribe(){Ot(this,xy)||this.setEventListener(Ot(this,f1))}onUnsubscribe(){var e;this.hasListeners()||((e=Ot(this,xy))==null||e.call(this),On(this,xy,void 0))}setEventListener(e){var r;On(this,f1,e),(r=Ot(this,xy))==null||r.call(this),On(this,xy,e(n=>{typeof n=="boolean"?this.setFocused(n):this.onFocus()}))}setFocused(e){Ot(this,s_)!==e&&(On(this,s_,e),this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(r=>{r(e)})}isFocused(){var e;return typeof Ot(this,s_)=="boolean"?Ot(this,s_):((e=globalThis.document)==null?void 0:e.visibilityState)!=="hidden"}},s_=new WeakMap,xy=new WeakMap,f1=new WeakMap,tse),d8=new XEe,p1,vy,m1,rse,QEe=(rse=class extends Oj{constructor(){super();Es(this,p1,!0);Es(this,vy);Es(this,m1);On(this,m1,e=>{if(!M_&&window.addEventListener){const r=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",r,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",r),window.removeEventListener("offline",n)}}})}onSubscribe(){Ot(this,vy)||this.setEventListener(Ot(this,m1))}onUnsubscribe(){var e;this.hasListeners()||((e=Ot(this,vy))==null||e.call(this),On(this,vy,void 0))}setEventListener(e){var r;On(this,m1,e),(r=Ot(this,vy))==null||r.call(this),On(this,vy,e(this.setOnline.bind(this)))}setOnline(e){Ot(this,p1)!==e&&(On(this,p1,e),this.listeners.forEach(n=>{n(e)}))}isOnline(){return Ot(this,p1)}},p1=new WeakMap,vy=new WeakMap,m1=new WeakMap,rse),jM=new QEe;function F5(){let t,e;const r=new Promise((i,o)=>{t=i,e=o});r.status="pending",r.catch(()=>{});function n(i){Object.assign(r,i),delete r.resolve,delete r.reject}return r.resolve=i=>{n({status:"fulfilled",value:i}),t(i)},r.reject=i=>{n({status:"rejected",reason:i}),e(i)},r}function JEe(t){return Math.min(1e3*2**t,3e4)}function _le(t){return(t??"online")==="online"?jM.isOnline():!0}var ble=class extends Error{constructor(t){super("CancelledError"),this.revert=t==null?void 0:t.revert,this.silent=t==null?void 0:t.silent}};function zF(t){return t instanceof ble}function wle(t){let e=!1,r=0,n=!1,i;const o=F5(),c=A=>{var I;n||(N(new ble(A)),(I=t.abort)==null||I.call(t))},a=()=>{e=!0},m=()=>{e=!1},g=()=>d8.isFocused()&&(t.networkMode==="always"||jM.isOnline())&&t.canRun(),_=()=>_le(t.networkMode)&&t.canRun(),j=A=>{var I;n||(n=!0,(I=t.onSuccess)==null||I.call(t,A),i==null||i(),o.resolve(A))},N=A=>{var I;n||(n=!0,(I=t.onError)==null||I.call(t,A),i==null||i(),o.reject(A))},C=()=>new Promise(A=>{var I;i=O=>{(n||g())&&A(O)},(I=t.onPause)==null||I.call(t)}).then(()=>{var A;i=void 0,n||(A=t.onContinue)==null||A.call(t)}),P=()=>{if(n)return;let A;const I=r===0?t.initialPromise:void 0;try{A=I??t.fn()}catch(O){A=Promise.reject(O)}Promise.resolve(A).then(j).catch(O=>{var K;if(n)return;const R=t.retry??(M_?0:3),z=t.retryDelay??JEe,W=typeof z=="function"?z(r,O):z,V=R===!0||typeof R=="number"&&rg()?void 0:C()).then(()=>{e?N(O):P()})})};return{promise:o,cancel:c,continue:()=>(i==null||i(),o),cancelRetry:a,continueRetry:m,canStart:_,start:()=>(_()?P():C().then(P),o)}}var eAe=t=>setTimeout(t,0);function tAe(){let t=[],e=0,r=a=>{a()},n=a=>{a()},i=eAe;const o=a=>{e?t.push(a):i(()=>{r(a)})},c=()=>{const a=t;t=[],a.length&&i(()=>{n(()=>{a.forEach(m=>{r(m)})})})};return{batch:a=>{let m;e++;try{m=a()}finally{e--,e||c()}return m},batchCalls:a=>(...m)=>{o(()=>{a(...m)})},schedule:o,setNotifyFunction:a=>{r=a},setBatchNotifyFunction:a=>{n=a},setScheduler:a=>{i=a}}}var kl=tAe(),i_,nse,jle=(nse=class{constructor(){Es(this,i_)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),R5(this.gcTime)&&On(this,i_,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(M_?1/0:5*60*1e3))}clearGcTimeout(){Ot(this,i_)&&(clearTimeout(Ot(this,i_)),On(this,i_,void 0))}},i_=new WeakMap,nse),g1,a_,Yd,o_,Tc,nT,l_,nf,xm,sse,rAe=(sse=class extends jle{constructor(e){super();Es(this,nf);Es(this,g1);Es(this,a_);Es(this,Yd);Es(this,o_);Es(this,Tc);Es(this,nT);Es(this,l_);On(this,l_,!1),On(this,nT,e.defaultOptions),this.setOptions(e.options),this.observers=[],On(this,o_,e.client),On(this,Yd,Ot(this,o_).getQueryCache()),this.queryKey=e.queryKey,this.queryHash=e.queryHash,On(this,g1,nAe(this.options)),this.state=e.state??Ot(this,g1),this.scheduleGc()}get meta(){return this.options.meta}get promise(){var e;return(e=Ot(this,Tc))==null?void 0:e.promise}setOptions(e){this.options={...Ot(this,nT),...e},this.updateGcTime(this.options.gcTime)}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&Ot(this,Yd).remove(this)}setData(e,r){const n=L5(this.state.data,e,this.options);return Ei(this,nf,xm).call(this,{data:n,type:"success",dataUpdatedAt:r==null?void 0:r.updatedAt,manual:r==null?void 0:r.manual}),n}setState(e,r){Ei(this,nf,xm).call(this,{type:"setState",state:e,setStateOptions:r})}cancel(e){var n,i;const r=(n=Ot(this,Tc))==null?void 0:n.promise;return(i=Ot(this,Tc))==null||i.cancel(e),r?r.then(Jc).catch(Jc):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(Ot(this,g1))}isActive(){return this.observers.some(e=>Xd(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===u8||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>Hy(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:!gle(this.state.dataUpdatedAt,e)}onFocus(){var r;const e=this.observers.find(n=>n.shouldFetchOnWindowFocus());e==null||e.refetch({cancelRefetch:!1}),(r=Ot(this,Tc))==null||r.continue()}onOnline(){var r;const e=this.observers.find(n=>n.shouldFetchOnReconnect());e==null||e.refetch({cancelRefetch:!1}),(r=Ot(this,Tc))==null||r.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),Ot(this,Yd).notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(r=>r!==e),this.observers.length||(Ot(this,Tc)&&(Ot(this,l_)?Ot(this,Tc).cancel({revert:!0}):Ot(this,Tc).cancelRetry()),this.scheduleGc()),Ot(this,Yd).notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||Ei(this,nf,xm).call(this,{type:"invalidate"})}fetch(e,r){var g,_,j;if(this.state.fetchStatus!=="idle"){if(this.state.data!==void 0&&(r!=null&&r.cancelRefetch))this.cancel({silent:!0});else if(Ot(this,Tc))return Ot(this,Tc).continueRetry(),Ot(this,Tc).promise}if(e&&this.setOptions(e),!this.options.queryFn){const N=this.observers.find(C=>C.options.queryFn);N&&this.setOptions(N.options)}const n=new AbortController,i=N=>{Object.defineProperty(N,"signal",{enumerable:!0,get:()=>(On(this,l_,!0),n.signal)})},o=()=>{const N=xle(this.options,r),P=(()=>{const A={client:Ot(this,o_),queryKey:this.queryKey,meta:this.meta};return i(A),A})();return On(this,l_,!1),this.options.persister?this.options.persister(N,P,this):N(P)},a=(()=>{const N={fetchOptions:r,options:this.options,queryKey:this.queryKey,client:Ot(this,o_),state:this.state,fetchFn:o};return i(N),N})();(g=this.options.behavior)==null||g.onFetch(a,this),On(this,a_,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((_=a.fetchOptions)==null?void 0:_.meta))&&Ei(this,nf,xm).call(this,{type:"fetch",meta:(j=a.fetchOptions)==null?void 0:j.meta});const m=N=>{var C,P,A,I;zF(N)&&N.silent||Ei(this,nf,xm).call(this,{type:"error",error:N}),zF(N)||((P=(C=Ot(this,Yd).config).onError)==null||P.call(C,N,this),(I=(A=Ot(this,Yd).config).onSettled)==null||I.call(A,this.state.data,N,this)),this.scheduleGc()};return On(this,Tc,wle({initialPromise:r==null?void 0:r.initialPromise,fn:a.fetchFn,abort:n.abort.bind(n),onSuccess:N=>{var C,P,A,I;if(N===void 0){m(new Error(`${this.queryHash} data is undefined`));return}try{this.setData(N)}catch(O){m(O);return}(P=(C=Ot(this,Yd).config).onSuccess)==null||P.call(C,N,this),(I=(A=Ot(this,Yd).config).onSettled)==null||I.call(A,N,this.state.error,this),this.scheduleGc()},onError:m,onFail:(N,C)=>{Ei(this,nf,xm).call(this,{type:"failed",failureCount:N,error:C})},onPause:()=>{Ei(this,nf,xm).call(this,{type:"pause"})},onContinue:()=>{Ei(this,nf,xm).call(this,{type:"continue"})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0})),Ot(this,Tc).start()}},g1=new WeakMap,a_=new WeakMap,Yd=new WeakMap,o_=new WeakMap,Tc=new WeakMap,nT=new WeakMap,l_=new WeakMap,nf=new WeakSet,xm=function(e){const r=n=>{switch(e.type){case"failed":return{...n,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...Sle(n.data,this.options),fetchMeta:e.meta??null};case"success":return On(this,a_,void 0),{...n,data:e.data,dataUpdateCount:n.dataUpdateCount+1,dataUpdatedAt:e.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const i=e.error;return zF(i)&&i.revert&&Ot(this,a_)?{...Ot(this,a_),fetchStatus:"idle"}:{...n,error:i,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error"};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=r(this.state),kl.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),Ot(this,Yd).notify({query:this,type:"updated",action:e})})},sse);function Sle(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:_le(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}function nAe(t){const e=typeof t.initialData=="function"?t.initialData():t.initialData,r=e!==void 0,n=r?typeof t.initialDataUpdatedAt=="function"?t.initialDataUpdatedAt():t.initialDataUpdatedAt:0;return{data:e,dataUpdateCount:0,dataUpdatedAt:r?n??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:r?"success":"pending",fetchStatus:"idle"}}var ap,ise,sAe=(ise=class extends Oj{constructor(e={}){super();Es(this,ap);this.config=e,On(this,ap,new Map)}build(e,r,n){const i=r.queryKey,o=r.queryHash??c8(i,r);let c=this.get(o);return c||(c=new rAe({client:e,queryKey:i,queryHash:o,options:e.defaultQueryOptions(r),state:n,defaultOptions:e.getQueryDefaults(i)}),this.add(c)),c}add(e){Ot(this,ap).has(e.queryHash)||(Ot(this,ap).set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const r=Ot(this,ap).get(e.queryHash);r&&(e.destroy(),r===e&&Ot(this,ap).delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){kl.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return Ot(this,ap).get(e)}getAll(){return[...Ot(this,ap).values()]}find(e){const r={exact:!0,...e};return this.getAll().find(n=>dY(r,n))}findAll(e={}){const r=this.getAll();return Object.keys(e).length>0?r.filter(n=>dY(e,n)):r}notify(e){kl.batch(()=>{this.listeners.forEach(r=>{r(e)})})}onFocus(){kl.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){kl.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},ap=new WeakMap,ise),op,Yc,c_,lp,Qg,ase,iAe=(ase=class extends jle{constructor(e){super();Es(this,lp);Es(this,op);Es(this,Yc);Es(this,c_);this.mutationId=e.mutationId,On(this,Yc,e.mutationCache),On(this,op,[]),this.state=e.state||Nle(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){Ot(this,op).includes(e)||(Ot(this,op).push(e),this.clearGcTimeout(),Ot(this,Yc).notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){On(this,op,Ot(this,op).filter(r=>r!==e)),this.scheduleGc(),Ot(this,Yc).notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){Ot(this,op).length||(this.state.status==="pending"?this.scheduleGc():Ot(this,Yc).remove(this))}continue(){var e;return((e=Ot(this,c_))==null?void 0:e.continue())??this.execute(this.state.variables)}async execute(e){var o,c,a,m,g,_,j,N,C,P,A,I,O,R,z,W,V,K,Q,te;const r=()=>{Ei(this,lp,Qg).call(this,{type:"continue"})};On(this,c_,wle({fn:()=>this.options.mutationFn?this.options.mutationFn(e):Promise.reject(new Error("No mutationFn found")),onFail:(X,ie)=>{Ei(this,lp,Qg).call(this,{type:"failed",failureCount:X,error:ie})},onPause:()=>{Ei(this,lp,Qg).call(this,{type:"pause"})},onContinue:r,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>Ot(this,Yc).canRun(this)}));const n=this.state.status==="pending",i=!Ot(this,c_).canStart();try{if(n)r();else{Ei(this,lp,Qg).call(this,{type:"pending",variables:e,isPaused:i}),await((c=(o=Ot(this,Yc).config).onMutate)==null?void 0:c.call(o,e,this));const ie=await((m=(a=this.options).onMutate)==null?void 0:m.call(a,e));ie!==this.state.context&&Ei(this,lp,Qg).call(this,{type:"pending",context:ie,variables:e,isPaused:i})}const X=await Ot(this,c_).start();return await((_=(g=Ot(this,Yc).config).onSuccess)==null?void 0:_.call(g,X,e,this.state.context,this)),await((N=(j=this.options).onSuccess)==null?void 0:N.call(j,X,e,this.state.context)),await((P=(C=Ot(this,Yc).config).onSettled)==null?void 0:P.call(C,X,null,this.state.variables,this.state.context,this)),await((I=(A=this.options).onSettled)==null?void 0:I.call(A,X,null,e,this.state.context)),Ei(this,lp,Qg).call(this,{type:"success",data:X}),X}catch(X){try{throw await((R=(O=Ot(this,Yc).config).onError)==null?void 0:R.call(O,X,e,this.state.context,this)),await((W=(z=this.options).onError)==null?void 0:W.call(z,X,e,this.state.context)),await((K=(V=Ot(this,Yc).config).onSettled)==null?void 0:K.call(V,void 0,X,this.state.variables,this.state.context,this)),await((te=(Q=this.options).onSettled)==null?void 0:te.call(Q,void 0,X,e,this.state.context)),X}finally{Ei(this,lp,Qg).call(this,{type:"error",error:X})}}finally{Ot(this,Yc).runNext(this)}}},op=new WeakMap,Yc=new WeakMap,c_=new WeakMap,lp=new WeakSet,Qg=function(e){const r=n=>{switch(e.type){case"failed":return{...n,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...n,isPaused:!0};case"continue":return{...n,isPaused:!1};case"pending":return{...n,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{...n,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...n,data:void 0,error:e.error,failureCount:n.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=r(this.state),kl.batch(()=>{Ot(this,op).forEach(n=>{n.onMutationUpdate(e)}),Ot(this,Yc).notify({mutation:this,type:"updated",action:e})})},ase);function Nle(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Nm,sf,sT,ose,aAe=(ose=class extends Oj{constructor(e={}){super();Es(this,Nm);Es(this,sf);Es(this,sT);this.config=e,On(this,Nm,new Set),On(this,sf,new Map),On(this,sT,0)}build(e,r,n){const i=new iAe({mutationCache:this,mutationId:++KA(this,sT)._,options:e.defaultMutationOptions(r),state:n});return this.add(i),i}add(e){Ot(this,Nm).add(e);const r=gP(e);if(typeof r=="string"){const n=Ot(this,sf).get(r);n?n.push(e):Ot(this,sf).set(r,[e])}this.notify({type:"added",mutation:e})}remove(e){if(Ot(this,Nm).delete(e)){const r=gP(e);if(typeof r=="string"){const n=Ot(this,sf).get(r);if(n)if(n.length>1){const i=n.indexOf(e);i!==-1&&n.splice(i,1)}else n[0]===e&&Ot(this,sf).delete(r)}}this.notify({type:"removed",mutation:e})}canRun(e){const r=gP(e);if(typeof r=="string"){const n=Ot(this,sf).get(r),i=n==null?void 0:n.find(o=>o.state.status==="pending");return!i||i===e}else return!0}runNext(e){var n;const r=gP(e);if(typeof r=="string"){const i=(n=Ot(this,sf).get(r))==null?void 0:n.find(o=>o!==e&&o.state.isPaused);return(i==null?void 0:i.continue())??Promise.resolve()}else return Promise.resolve()}clear(){kl.batch(()=>{Ot(this,Nm).forEach(e=>{this.notify({type:"removed",mutation:e})}),Ot(this,Nm).clear(),Ot(this,sf).clear()})}getAll(){return Array.from(Ot(this,Nm))}find(e){const r={exact:!0,...e};return this.getAll().find(n=>hY(r,n))}findAll(e={}){return this.getAll().filter(r=>hY(e,r))}notify(e){kl.batch(()=>{this.listeners.forEach(r=>{r(e)})})}resumePausedMutations(){const e=this.getAll().filter(r=>r.state.isPaused);return kl.batch(()=>Promise.all(e.map(r=>r.continue().catch(Jc))))}},Nm=new WeakMap,sf=new WeakMap,sT=new WeakMap,ose);function gP(t){var e;return(e=t.options.scope)==null?void 0:e.id}function mY(t){return{onFetch:(e,r)=>{var _,j,N,C,P;const n=e.options,i=(N=(j=(_=e.fetchOptions)==null?void 0:_.meta)==null?void 0:j.fetchMore)==null?void 0:N.direction,o=((C=e.state.data)==null?void 0:C.pages)||[],c=((P=e.state.data)==null?void 0:P.pageParams)||[];let a={pages:[],pageParams:[]},m=0;const g=async()=>{let A=!1;const I=z=>{Object.defineProperty(z,"signal",{enumerable:!0,get:()=>(e.signal.aborted?A=!0:e.signal.addEventListener("abort",()=>{A=!0}),e.signal)})},O=xle(e.options,e.fetchOptions),R=async(z,W,V)=>{if(A)return Promise.reject();if(W==null&&z.pages.length)return Promise.resolve(z);const Q=(()=>{const he={client:e.client,queryKey:e.queryKey,pageParam:W,direction:V?"backward":"forward",meta:e.options.meta};return I(he),he})(),te=await O(Q),{maxPages:X}=e.options,ie=V?YEe:ZEe;return{pages:ie(z.pages,te,X),pageParams:ie(z.pageParams,W,X)}};if(i&&o.length){const z=i==="backward",W=z?oAe:gY,V={pages:o,pageParams:c},K=W(n,V);a=await R(V,K,z)}else{const z=t??o.length;do{const W=m===0?c[0]??n.initialPageParam:gY(n,a);if(m>0&&W==null)break;a=await R(a,W),m++}while(m{var A,I;return(I=(A=e.options).persister)==null?void 0:I.call(A,g,{client:e.client,queryKey:e.queryKey,meta:e.options.meta,signal:e.signal},r)}:e.fetchFn=g}}}function gY(t,{pages:e,pageParams:r}){const n=e.length-1;return e.length>0?t.getNextPageParam(e[n],e,r[n],r):void 0}function oAe(t,{pages:e,pageParams:r}){var n;return e.length>0?(n=t.getPreviousPageParam)==null?void 0:n.call(t,e[0],e,r[0],r):void 0}var Ao,_y,by,y1,x1,wy,v1,_1,lse,lAe=(lse=class{constructor(t={}){Es(this,Ao);Es(this,_y);Es(this,by);Es(this,y1);Es(this,x1);Es(this,wy);Es(this,v1);Es(this,_1);On(this,Ao,t.queryCache||new sAe),On(this,_y,t.mutationCache||new aAe),On(this,by,t.defaultOptions||{}),On(this,y1,new Map),On(this,x1,new Map),On(this,wy,0)}mount(){KA(this,wy)._++,Ot(this,wy)===1&&(On(this,v1,d8.subscribe(async t=>{t&&(await this.resumePausedMutations(),Ot(this,Ao).onFocus())})),On(this,_1,jM.subscribe(async t=>{t&&(await this.resumePausedMutations(),Ot(this,Ao).onOnline())})))}unmount(){var t,e;KA(this,wy)._--,Ot(this,wy)===0&&((t=Ot(this,v1))==null||t.call(this),On(this,v1,void 0),(e=Ot(this,_1))==null||e.call(this),On(this,_1,void 0))}isFetching(t){return Ot(this,Ao).findAll({...t,fetchStatus:"fetching"}).length}isMutating(t){return Ot(this,_y).findAll({...t,status:"pending"}).length}getQueryData(t){var r;const e=this.defaultQueryOptions({queryKey:t});return(r=Ot(this,Ao).get(e.queryHash))==null?void 0:r.state.data}ensureQueryData(t){const e=this.defaultQueryOptions(t),r=Ot(this,Ao).build(this,e),n=r.state.data;return n===void 0?this.fetchQuery(t):(t.revalidateIfStale&&r.isStaleByTime(Hy(e.staleTime,r))&&this.prefetchQuery(e),Promise.resolve(n))}getQueriesData(t){return Ot(this,Ao).findAll(t).map(({queryKey:e,state:r})=>{const n=r.data;return[e,n]})}setQueryData(t,e,r){const n=this.defaultQueryOptions({queryKey:t}),i=Ot(this,Ao).get(n.queryHash),o=i==null?void 0:i.state.data,c=GEe(e,o);if(c!==void 0)return Ot(this,Ao).build(this,n).setData(c,{...r,manual:!0})}setQueriesData(t,e,r){return kl.batch(()=>Ot(this,Ao).findAll(t).map(({queryKey:n})=>[n,this.setQueryData(n,e,r)]))}getQueryState(t){var r;const e=this.defaultQueryOptions({queryKey:t});return(r=Ot(this,Ao).get(e.queryHash))==null?void 0:r.state}removeQueries(t){const e=Ot(this,Ao);kl.batch(()=>{e.findAll(t).forEach(r=>{e.remove(r)})})}resetQueries(t,e){const r=Ot(this,Ao);return kl.batch(()=>(r.findAll(t).forEach(n=>{n.reset()}),this.refetchQueries({type:"active",...t},e)))}cancelQueries(t,e={}){const r={revert:!0,...e},n=kl.batch(()=>Ot(this,Ao).findAll(t).map(i=>i.cancel(r)));return Promise.all(n).then(Jc).catch(Jc)}invalidateQueries(t,e={}){return kl.batch(()=>(Ot(this,Ao).findAll(t).forEach(r=>{r.invalidate()}),(t==null?void 0:t.refetchType)==="none"?Promise.resolve():this.refetchQueries({...t,type:(t==null?void 0:t.refetchType)??(t==null?void 0:t.type)??"active"},e)))}refetchQueries(t,e={}){const r={...e,cancelRefetch:e.cancelRefetch??!0},n=kl.batch(()=>Ot(this,Ao).findAll(t).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let o=i.fetch(void 0,r);return r.throwOnError||(o=o.catch(Jc)),i.state.fetchStatus==="paused"?Promise.resolve():o}));return Promise.all(n).then(Jc)}fetchQuery(t){const e=this.defaultQueryOptions(t);e.retry===void 0&&(e.retry=!1);const r=Ot(this,Ao).build(this,e);return r.isStaleByTime(Hy(e.staleTime,r))?r.fetch(e):Promise.resolve(r.state.data)}prefetchQuery(t){return this.fetchQuery(t).then(Jc).catch(Jc)}fetchInfiniteQuery(t){return t.behavior=mY(t.pages),this.fetchQuery(t)}prefetchInfiniteQuery(t){return this.fetchInfiniteQuery(t).then(Jc).catch(Jc)}ensureInfiniteQueryData(t){return t.behavior=mY(t.pages),this.ensureQueryData(t)}resumePausedMutations(){return jM.isOnline()?Ot(this,_y).resumePausedMutations():Promise.resolve()}getQueryCache(){return Ot(this,Ao)}getMutationCache(){return Ot(this,_y)}getDefaultOptions(){return Ot(this,by)}setDefaultOptions(t){On(this,by,t)}setQueryDefaults(t,e){Ot(this,y1).set(O_(t),{queryKey:t,defaultOptions:e})}getQueryDefaults(t){const e=[...Ot(this,y1).values()],r={};return e.forEach(n=>{Q2(t,n.queryKey)&&Object.assign(r,n.defaultOptions)}),r}setMutationDefaults(t,e){Ot(this,x1).set(O_(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){const e=[...Ot(this,x1).values()],r={};return e.forEach(n=>{Q2(t,n.mutationKey)&&Object.assign(r,n.defaultOptions)}),r}defaultQueryOptions(t){if(t._defaulted)return t;const e={...Ot(this,by).queries,...this.getQueryDefaults(t.queryKey),...t,_defaulted:!0};return e.queryHash||(e.queryHash=c8(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===u8&&(e.enabled=!1),e}defaultMutationOptions(t){return t!=null&&t._defaulted?t:{...Ot(this,by).mutations,...(t==null?void 0:t.mutationKey)&&this.getMutationDefaults(t.mutationKey),...t,_defaulted:!0}}clear(){Ot(this,Ao).clear(),Ot(this,_y).clear()}},Ao=new WeakMap,_y=new WeakMap,by=new WeakMap,y1=new WeakMap,x1=new WeakMap,wy=new WeakMap,v1=new WeakMap,_1=new WeakMap,lse),Tu,ea,iT,Xc,u_,b1,jy,Sy,aT,w1,j1,d_,h_,Ny,S1,_a,LC,z5,B5,$5,U5,V5,q5,H5,Cle,cse,cAe=(cse=class extends Oj{constructor(e,r){super();Es(this,_a);Es(this,Tu);Es(this,ea);Es(this,iT);Es(this,Xc);Es(this,u_);Es(this,b1);Es(this,jy);Es(this,Sy);Es(this,aT);Es(this,w1);Es(this,j1);Es(this,d_);Es(this,h_);Es(this,Ny);Es(this,S1,new Set);this.options=r,On(this,Tu,e),On(this,Sy,null),On(this,jy,F5()),this.options.experimental_prefetchInRender||Ot(this,jy).reject(new Error("experimental_prefetchInRender feature flag is not enabled")),this.bindMethods(),this.setOptions(r)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(Ot(this,ea).addObserver(this),yY(Ot(this,ea),this.options)?Ei(this,_a,LC).call(this):this.updateResult(),Ei(this,_a,U5).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return W5(Ot(this,ea),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return W5(Ot(this,ea),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,Ei(this,_a,V5).call(this),Ei(this,_a,q5).call(this),Ot(this,ea).removeObserver(this)}setOptions(e){const r=this.options,n=Ot(this,ea);if(this.options=Ot(this,Tu).defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof Xd(this.options.enabled,Ot(this,ea))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");Ei(this,_a,H5).call(this),Ot(this,ea).setOptions(this.options),r._defaulted&&!wM(this.options,r)&&Ot(this,Tu).getQueryCache().notify({type:"observerOptionsUpdated",query:Ot(this,ea),observer:this});const i=this.hasListeners();i&&xY(Ot(this,ea),n,this.options,r)&&Ei(this,_a,LC).call(this),this.updateResult(),i&&(Ot(this,ea)!==n||Xd(this.options.enabled,Ot(this,ea))!==Xd(r.enabled,Ot(this,ea))||Hy(this.options.staleTime,Ot(this,ea))!==Hy(r.staleTime,Ot(this,ea)))&&Ei(this,_a,z5).call(this);const o=Ei(this,_a,B5).call(this);i&&(Ot(this,ea)!==n||Xd(this.options.enabled,Ot(this,ea))!==Xd(r.enabled,Ot(this,ea))||o!==Ot(this,Ny))&&Ei(this,_a,$5).call(this,o)}getOptimisticResult(e){const r=Ot(this,Tu).getQueryCache().build(Ot(this,Tu),e),n=this.createResult(r,e);return dAe(this,n)&&(On(this,Xc,n),On(this,b1,this.options),On(this,u_,Ot(this,ea).state)),n}getCurrentResult(){return Ot(this,Xc)}trackResult(e,r){return new Proxy(e,{get:(n,i)=>(this.trackProp(i),r==null||r(i),Reflect.get(n,i))})}trackProp(e){Ot(this,S1).add(e)}getCurrentQuery(){return Ot(this,ea)}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const r=Ot(this,Tu).defaultQueryOptions(e),n=Ot(this,Tu).getQueryCache().build(Ot(this,Tu),r);return n.fetch().then(()=>this.createResult(n,r))}fetch(e){return Ei(this,_a,LC).call(this,{...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),Ot(this,Xc)))}createResult(e,r){var X;const n=Ot(this,ea),i=this.options,o=Ot(this,Xc),c=Ot(this,u_),a=Ot(this,b1),g=e!==n?e.state:Ot(this,iT),{state:_}=e;let j={..._},N=!1,C;if(r._optimisticResults){const ie=this.hasListeners(),he=!ie&&yY(e,r),xe=ie&&xY(e,n,r,i);(he||xe)&&(j={...j,...Sle(_.data,e.options)}),r._optimisticResults==="isRestoring"&&(j.fetchStatus="idle")}let{error:P,errorUpdatedAt:A,status:I}=j;C=j.data;let O=!1;if(r.placeholderData!==void 0&&C===void 0&&I==="pending"){let ie;o!=null&&o.isPlaceholderData&&r.placeholderData===(a==null?void 0:a.placeholderData)?(ie=o.data,O=!0):ie=typeof r.placeholderData=="function"?r.placeholderData((X=Ot(this,j1))==null?void 0:X.state.data,Ot(this,j1)):r.placeholderData,ie!==void 0&&(I="success",C=L5(o==null?void 0:o.data,ie,r),N=!0)}if(r.select&&C!==void 0&&!O)if(o&&C===(c==null?void 0:c.data)&&r.select===Ot(this,aT))C=Ot(this,w1);else try{On(this,aT,r.select),C=r.select(C),C=L5(o==null?void 0:o.data,C,r),On(this,w1,C),On(this,Sy,null)}catch(ie){On(this,Sy,ie)}Ot(this,Sy)&&(P=Ot(this,Sy),C=Ot(this,w1),A=Date.now(),I="error");const R=j.fetchStatus==="fetching",z=I==="pending",W=I==="error",V=z&&R,K=C!==void 0,te={status:I,fetchStatus:j.fetchStatus,isPending:z,isSuccess:I==="success",isError:W,isInitialLoading:V,isLoading:V,data:C,dataUpdatedAt:j.dataUpdatedAt,error:P,errorUpdatedAt:A,failureCount:j.fetchFailureCount,failureReason:j.fetchFailureReason,errorUpdateCount:j.errorUpdateCount,isFetched:j.dataUpdateCount>0||j.errorUpdateCount>0,isFetchedAfterMount:j.dataUpdateCount>g.dataUpdateCount||j.errorUpdateCount>g.errorUpdateCount,isFetching:R,isRefetching:R&&!z,isLoadingError:W&&!K,isPaused:j.fetchStatus==="paused",isPlaceholderData:N,isRefetchError:W&&K,isStale:h8(e,r),refetch:this.refetch,promise:Ot(this,jy),isEnabled:Xd(r.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const ie=pe=>{te.status==="error"?pe.reject(te.error):te.data!==void 0&&pe.resolve(te.data)},he=()=>{const pe=On(this,jy,te.promise=F5());ie(pe)},xe=Ot(this,jy);switch(xe.status){case"pending":e.queryHash===n.queryHash&&ie(xe);break;case"fulfilled":(te.status==="error"||te.data!==xe.value)&&he();break;case"rejected":(te.status!=="error"||te.error!==xe.reason)&&he();break}}return te}updateResult(){const e=Ot(this,Xc),r=this.createResult(Ot(this,ea),this.options);if(On(this,u_,Ot(this,ea).state),On(this,b1,this.options),Ot(this,u_).data!==void 0&&On(this,j1,Ot(this,ea)),wM(r,e))return;On(this,Xc,r);const n=()=>{if(!e)return!0;const{notifyOnChangeProps:i}=this.options,o=typeof i=="function"?i():i;if(o==="all"||!o&&!Ot(this,S1).size)return!0;const c=new Set(o??Ot(this,S1));return this.options.throwOnError&&c.add("error"),Object.keys(Ot(this,Xc)).some(a=>{const m=a;return Ot(this,Xc)[m]!==e[m]&&c.has(m)})};Ei(this,_a,Cle).call(this,{listeners:n()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&Ei(this,_a,U5).call(this)}},Tu=new WeakMap,ea=new WeakMap,iT=new WeakMap,Xc=new WeakMap,u_=new WeakMap,b1=new WeakMap,jy=new WeakMap,Sy=new WeakMap,aT=new WeakMap,w1=new WeakMap,j1=new WeakMap,d_=new WeakMap,h_=new WeakMap,Ny=new WeakMap,S1=new WeakMap,_a=new WeakSet,LC=function(e){Ei(this,_a,H5).call(this);let r=Ot(this,ea).fetch(this.options,e);return e!=null&&e.throwOnError||(r=r.catch(Jc)),r},z5=function(){Ei(this,_a,V5).call(this);const e=Hy(this.options.staleTime,Ot(this,ea));if(M_||Ot(this,Xc).isStale||!R5(e))return;const n=gle(Ot(this,Xc).dataUpdatedAt,e)+1;On(this,d_,setTimeout(()=>{Ot(this,Xc).isStale||this.updateResult()},n))},B5=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(Ot(this,ea)):this.options.refetchInterval)??!1},$5=function(e){Ei(this,_a,q5).call(this),On(this,Ny,e),!(M_||Xd(this.options.enabled,Ot(this,ea))===!1||!R5(Ot(this,Ny))||Ot(this,Ny)===0)&&On(this,h_,setInterval(()=>{(this.options.refetchIntervalInBackground||d8.isFocused())&&Ei(this,_a,LC).call(this)},Ot(this,Ny)))},U5=function(){Ei(this,_a,z5).call(this),Ei(this,_a,$5).call(this,Ei(this,_a,B5).call(this))},V5=function(){Ot(this,d_)&&(clearTimeout(Ot(this,d_)),On(this,d_,void 0))},q5=function(){Ot(this,h_)&&(clearInterval(Ot(this,h_)),On(this,h_,void 0))},H5=function(){const e=Ot(this,Tu).getQueryCache().build(Ot(this,Tu),this.options);if(e===Ot(this,ea))return;const r=Ot(this,ea);On(this,ea,e),On(this,iT,e.state),this.hasListeners()&&(r==null||r.removeObserver(this),e.addObserver(this))},Cle=function(e){kl.batch(()=>{e.listeners&&this.listeners.forEach(r=>{r(Ot(this,Xc))}),Ot(this,Tu).getQueryCache().notify({query:Ot(this,ea),type:"observerResultsUpdated"})})},cse);function uAe(t,e){return Xd(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&e.retryOnMount===!1)}function yY(t,e){return uAe(t,e)||t.state.data!==void 0&&W5(t,e,e.refetchOnMount)}function W5(t,e,r){if(Xd(e.enabled,t)!==!1&&Hy(e.staleTime,t)!=="static"){const n=typeof r=="function"?r(t):r;return n==="always"||n!==!1&&h8(t,e)}return!1}function xY(t,e,r,n){return(t!==e||Xd(n.enabled,t)===!1)&&(!r.suspense||t.state.status!=="error")&&h8(t,r)}function h8(t,e){return Xd(e.enabled,t)!==!1&&t.isStaleByTime(Hy(e.staleTime,t))}function dAe(t,e){return!wM(t.getCurrentResult(),e)}var Cy,ky,Eu,Cm,zm,SI,G5,use,hAe=(use=class extends Oj{constructor(r,n){super();Es(this,zm);Es(this,Cy);Es(this,ky);Es(this,Eu);Es(this,Cm);On(this,Cy,r),this.setOptions(n),this.bindMethods(),Ei(this,zm,SI).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(r){var i;const n=this.options;this.options=Ot(this,Cy).defaultMutationOptions(r),wM(this.options,n)||Ot(this,Cy).getMutationCache().notify({type:"observerOptionsUpdated",mutation:Ot(this,Eu),observer:this}),n!=null&&n.mutationKey&&this.options.mutationKey&&O_(n.mutationKey)!==O_(this.options.mutationKey)?this.reset():((i=Ot(this,Eu))==null?void 0:i.state.status)==="pending"&&Ot(this,Eu).setOptions(this.options)}onUnsubscribe(){var r;this.hasListeners()||(r=Ot(this,Eu))==null||r.removeObserver(this)}onMutationUpdate(r){Ei(this,zm,SI).call(this),Ei(this,zm,G5).call(this,r)}getCurrentResult(){return Ot(this,ky)}reset(){var r;(r=Ot(this,Eu))==null||r.removeObserver(this),On(this,Eu,void 0),Ei(this,zm,SI).call(this),Ei(this,zm,G5).call(this)}mutate(r,n){var i;return On(this,Cm,n),(i=Ot(this,Eu))==null||i.removeObserver(this),On(this,Eu,Ot(this,Cy).getMutationCache().build(Ot(this,Cy),this.options)),Ot(this,Eu).addObserver(this),Ot(this,Eu).execute(r)}},Cy=new WeakMap,ky=new WeakMap,Eu=new WeakMap,Cm=new WeakMap,zm=new WeakSet,SI=function(){var n;const r=((n=Ot(this,Eu))==null?void 0:n.state)??Nle();On(this,ky,{...r,isPending:r.status==="pending",isSuccess:r.status==="success",isError:r.status==="error",isIdle:r.status==="idle",mutate:this.mutate,reset:this.reset})},G5=function(r){kl.batch(()=>{var n,i,o,c,a,m,g,_;if(Ot(this,Cm)&&this.hasListeners()){const j=Ot(this,ky).variables,N=Ot(this,ky).context;(r==null?void 0:r.type)==="success"?((i=(n=Ot(this,Cm)).onSuccess)==null||i.call(n,r.data,j,N),(c=(o=Ot(this,Cm)).onSettled)==null||c.call(o,r.data,null,j,N)):(r==null?void 0:r.type)==="error"&&((m=(a=Ot(this,Cm)).onError)==null||m.call(a,r.error,j,N),(_=(g=Ot(this,Cm)).onSettled)==null||_.call(g,void 0,r.error,j,N))}this.listeners.forEach(j=>{j(Ot(this,ky))})})},use),kle=D.createContext(void 0),Wn=t=>{const e=D.useContext(kle);if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},fAe=({client:t,children:e})=>(D.useEffect(()=>(t.mount(),()=>{t.unmount()}),[t]),s.jsx(kle.Provider,{value:t,children:e})),Tle=D.createContext(!1),pAe=()=>D.useContext(Tle);Tle.Provider;function mAe(){let t=!1;return{clearReset:()=>{t=!1},reset:()=>{t=!0},isReset:()=>t}}var gAe=D.createContext(mAe()),yAe=()=>D.useContext(gAe),xAe=(t,e)=>{(t.suspense||t.throwOnError||t.experimental_prefetchInRender)&&(e.isReset()||(t.retryOnMount=!1))},vAe=t=>{D.useEffect(()=>{t.clearReset()},[t])},_Ae=({result:t,errorResetBoundary:e,throwOnError:r,query:n,suspense:i})=>t.isError&&!e.isReset()&&!t.isFetching&&n&&(i&&t.data===void 0||vle(r,[t.error,n])),bAe=t=>{if(t.suspense){const e=n=>n==="static"?n:Math.max(n??1e3,1e3),r=t.staleTime;t.staleTime=typeof r=="function"?(...n)=>e(r(...n)):e(r),typeof t.gcTime=="number"&&(t.gcTime=Math.max(t.gcTime,1e3))}},wAe=(t,e)=>t.isLoading&&t.isFetching&&!e,jAe=(t,e)=>(t==null?void 0:t.suspense)&&e.isPending,vY=(t,e,r)=>e.fetchOptimistic(t).catch(()=>{r.clearReset()});function SAe(t,e,r){var j,N,C,P,A;const n=pAe(),i=yAe(),o=Wn(),c=o.defaultQueryOptions(t);(N=(j=o.getDefaultOptions().queries)==null?void 0:j._experimental_beforeQuery)==null||N.call(j,c),c._optimisticResults=n?"isRestoring":"optimistic",bAe(c),xAe(c,i),vAe(i);const a=!o.getQueryCache().get(c.queryHash),[m]=D.useState(()=>new e(o,c)),g=m.getOptimisticResult(c),_=!n&&t.subscribed!==!1;if(D.useSyncExternalStore(D.useCallback(I=>{const O=_?m.subscribe(kl.batchCalls(I)):Jc;return m.updateResult(),O},[m,_]),()=>m.getCurrentResult(),()=>m.getCurrentResult()),D.useEffect(()=>{m.setOptions(c)},[c,m]),jAe(c,g))throw vY(c,m,i);if(_Ae({result:g,errorResetBoundary:i,throwOnError:c.throwOnError,query:o.getQueryCache().get(c.queryHash),suspense:c.suspense}))throw g.error;if((P=(C=o.getDefaultOptions().queries)==null?void 0:C._experimental_afterQuery)==null||P.call(C,c,g),c.experimental_prefetchInRender&&!M_&&wAe(g,n)){const I=a?vY(c,m,i):(A=o.getQueryCache().get(c.queryHash))==null?void 0:A.promise;I==null||I.catch(Jc).finally(()=>{m.updateResult()})}return c.notifyOnChangeProps?g:m.trackResult(g)}function Sr(t,e){return SAe(t,cAe)}function zr(t,e){const r=Wn(),[n]=D.useState(()=>new hAe(r,t));D.useEffect(()=>{n.setOptions(t)},[n,t]);const i=D.useSyncExternalStore(D.useCallback(c=>n.subscribe(kl.batchCalls(c)),[n]),()=>n.getCurrentResult(),()=>n.getCurrentResult()),o=D.useCallback((c,a)=>{n.mutate(c,a).catch(Jc)},[n]);if(i.error&&vle(n.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:o,mutateAsync:i.mutate}}/** * @remix-run/router v1.23.0 * * 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 J2(){return J2=Object.assign?Object.assign.bind():function(t){for(var e=1;e"u")throw new Error(e)}function Ele(t,e){if(!t){typeof console<"u"&&console.warn(e);try{throw new Error(e)}catch{}}}function CAe(){return Math.random().toString(36).substr(2,8)}function bY(t,e){return{usr:t.state,key:t.key,idx:e}}function K5(t,e,r,n){return r===void 0&&(r=null),J2({pathname:typeof t=="string"?t:t.pathname,search:"",hash:""},typeof e=="string"?Rj(e):e,{state:r,key:e&&e.key||n||CAe()})}function SM(t){let{pathname:e="/",search:r="",hash:n=""}=t;return r&&r!=="?"&&(e+=r.charAt(0)==="?"?r:"?"+r),n&&n!=="#"&&(e+=n.charAt(0)==="#"?n:"#"+n),e}function Rj(t){let e={};if(t){let r=t.indexOf("#");r>=0&&(e.hash=t.substr(r),t=t.substr(0,r));let n=t.indexOf("?");n>=0&&(e.search=t.substr(n),t=t.substr(0,n)),t&&(e.pathname=t)}return e}function kAe(t,e,r,n){n===void 0&&(n={});let{window:i=document.defaultView,v5Compat:o=!1}=n,c=i.history,a=Ay.Pop,m=null,g=_();g==null&&(g=0,c.replaceState(J2({},c.state,{idx:g}),""));function _(){return(c.state||{idx:null}).idx}function j(){a=Ay.Pop;let I=_(),O=I==null?null:I-g;g=I,m&&m({action:a,location:A.location,delta:O})}function N(I,O){a=Ay.Push;let R=K5(A.location,I,O);g=_()+1;let z=bY(R,g),W=A.createHref(R);try{c.pushState(z,"",W)}catch(V){if(V instanceof DOMException&&V.name==="DataCloneError")throw V;i.location.assign(W)}o&&m&&m({action:a,location:A.location,delta:1})}function C(I,O){a=Ay.Replace;let R=K5(A.location,I,O);g=_();let z=bY(R,g),W=A.createHref(R);c.replaceState(z,"",W),o&&m&&m({action:a,location:A.location,delta:0})}function P(I){let O=i.location.origin!=="null"?i.location.origin:i.location.href,R=typeof I=="string"?I:SM(I);return R=R.replace(/ $/,"%20"),Ko(O,"No window.location.(origin|href) available to create URL for href: "+R),new URL(R,O)}let A={get action(){return a},get location(){return t(i,c)},listen(I){if(m)throw new Error("A history only accepts one active listener");return i.addEventListener(_Y,j),m=I,()=>{i.removeEventListener(_Y,j),m=null}},createHref(I){return e(i,I)},createURL:P,encodeLocation(I){let O=P(I);return{pathname:O.pathname,search:O.search,hash:O.hash}},push:N,replace:C,go(I){return c.go(I)}};return A}var wY;(function(t){t.data="data",t.deferred="deferred",t.redirect="redirect",t.error="error"})(wY||(wY={}));function TAe(t,e,r){return r===void 0&&(r="/"),EAe(t,e,r)}function EAe(t,e,r,n){let i=typeof e=="string"?Rj(e):e,o=f8(i.pathname||"/",r);if(o==null)return null;let c=Ale(t);AAe(c);let a=null;for(let m=0;a==null&&m{let m={relativePath:a===void 0?o.path||"":a,caseSensitive:o.caseSensitive===!0,childrenIndex:c,route:o};m.relativePath.startsWith("/")&&(Ko(m.relativePath.startsWith(n),'Absolute route path "'+m.relativePath+'" nested under path '+('"'+n+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),m.relativePath=m.relativePath.slice(n.length));let g=Wy([n,m.relativePath]),_=r.concat(m);o.children&&o.children.length>0&&(Ko(o.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+g+'".')),Ale(o.children,e,_,g)),!(o.path==null&&!o.index)&&e.push({path:g,score:LAe(g,o.index),routesMeta:_})};return t.forEach((o,c)=>{var a;if(o.path===""||!((a=o.path)!=null&&a.includes("?")))i(o,c);else for(let m of Ple(o.path))i(o,c,m)}),e}function Ple(t){let e=t.split("/");if(e.length===0)return[];let[r,...n]=e,i=r.endsWith("?"),o=r.replace(/\?$/,"");if(n.length===0)return i?[o,""]:[o];let c=Ple(n.join("/")),a=[];return a.push(...c.map(m=>m===""?o:[o,m].join("/"))),i&&a.push(...c),a.map(m=>t.startsWith("/")&&m===""?"/":m)}function AAe(t){t.sort((e,r)=>e.score!==r.score?r.score-e.score:FAe(e.routesMeta.map(n=>n.childrenIndex),r.routesMeta.map(n=>n.childrenIndex)))}const PAe=/^:[\w-]+$/,IAe=3,MAe=2,OAe=1,RAe=10,DAe=-2,jY=t=>t==="*";function LAe(t,e){let r=t.split("/"),n=r.length;return r.some(jY)&&(n+=DAe),e&&(n+=MAe),r.filter(i=>!jY(i)).reduce((i,o)=>i+(PAe.test(o)?IAe:o===""?OAe:RAe),n)}function FAe(t,e){return t.length===e.length&&t.slice(0,-1).every((n,i)=>n===e[i])?t[t.length-1]-e[e.length-1]:0}function zAe(t,e,r){let{routesMeta:n}=t,i={},o="/",c=[];for(let a=0;a{let{paramName:N,isOptional:C}=_;if(N==="*"){let A=a[j]||"";c=o.slice(0,o.length-A.length).replace(/(.)\/+$/,"$1")}const P=a[j];return C&&!P?g[N]=void 0:g[N]=(P||"").replace(/%2F/g,"/"),g},{}),pathname:o,pathnameBase:c,pattern:t}}function $Ae(t,e,r){e===void 0&&(e=!1),r===void 0&&(r=!0),Ele(t==="*"||!t.endsWith("*")||t.endsWith("/*"),'Route path "'+t+'" will be treated as if it were '+('"'+t.replace(/\*$/,"/*")+'" because the `*` character must ')+"always follow a `/` in the pattern. To get rid of this warning, "+('please change the route path to "'+t.replace(/\*$/,"/*")+'".'));let n=[],i="^"+t.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(c,a,m)=>(n.push({paramName:a,isOptional:m!=null}),m?"/?([^\\/]+)?":"/([^\\/]+)"));return t.endsWith("*")?(n.push({paramName:"*"}),i+=t==="*"||t==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):r?i+="\\/*$":t!==""&&t!=="/"&&(i+="(?:(?=\\/|$))"),[new RegExp(i,e?void 0:"i"),n]}function UAe(t){try{return t.split("/").map(e=>decodeURIComponent(e).replace(/\//g,"%2F")).join("/")}catch(e){return Ele(!1,'The URL path "'+t+'" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent '+("encoding ("+e+").")),t}}function f8(t,e){if(e==="/")return t;if(!t.toLowerCase().startsWith(e.toLowerCase()))return null;let r=e.endsWith("/")?e.length-1:e.length,n=t.charAt(r);return n&&n!=="/"?null:t.slice(r)||"/"}function VAe(t,e){e===void 0&&(e="/");let{pathname:r,search:n="",hash:i=""}=typeof t=="string"?Rj(t):t;return{pathname:r?r.startsWith("/")?r:qAe(r,e):e,search:GAe(n),hash:KAe(i)}}function qAe(t,e){let r=e.replace(/\/+$/,"").split("/");return t.split("/").forEach(i=>{i===".."?r.length>1&&r.pop():i!=="."&&r.push(i)}),r.length>1?r.join("/"):"/"}function BF(t,e,r,n){return"Cannot include a '"+t+"' character in a manually specified "+("`to."+e+"` field ["+JSON.stringify(n)+"]. Please separate it out to the ")+("`to."+r+"` field. Alternatively you may provide the full path as ")+'a string in and the router will parse it for you.'}function HAe(t){return t.filter((e,r)=>r===0||e.route.path&&e.route.path.length>0)}function p8(t,e){let r=HAe(t);return e?r.map((n,i)=>i===r.length-1?n.pathname:n.pathnameBase):r.map(n=>n.pathnameBase)}function m8(t,e,r,n){n===void 0&&(n=!1);let i;typeof t=="string"?i=Rj(t):(i=J2({},t),Ko(!i.pathname||!i.pathname.includes("?"),BF("?","pathname","search",i)),Ko(!i.pathname||!i.pathname.includes("#"),BF("#","pathname","hash",i)),Ko(!i.search||!i.search.includes("#"),BF("#","search","hash",i)));let o=t===""||i.pathname==="",c=o?"/":i.pathname,a;if(c==null)a=r;else{let j=e.length-1;if(!n&&c.startsWith("..")){let N=c.split("/");for(;N[0]==="..";)N.shift(),j-=1;i.pathname=N.join("/")}a=j>=0?e[j]:"/"}let m=VAe(i,a),g=c&&c!=="/"&&c.endsWith("/"),_=(o||c===".")&&r.endsWith("/");return!m.pathname.endsWith("/")&&(g||_)&&(m.pathname+="/"),m}const Wy=t=>t.join("/").replace(/\/\/+/g,"/"),WAe=t=>t.replace(/\/+$/,"").replace(/^\/*/,"/"),GAe=t=>!t||t==="?"?"":t.startsWith("?")?t:"?"+t,KAe=t=>!t||t==="#"?"":t.startsWith("#")?t:"#"+t;function ZAe(t){return t!=null&&typeof t.status=="number"&&typeof t.statusText=="string"&&typeof t.internal=="boolean"&&"data"in t}const Ile=["post","put","patch","delete"];new Set(Ile);const YAe=["get",...Ile];new Set(YAe);/** * React Router v6.30.1 * * 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 ek(){return ek=Object.assign?Object.assign.bind():function(t){for(var e=1;e{a.current=!0}),D.useCallback(function(g,_){if(_===void 0&&(_={}),!a.current)return;if(typeof g=="number"){n.go(g);return}let j=m8(g,JSON.parse(c),o,_.relative==="path");t==null&&e!=="/"&&(j.pathname=j.pathname==="/"?e:Wy([e,j.pathname])),(_.replace?n.replace:n.push)(j,_.state,_)},[e,n,c,o,t])}function mu(){let{matches:t}=D.useContext(tg),e=t[t.length-1];return e?e.params:{}}function Rle(t,e){let{relative:r}=e===void 0?{}:e,{future:n}=D.useContext(yx),{matches:i}=D.useContext(tg),{pathname:o}=xx(),c=JSON.stringify(p8(i,n.v7_relativeSplatPath));return D.useMemo(()=>m8(t,JSON.parse(c),o,r==="path"),[t,c,o,r])}function ePe(t,e){return tPe(t,e)}function tPe(t,e,r,n){Dj()||Ko(!1);let{navigator:i}=D.useContext(yx),{matches:o}=D.useContext(tg),c=o[o.length-1],a=c?c.params:{};c&&c.pathname;let m=c?c.pathnameBase:"/";c&&c.route;let g=xx(),_;if(e){var j;let I=typeof e=="string"?Rj(e):e;m==="/"||(j=I.pathname)!=null&&j.startsWith(m)||Ko(!1),_=I}else _=g;let N=_.pathname||"/",C=N;if(m!=="/"){let I=m.replace(/^\//,"").split("/");C="/"+N.replace(/^\//,"").split("/").slice(I.length).join("/")}let P=TAe(t,{pathname:C}),A=aPe(P&&P.map(I=>Object.assign({},I,{params:Object.assign({},a,I.params),pathname:Wy([m,i.encodeLocation?i.encodeLocation(I.pathname).pathname:I.pathname]),pathnameBase:I.pathnameBase==="/"?m:Wy([m,i.encodeLocation?i.encodeLocation(I.pathnameBase).pathname:I.pathnameBase])})),o,r,n);return e&&A?D.createElement(hD.Provider,{value:{location:ek({pathname:"/",search:"",hash:"",state:null,key:"default"},_),navigationType:Ay.Pop}},A):A}function rPe(){let t=uPe(),e=ZAe(t)?t.status+" "+t.statusText:t instanceof Error?t.message:JSON.stringify(t),r=t instanceof Error?t.stack:null,i={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return D.createElement(D.Fragment,null,D.createElement("h2",null,"Unexpected Application Error!"),D.createElement("h3",{style:{fontStyle:"italic"}},e),r?D.createElement("pre",{style:i},r):null,null)}const nPe=D.createElement(rPe,null);class sPe extends D.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,r){return r.location!==e.location||r.revalidation!=="idle"&&e.revalidation==="idle"?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:e.error!==void 0?e.error:r.error,location:r.location,revalidation:e.revalidation||r.revalidation}}componentDidCatch(e,r){console.error("React Router caught the following error during render",e,r)}render(){return this.state.error!==void 0?D.createElement(tg.Provider,{value:this.props.routeContext},D.createElement(Mle.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function iPe(t){let{routeContext:e,match:r,children:n}=t,i=D.useContext(g8);return i&&i.static&&i.staticContext&&(r.route.errorElement||r.route.ErrorBoundary)&&(i.staticContext._deepestRenderedBoundaryId=r.route.id),D.createElement(tg.Provider,{value:e},n)}function aPe(t,e,r,n){var i;if(e===void 0&&(e=[]),r===void 0&&(r=null),n===void 0&&(n=null),t==null){var o;if(!r)return null;if(r.errors)t=r.matches;else if((o=n)!=null&&o.v7_partialHydration&&e.length===0&&!r.initialized&&r.matches.length>0)t=r.matches;else return null}let c=t,a=(i=r)==null?void 0:i.errors;if(a!=null){let _=c.findIndex(j=>j.route.id&&(a==null?void 0:a[j.route.id])!==void 0);_>=0||Ko(!1),c=c.slice(0,Math.min(c.length,_+1))}let m=!1,g=-1;if(r&&n&&n.v7_partialHydration)for(let _=0;_=0?c=c.slice(0,g+1):c=[c[0]];break}}}return c.reduceRight((_,j,N)=>{let C,P=!1,A=null,I=null;r&&(C=a&&j.route.id?a[j.route.id]:void 0,A=j.route.errorElement||nPe,m&&(g<0&&N===0?(hPe("route-fallback"),P=!0,I=null):g===N&&(P=!0,I=j.route.hydrateFallbackElement||null)));let O=e.concat(c.slice(0,N+1)),R=()=>{let z;return C?z=A:P?z=I:j.route.Component?z=D.createElement(j.route.Component,null):j.route.element?z=j.route.element:z=_,D.createElement(iPe,{match:j,routeContext:{outlet:_,matches:O,isDataRoute:r!=null},children:z})};return r&&(j.route.ErrorBoundary||j.route.errorElement||N===0)?D.createElement(sPe,{location:r.location,revalidation:r.revalidation,component:A,error:C,children:R(),routeContext:{outlet:null,matches:O,isDataRoute:!0}}):R()},null)}var Dle=function(t){return t.UseBlocker="useBlocker",t.UseRevalidator="useRevalidator",t.UseNavigateStable="useNavigate",t}(Dle||{}),Lle=function(t){return t.UseBlocker="useBlocker",t.UseLoaderData="useLoaderData",t.UseActionData="useActionData",t.UseRouteError="useRouteError",t.UseNavigation="useNavigation",t.UseRouteLoaderData="useRouteLoaderData",t.UseMatches="useMatches",t.UseRevalidator="useRevalidator",t.UseNavigateStable="useNavigate",t.UseRouteId="useRouteId",t}(Lle||{});function oPe(t){let e=D.useContext(g8);return e||Ko(!1),e}function lPe(t){let e=D.useContext(XAe);return e||Ko(!1),e}function cPe(t){let e=D.useContext(tg);return e||Ko(!1),e}function Fle(t){let e=cPe(),r=e.matches[e.matches.length-1];return r.route.id||Ko(!1),r.route.id}function uPe(){var t;let e=D.useContext(Mle),r=lPe(),n=Fle();return e!==void 0?e:(t=r.errors)==null?void 0:t[n]}function dPe(){let{router:t}=oPe(Dle.UseNavigateStable),e=Fle(Lle.UseNavigateStable),r=D.useRef(!1);return Ole(()=>{r.current=!0}),D.useCallback(function(i,o){o===void 0&&(o={}),r.current&&(typeof i=="number"?t.navigate(i):t.navigate(i,ek({fromRouteId:e},o)))},[t,e])}const SY={};function hPe(t,e,r){SY[t]||(SY[t]=!0)}function fPe(t,e){t==null||t.v7_startTransition,t==null||t.v7_relativeSplatPath}function $F(t){let{to:e,replace:r,state:n,relative:i}=t;Dj()||Ko(!1);let{future:o,static:c}=D.useContext(yx),{matches:a}=D.useContext(tg),{pathname:m}=xx(),g=Bs(),_=m8(e,p8(a,o.v7_relativeSplatPath),m,i==="path"),j=JSON.stringify(_);return D.useEffect(()=>g(JSON.parse(j),{replace:r,state:n,relative:i}),[g,j,i,r,n]),null}function jn(t){Ko(!1)}function pPe(t){let{basename:e="/",children:r=null,location:n,navigationType:i=Ay.Pop,navigator:o,static:c=!1,future:a}=t;Dj()&&Ko(!1);let m=e.replace(/^\/*/,"/"),g=D.useMemo(()=>({basename:m,navigator:o,static:c,future:ek({v7_relativeSplatPath:!1},a)}),[m,a,o,c]);typeof n=="string"&&(n=Rj(n));let{pathname:_="/",search:j="",hash:N="",state:C=null,key:P="default"}=n,A=D.useMemo(()=>{let I=f8(_,m);return I==null?null:{location:{pathname:I,search:j,hash:N,state:C,key:P},navigationType:i}},[m,_,j,N,C,P,i]);return A==null?null:D.createElement(yx.Provider,{value:g},D.createElement(hD.Provider,{children:r,value:A}))}function mPe(t){let{children:e,location:r}=t;return ePe(Z5(e),r)}new Promise(()=>{});function Z5(t,e){e===void 0&&(e=[]);let r=[];return D.Children.forEach(t,(n,i)=>{if(!D.isValidElement(n))return;let o=[...e,i];if(n.type===D.Fragment){r.push.apply(r,Z5(n.props.children,o));return}n.type!==jn&&Ko(!1),!n.props.index||!n.props.children||Ko(!1);let c={id:n.props.id||o.join("-"),caseSensitive:n.props.caseSensitive,element:n.props.element,Component:n.props.Component,index:n.props.index,path:n.props.path,loader:n.props.loader,action:n.props.action,errorElement:n.props.errorElement,ErrorBoundary:n.props.ErrorBoundary,hasErrorBoundary:n.props.ErrorBoundary!=null||n.props.errorElement!=null,shouldRevalidate:n.props.shouldRevalidate,handle:n.props.handle,lazy:n.props.lazy};n.props.children&&(c.children=Z5(n.props.children,o)),r.push(c)}),r}/** * React Router DOM v6.30.1 * * 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 Y5(){return Y5=Object.assign?Object.assign.bind():function(t){for(var e=1;e=0)&&(r[i]=t[i]);return r}function yPe(t){return!!(t.metaKey||t.altKey||t.ctrlKey||t.shiftKey)}function xPe(t,e){return t.button===0&&(!e||e==="_self")&&!yPe(t)}function X5(t){return t===void 0&&(t=""),new URLSearchParams(typeof t=="string"||Array.isArray(t)||t instanceof URLSearchParams?t:Object.keys(t).reduce((e,r)=>{let n=t[r];return e.concat(Array.isArray(n)?n.map(i=>[r,i]):[[r,n]])},[]))}function vPe(t,e){let r=X5(t);return e&&e.forEach((n,i)=>{r.has(i)||e.getAll(i).forEach(o=>{r.append(i,o)})}),r}const _Pe=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],bPe="6";try{window.__reactRouterVersion=bPe}catch{}const wPe="startTransition",NY=ZV[wPe];function jPe(t){let{basename:e,children:r,future:n,window:i}=t,o=D.useRef();o.current==null&&(o.current=NAe({window:i,v5Compat:!0}));let c=o.current,[a,m]=D.useState({action:c.action,location:c.location}),{v7_startTransition:g}=n||{},_=D.useCallback(j=>{g&&NY?NY(()=>m(j)):m(j)},[m,g]);return D.useLayoutEffect(()=>c.listen(_),[c,_]),D.useEffect(()=>fPe(n),[n]),D.createElement(pPe,{basename:e,children:r,location:a.location,navigationType:a.action,navigator:c,future:n})}const SPe=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",NPe=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,jd=D.forwardRef(function(e,r){let{onClick:n,relative:i,reloadDocument:o,replace:c,state:a,target:m,to:g,preventScrollReset:_,viewTransition:j}=e,N=gPe(e,_Pe),{basename:C}=D.useContext(yx),P,A=!1;if(typeof g=="string"&&NPe.test(g)&&(P=g,SPe))try{let z=new URL(window.location.href),W=g.startsWith("//")?new URL(z.protocol+g):new URL(g),V=f8(W.pathname,C);W.origin===z.origin&&V!=null?g=V+W.search+W.hash:A=!0}catch{}let I=QAe(g,{relative:i}),O=CPe(g,{replace:c,state:a,target:m,preventScrollReset:_,relative:i,viewTransition:j});function R(z){n&&n(z),z.defaultPrevented||O(z)}return D.createElement("a",Y5({},N,{href:P||I,onClick:A||o?n:R,ref:r,target:m}))});var CY;(function(t){t.UseScrollRestoration="useScrollRestoration",t.UseSubmit="useSubmit",t.UseSubmitFetcher="useSubmitFetcher",t.UseFetcher="useFetcher",t.useViewTransitionState="useViewTransitionState"})(CY||(CY={}));var kY;(function(t){t.UseFetcher="useFetcher",t.UseFetchers="useFetchers",t.UseScrollRestoration="useScrollRestoration"})(kY||(kY={}));function CPe(t,e){let{target:r,replace:n,state:i,preventScrollReset:o,relative:c,viewTransition:a}=e===void 0?{}:e,m=Bs(),g=xx(),_=Rle(t,{relative:c});return D.useCallback(j=>{if(xPe(j,r)){j.preventDefault();let N=n!==void 0?n:SM(g)===SM(_);m(t,{replace:N,state:i,preventScrollReset:o,relative:c,viewTransition:a})}},[g,m,_,n,i,r,t,o,c,a])}function n0(t){let e=D.useRef(X5(t)),r=D.useRef(!1),n=xx(),i=D.useMemo(()=>vPe(n.search,r.current?null:e.current),[n.search]),o=Bs(),c=D.useCallback((a,m)=>{const g=X5(typeof a=="function"?a(i):a);r.current=!0,o("?"+g,m)},[o,i]);return[i,c]}var kPe=typeof Element<"u",TPe=typeof Map=="function",EPe=typeof Set=="function",APe=typeof ArrayBuffer=="function"&&!!ArrayBuffer.isView;function NI(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){if(t.constructor!==e.constructor)return!1;var r,n,i;if(Array.isArray(t)){if(r=t.length,r!=e.length)return!1;for(n=r;n--!==0;)if(!NI(t[n],e[n]))return!1;return!0}var o;if(TPe&&t instanceof Map&&e instanceof Map){if(t.size!==e.size)return!1;for(o=t.entries();!(n=o.next()).done;)if(!e.has(n.value[0]))return!1;for(o=t.entries();!(n=o.next()).done;)if(!NI(n.value[1],e.get(n.value[0])))return!1;return!0}if(EPe&&t instanceof Set&&e instanceof Set){if(t.size!==e.size)return!1;for(o=t.entries();!(n=o.next()).done;)if(!e.has(n.value[0]))return!1;return!0}if(APe&&ArrayBuffer.isView(t)&&ArrayBuffer.isView(e)){if(r=t.length,r!=e.length)return!1;for(n=r;n--!==0;)if(t[n]!==e[n])return!1;return!0}if(t.constructor===RegExp)return t.source===e.source&&t.flags===e.flags;if(t.valueOf!==Object.prototype.valueOf&&typeof t.valueOf=="function"&&typeof e.valueOf=="function")return t.valueOf()===e.valueOf();if(t.toString!==Object.prototype.toString&&typeof t.toString=="function"&&typeof e.toString=="function")return t.toString()===e.toString();if(i=Object.keys(t),r=i.length,r!==Object.keys(e).length)return!1;for(n=r;n--!==0;)if(!Object.prototype.hasOwnProperty.call(e,i[n]))return!1;if(kPe&&t instanceof Element)return!1;for(n=r;n--!==0;)if(!((i[n]==="_owner"||i[n]==="__v"||i[n]==="__o")&&t.$$typeof)&&!NI(t[i[n]],e[i[n]]))return!1;return!0}return t!==t&&e!==e}var PPe=function(e,r){try{return NI(e,r)}catch(n){if((n.message||"").match(/stack|recursion/i))return console.warn("react-fast-compare cannot handle circular refs"),!1;throw n}};const IPe=sa(PPe);var MPe=function(t,e,r,n,i,o,c,a){if(!t){var m;if(e===void 0)m=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var g=[r,n,i,o,c,a],_=0;m=new Error(e.replace(/%s/g,function(){return g[_++]})),m.name="Invariant Violation"}throw m.framesToPop=1,m}},OPe=MPe;const TY=sa(OPe);var RPe=function(e,r,n,i){var o=n?n.call(i,e,r):void 0;if(o!==void 0)return!!o;if(e===r)return!0;if(typeof e!="object"||!e||typeof r!="object"||!r)return!1;var c=Object.keys(e),a=Object.keys(r);if(c.length!==a.length)return!1;for(var m=Object.prototype.hasOwnProperty.bind(r),g=0;g(t.BASE="base",t.BODY="body",t.HEAD="head",t.HTML="html",t.LINK="link",t.META="meta",t.NOSCRIPT="noscript",t.SCRIPT="script",t.STYLE="style",t.TITLE="title",t.FRAGMENT="Symbol(react.fragment)",t))(zle||{}),UF={link:{rel:["amphtml","canonical","alternate"]},script:{type:["application/ld+json"]},meta:{charset:"",name:["generator","robots","description"],property:["og:type","og:title","og:url","og:image","og:image:alt","og:description","twitter:url","twitter:title","twitter:description","twitter:image","twitter:image:alt","twitter:card","twitter:site"]}},EY=Object.values(zle),y8={accesskey:"accessKey",charset:"charSet",class:"className",contenteditable:"contentEditable",contextmenu:"contextMenu","http-equiv":"httpEquiv",itemprop:"itemProp",tabindex:"tabIndex"},LPe=Object.entries(y8).reduce((t,[e,r])=>(t[r]=e,t),{}),mf="data-rh",r1={DEFAULT_TITLE:"defaultTitle",DEFER:"defer",ENCODE_SPECIAL_CHARACTERS:"encodeSpecialCharacters",ON_CHANGE_CLIENT_STATE:"onChangeClientState",TITLE_TEMPLATE:"titleTemplate",PRIORITIZE_SEO_TAGS:"prioritizeSeoTags"},n1=(t,e)=>{for(let r=t.length-1;r>=0;r-=1){const n=t[r];if(Object.prototype.hasOwnProperty.call(n,e))return n[e]}return null},FPe=t=>{let e=n1(t,"title");const r=n1(t,r1.TITLE_TEMPLATE);if(Array.isArray(e)&&(e=e.join("")),r&&e)return r.replace(/%s/g,()=>e);const n=n1(t,r1.DEFAULT_TITLE);return e||n||void 0},zPe=t=>n1(t,r1.ON_CHANGE_CLIENT_STATE)||(()=>{}),VF=(t,e)=>e.filter(r=>typeof r[t]<"u").map(r=>r[t]).reduce((r,n)=>({...r,...n}),{}),BPe=(t,e)=>e.filter(r=>typeof r.base<"u").map(r=>r.base).reverse().reduce((r,n)=>{if(!r.length){const i=Object.keys(n);for(let o=0;oconsole&&typeof console.warn=="function"&&console.warn(t),dC=(t,e,r)=>{const n={};return r.filter(i=>Array.isArray(i[t])?!0:(typeof i[t]<"u"&&$Pe(`Helmet: ${t} should be of type "Array". Instead found type "${typeof i[t]}"`),!1)).map(i=>i[t]).reverse().reduce((i,o)=>{const c={};o.filter(m=>{let g;const _=Object.keys(m);for(let N=0;N<_.length;N+=1){const C=_[N],P=C.toLowerCase();e.indexOf(P)!==-1&&!(g==="rel"&&m[g].toLowerCase()==="canonical")&&!(P==="rel"&&m[P].toLowerCase()==="stylesheet")&&(g=P),e.indexOf(C)!==-1&&(C==="innerHTML"||C==="cssText"||C==="itemprop")&&(g=C)}if(!g||!m[g])return!1;const j=m[g].toLowerCase();return n[g]||(n[g]={}),c[g]||(c[g]={}),n[g][j]?!1:(c[g][j]=!0,!0)}).reverse().forEach(m=>i.push(m));const a=Object.keys(c);for(let m=0;m{if(Array.isArray(t)&&t.length){for(let r=0;r({baseTag:BPe(["href"],t),bodyAttributes:VF("bodyAttributes",t),defer:n1(t,r1.DEFER),encode:n1(t,r1.ENCODE_SPECIAL_CHARACTERS),htmlAttributes:VF("htmlAttributes",t),linkTags:dC("link",["rel","href"],t),metaTags:dC("meta",["name","charset","http-equiv","property","itemprop"],t),noscriptTags:dC("noscript",["innerHTML"],t),onChangeClientState:zPe(t),scriptTags:dC("script",["src","innerHTML"],t),styleTags:dC("style",["cssText"],t),title:FPe(t),titleAttributes:VF("titleAttributes",t),prioritizeSeoTags:UPe(t,r1.PRIORITIZE_SEO_TAGS)}),Ble=t=>Array.isArray(t)?t.join(""):t,qPe=(t,e)=>{const r=Object.keys(t);for(let n=0;nArray.isArray(t)?t.reduce((r,n)=>(qPe(n,e)?r.priority.push(n):r.default.push(n),r),{priority:[],default:[]}):{default:t,priority:[]},AY=(t,e)=>({...t,[e]:void 0}),HPe=["noscript","script","style"],Q5=(t,e=!0)=>e===!1?String(t):String(t).replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"),$le=t=>Object.keys(t).reduce((e,r)=>{const n=typeof t[r]<"u"?`${r}="${t[r]}"`:`${r}`;return e?`${e} ${n}`:n},""),WPe=(t,e,r,n)=>{const i=$le(r),o=Ble(e);return i?`<${t} ${mf}="true" ${i}>${Q5(o,n)}`:`<${t} ${mf}="true">${Q5(o,n)}`},GPe=(t,e,r=!0)=>e.reduce((n,i)=>{const o=i,c=Object.keys(o).filter(g=>!(g==="innerHTML"||g==="cssText")).reduce((g,_)=>{const j=typeof o[_]>"u"?_:`${_}="${Q5(o[_],r)}"`;return g?`${g} ${j}`:j},""),a=o.innerHTML||o.cssText||"",m=HPe.indexOf(t)===-1;return`${n}<${t} ${mf}="true" ${c}${m?"/>":`>${a}`}`},""),Ule=(t,e={})=>Object.keys(t).reduce((r,n)=>{const i=y8[n];return r[i||n]=t[n],r},e),KPe=(t,e,r)=>{const n={key:e,[mf]:!0},i=Ule(r,n);return[Ve.createElement("title",i,e)]},CI=(t,e)=>e.map((r,n)=>{const i={key:n,[mf]:!0};return Object.keys(r).forEach(o=>{const a=y8[o]||o;if(a==="innerHTML"||a==="cssText"){const m=r.innerHTML||r.cssText;i.dangerouslySetInnerHTML={__html:m}}else i[a]=r[o]}),Ve.createElement(t,i)}),Zd=(t,e,r=!0)=>{switch(t){case"title":return{toComponent:()=>KPe(t,e.title,e.titleAttributes),toString:()=>WPe(t,e.title,e.titleAttributes,r)};case"bodyAttributes":case"htmlAttributes":return{toComponent:()=>Ule(e),toString:()=>$le(e)};default:return{toComponent:()=>CI(t,e),toString:()=>GPe(t,e,r)}}},ZPe=({metaTags:t,linkTags:e,scriptTags:r,encode:n})=>{const i=qF(t,UF.meta),o=qF(e,UF.link),c=qF(r,UF.script);return{priorityMethods:{toComponent:()=>[...CI("meta",i.priority),...CI("link",o.priority),...CI("script",c.priority)],toString:()=>`${Zd("meta",i.priority,n)} ${Zd("link",o.priority,n)} ${Zd("script",c.priority,n)}`},metaTags:i.default,linkTags:o.default,scriptTags:c.default}},YPe=t=>{const{baseTag:e,bodyAttributes:r,encode:n=!0,htmlAttributes:i,noscriptTags:o,styleTags:c,title:a="",titleAttributes:m,prioritizeSeoTags:g}=t;let{linkTags:_,metaTags:j,scriptTags:N}=t,C={toComponent:()=>{},toString:()=>""};return g&&({priorityMethods:C,linkTags:_,metaTags:j,scriptTags:N}=ZPe(t)),{priority:C,base:Zd("base",e,n),bodyAttributes:Zd("bodyAttributes",r,n),htmlAttributes:Zd("htmlAttributes",i,n),link:Zd("link",_,n),meta:Zd("meta",j,n),noscript:Zd("noscript",o,n),script:Zd("script",N,n),style:Zd("style",c,n),title:Zd("title",{title:a,titleAttributes:m},n)}},J5=YPe,yP=[],Vle=!!(typeof window<"u"&&window.document&&window.document.createElement),e$=class{constructor(t,e){um(this,"instances",[]);um(this,"canUseDOM",Vle);um(this,"context");um(this,"value",{setHelmet:t=>{this.context.helmet=t},helmetInstances:{get:()=>this.canUseDOM?yP:this.instances,add:t=>{(this.canUseDOM?yP:this.instances).push(t)},remove:t=>{const e=(this.canUseDOM?yP:this.instances).indexOf(t);(this.canUseDOM?yP:this.instances).splice(e,1)}}});this.context=t,this.canUseDOM=e||!1,e||(t.helmet=J5({baseTag:[],bodyAttributes:{},htmlAttributes:{},linkTags:[],metaTags:[],noscriptTags:[],scriptTags:[],styleTags:[],title:"",titleAttributes:{}}))}},XPe={},qle=Ve.createContext(XPe),f_,Hle=(f_=class extends D.Component{constructor(r){super(r);um(this,"helmetData");this.helmetData=new e$(this.props.context||{},f_.canUseDOM)}render(){return Ve.createElement(qle.Provider,{value:this.helmetData.value},this.props.children)}},um(f_,"canUseDOM",Vle),f_),ew=(t,e)=>{const r=document.head||document.querySelector("head"),n=r.querySelectorAll(`${t}[${mf}]`),i=[].slice.call(n),o=[];let c;return e&&e.length&&e.forEach(a=>{const m=document.createElement(t);for(const g in a)if(Object.prototype.hasOwnProperty.call(a,g))if(g==="innerHTML")m.innerHTML=a.innerHTML;else if(g==="cssText")m.styleSheet?m.styleSheet.cssText=a.cssText:m.appendChild(document.createTextNode(a.cssText));else{const _=g,j=typeof a[_]>"u"?"":a[_];m.setAttribute(g,j)}m.setAttribute(mf,"true"),i.some((g,_)=>(c=_,m.isEqualNode(g)))?i.splice(c,1):o.push(m)}),i.forEach(a=>{var m;return(m=a.parentNode)==null?void 0:m.removeChild(a)}),o.forEach(a=>r.appendChild(a)),{oldTags:i,newTags:o}},t$=(t,e)=>{const r=document.getElementsByTagName(t)[0];if(!r)return;const n=r.getAttribute(mf),i=n?n.split(","):[],o=[...i],c=Object.keys(e);for(const a of c){const m=e[a]||"";r.getAttribute(a)!==m&&r.setAttribute(a,m),i.indexOf(a)===-1&&i.push(a);const g=o.indexOf(a);g!==-1&&o.splice(g,1)}for(let a=o.length-1;a>=0;a-=1)r.removeAttribute(o[a]);i.length===o.length?r.removeAttribute(mf):r.getAttribute(mf)!==c.join(",")&&r.setAttribute(mf,c.join(","))},QPe=(t,e)=>{typeof t<"u"&&document.title!==t&&(document.title=Ble(t)),t$("title",e)},PY=(t,e)=>{const{baseTag:r,bodyAttributes:n,htmlAttributes:i,linkTags:o,metaTags:c,noscriptTags:a,onChangeClientState:m,scriptTags:g,styleTags:_,title:j,titleAttributes:N}=t;t$("body",n),t$("html",i),QPe(j,N);const C={baseTag:ew("base",r),linkTags:ew("link",o),metaTags:ew("meta",c),noscriptTags:ew("noscript",a),scriptTags:ew("script",g),styleTags:ew("style",_)},P={},A={};Object.keys(C).forEach(I=>{const{newTags:O,oldTags:R}=C[I];O.length&&(P[I]=O),R.length&&(A[I]=C[I].oldTags)}),e&&e(),m(t,P,A)},hC=null,JPe=t=>{hC&&cancelAnimationFrame(hC),t.defer?hC=requestAnimationFrame(()=>{PY(t,()=>{hC=null})}):(PY(t),hC=null)},eIe=JPe,IY=class extends D.Component{constructor(){super(...arguments);um(this,"rendered",!1)}shouldComponentUpdate(e){return!DPe(e,this.props)}componentDidUpdate(){this.emitChange()}componentWillUnmount(){const{helmetInstances:e}=this.props.context;e.remove(this),this.emitChange()}emitChange(){const{helmetInstances:e,setHelmet:r}=this.props.context;let n=null;const i=VPe(e.get().map(o=>{const c={...o.props};return delete c.context,c}));Hle.canUseDOM?eIe(i):J5&&(n=J5(i)),r(n)}init(){if(this.rendered)return;this.rendered=!0;const{helmetInstances:e}=this.props.context;e.add(this),this.emitChange()}render(){return this.init(),null}},TB,tIe=(TB=class extends D.Component{shouldComponentUpdate(t){return!IPe(AY(this.props,"helmetData"),AY(t,"helmetData"))}mapNestedChildrenToProps(t,e){if(!e)return null;switch(t.type){case"script":case"noscript":return{innerHTML:e};case"style":return{cssText:e};default:throw new Error(`<${t.type} /> elements are self-closing and can not contain children. Refer to our API for more information.`)}}flattenArrayTypeChildren(t,e,r,n){return{...e,[t.type]:[...e[t.type]||[],{...r,...this.mapNestedChildrenToProps(t,n)}]}}mapObjectTypeChildren(t,e,r,n){switch(t.type){case"title":return{...e,[t.type]:n,titleAttributes:{...r}};case"body":return{...e,bodyAttributes:{...r}};case"html":return{...e,htmlAttributes:{...r}};default:return{...e,[t.type]:{...r}}}}mapArrayTypeChildrenToProps(t,e){let r={...e};return Object.keys(t).forEach(n=>{r={...r,[n]:t[n]}}),r}warnOnInvalidChildren(t,e){return TY(EY.some(r=>t.type===r),typeof t.type=="function"?"You may be attempting to nest components within each other, which is not allowed. Refer to our API for more information.":`Only elements types ${EY.join(", ")} are allowed. Helmet does not support rendering <${t.type}> elements. Refer to our API for more information.`),TY(!e||typeof e=="string"||Array.isArray(e)&&!e.some(r=>typeof r!="string"),`Helmet expects a string as a child of <${t.type}>. Did you forget to wrap your children in braces? ( <${t.type}>{\`\`} ) Refer to our API for more information.`),!0}mapChildrenToProps(t,e){let r={};return Ve.Children.forEach(t,n=>{if(!n||!n.props)return;const{children:i,...o}=n.props,c=Object.keys(o).reduce((m,g)=>(m[LPe[g]||g]=o[g],m),{});let{type:a}=n;switch(typeof a=="symbol"?a=a.toString():this.warnOnInvalidChildren(n,i),a){case"Symbol(react.fragment)":e=this.mapChildrenToProps(i,e);break;case"link":case"meta":case"noscript":case"script":case"style":r=this.flattenArrayTypeChildren(n,r,c,i);break;default:e=this.mapObjectTypeChildren(n,e,c,i);break}}),this.mapArrayTypeChildrenToProps(r,e)}render(){const{children:t,...e}=this.props;let r={...e},{helmetData:n}=e;if(t&&(r=this.mapChildrenToProps(t,r)),n&&!(n instanceof e$)){const i=n;n=new e$(i.context,!0),delete r.helmetData}return n?Ve.createElement(IY,{...r,context:n.value}):Ve.createElement(qle.Consumer,null,i=>Ve.createElement(IY,{...r,context:i}))}},um(TB,"defaultProps",{defer:!0,encodeSpecialCharacters:!0,prioritizeSeoTags:!1}),TB),r$=function(t,e){return r$=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(r[i]=n[i])},r$(t,e)};function Wle(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");r$(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var th=function(){return th=Object.assign||function(e){for(var r,n=1,i=arguments.length;n=0;a--)(c=t[a])&&(o=(i<3?c(o):i>3?c(e,r,o):c(e,r))||o);return i>3&&o&&Object.defineProperty(e,r,o),o}function Kle(t,e){return function(r,n){e(r,n,t)}}function Zle(t,e,r,n,i,o){function c(O){if(O!==void 0&&typeof O!="function")throw new TypeError("Function expected");return O}for(var a=n.kind,m=a==="getter"?"get":a==="setter"?"set":"value",g=!e&&t?n.static?t:t.prototype:null,_=e||(g?Object.getOwnPropertyDescriptor(g,n.name):{}),j,N=!1,C=r.length-1;C>=0;C--){var P={};for(var A in n)P[A]=A==="access"?{}:n[A];for(var A in n.access)P.access[A]=n.access[A];P.addInitializer=function(O){if(N)throw new TypeError("Cannot add initializers after decoration has completed");o.push(c(O||null))};var I=(0,r[C])(a==="accessor"?{get:_.get,set:_.set}:_[m],P);if(a==="accessor"){if(I===void 0)continue;if(I===null||typeof I!="object")throw new TypeError("Object expected");(j=c(I.get))&&(_.get=j),(j=c(I.set))&&(_.set=j),(j=c(I.init))&&i.unshift(j)}else(j=c(I))&&(a==="field"?i.unshift(j):_[m]=j)}g&&Object.defineProperty(g,n.name,_),N=!0}function Yle(t,e,r){for(var n=arguments.length>2,i=0;i0&&o[o.length-1])&&(g[0]===6||g[0]===2)){r=0;continue}if(g[0]===3&&(!o||g[1]>o[0]&&g[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function x8(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,o=[],c;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(a){c={error:a}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(c)throw c.error}}return o}function rce(){for(var t=[],e=0;e1||m(C,A)})},P&&(i[C]=P(i[C])))}function m(C,P){try{g(n[C](P))}catch(A){N(o[0][3],A)}}function g(C){C.value instanceof F1?Promise.resolve(C.value.v).then(_,j):N(o[0][2],C)}function _(C){m("next",C)}function j(C){m("throw",C)}function N(C,P){C(P),o.shift(),o.length&&m(o[0][0],o[0][1])}}function ice(t){var e,r;return e={},n("next"),n("throw",function(i){throw i}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(i,o){e[i]=t[i]?function(c){return(r=!r)?{value:F1(t[i](c)),done:!1}:o?o(c):c}:o}}function ace(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof NM=="function"?NM(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(o){r[o]=t[o]&&function(c){return new Promise(function(a,m){c=t[o](c),i(a,m,c.done,c.value)})}}function i(o,c,a,m){Promise.resolve(m).then(function(g){o({value:g,done:a})},c)}}function oce(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}var rIe=Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e},n$=function(t){return n$=Object.getOwnPropertyNames||function(e){var r=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(r[r.length]=n);return r},n$(t)};function lce(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r=n$(t),n=0;n0){document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),a=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));i=Promise.allSettled(r.map(m=>{if(m=oIe(m),m in MY)return;MY[m]=!0;const g=m.endsWith(".css"),_=g?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${m}"]${_}`))return;const j=document.createElement("link");if(j.rel=g?"stylesheet":aIe,g||(j.as="script"),j.crossOrigin="",j.href=m,a&&j.setAttribute("nonce",a),document.head.appendChild(j),g)return new Promise((N,C)=>{j.addEventListener("load",N),j.addEventListener("error",()=>C(new Error(`Unable to preload CSS for ${m}`)))})}))}function o(c){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=c,window.dispatchEvent(a),!a.defaultPrevented)throw c}return i.then(c=>{for(const a of c||[])a.status==="rejected"&&o(a.reason);return e().catch(o)})},lIe=t=>{let e;return t?e=t:typeof fetch>"u"?e=(...r)=>Lj(async()=>{const{default:n}=await Promise.resolve().then(()=>s0);return{default:n}},void 0).then(({default:n})=>n(...r)):e=fetch,(...r)=>e(...r)};class _8 extends Error{constructor(e,r="FunctionsError",n){super(e),this.name=r,this.context=n}}class OY extends _8{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class RY extends _8{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class DY extends _8{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var s$;(function(t){t.Any="any",t.ApNortheast1="ap-northeast-1",t.ApNortheast2="ap-northeast-2",t.ApSouth1="ap-south-1",t.ApSoutheast1="ap-southeast-1",t.ApSoutheast2="ap-southeast-2",t.CaCentral1="ca-central-1",t.EuCentral1="eu-central-1",t.EuWest1="eu-west-1",t.EuWest2="eu-west-2",t.EuWest3="eu-west-3",t.SaEast1="sa-east-1",t.UsEast1="us-east-1",t.UsWest1="us-west-1",t.UsWest2="us-west-2"})(s$||(s$={}));class cIe{constructor(e,{headers:r={},customFetch:n,region:i=s$.Any}={}){this.url=e,this.headers=r,this.region=i,this.fetch=lIe(n)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return ss(this,arguments,void 0,function*(r,n={}){var i;try{const{headers:o,method:c,body:a,signal:m}=n;let g={},{region:_}=n;_||(_=this.region);const j=new URL(`${this.url}/${r}`);_&&_!=="any"&&(g["x-region"]=_,j.searchParams.set("forceFunctionRegion",_));let N;a&&(o&&!Object.prototype.hasOwnProperty.call(o,"Content-Type")||!o)?typeof Blob<"u"&&a instanceof Blob||a instanceof ArrayBuffer?(g["Content-Type"]="application/octet-stream",N=a):typeof a=="string"?(g["Content-Type"]="text/plain",N=a):typeof FormData<"u"&&a instanceof FormData?N=a:(g["Content-Type"]="application/json",N=JSON.stringify(a)):N=a;const C=yield this.fetch(j.toString(),{method:c||"POST",headers:Object.assign(Object.assign(Object.assign({},g),this.headers),o),body:N,signal:m}).catch(O=>{throw O.name==="AbortError"?O:new OY(O)}),P=C.headers.get("x-relay-error");if(P&&P==="true")throw new RY(C);if(!C.ok)throw new DY(C);let A=((i=C.headers.get("Content-Type"))!==null&&i!==void 0?i:"text/plain").split(";")[0].trim(),I;return A==="application/json"?I=yield C.json():A==="application/octet-stream"||A==="application/pdf"?I=yield C.blob():A==="text/event-stream"?I=C:A==="multipart/form-data"?I=yield C.formData():I=yield C.text(),{data:I,error:null,response:C}}catch(o){return o instanceof Error&&o.name==="AbortError"?{data:null,error:new OY(o)}:{data:null,error:o,response:o instanceof DY||o instanceof RY?o.context:void 0}}})}}var tu={};const Fj=hse(iIe);var xP={},vP={},_P={},bP={},wP={},uIe=function(){if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;throw new Error("unable to locate global object")},z1=uIe();const dIe=z1.fetch,gce=z1.fetch.bind(z1),yce=z1.Headers,hIe=z1.Request,fIe=z1.Response,s0=Object.freeze(Object.defineProperty({__proto__:null,Headers:yce,Request:hIe,Response:fIe,default:gce,fetch:dIe},Symbol.toStringTag,{value:"Module"})),pIe=hse(s0);var jP={},LY;function xce(){if(LY)return jP;LY=1,Object.defineProperty(jP,"__esModule",{value:!0});class t extends Error{constructor(r){super(r.message),this.name="PostgrestError",this.details=r.details,this.hint=r.hint,this.code=r.code}}return jP.default=t,jP}var FY;function vce(){if(FY)return wP;FY=1,Object.defineProperty(wP,"__esModule",{value:!0});const t=Fj,e=t.__importDefault(pIe),r=t.__importDefault(xce());class n{constructor(o){var c,a;this.shouldThrowOnError=!1,this.method=o.method,this.url=o.url,this.headers=new Headers(o.headers),this.schema=o.schema,this.body=o.body,this.shouldThrowOnError=(c=o.shouldThrowOnError)!==null&&c!==void 0?c:!1,this.signal=o.signal,this.isMaybeSingle=(a=o.isMaybeSingle)!==null&&a!==void 0?a:!1,o.fetch?this.fetch=o.fetch:typeof fetch>"u"?this.fetch=e.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(o,c){return this.headers=new Headers(this.headers),this.headers.set(o,c),this}then(o,c){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json");const a=this.fetch;let m=a(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async g=>{var _,j,N,C;let P=null,A=null,I=null,O=g.status,R=g.statusText;if(g.ok){if(this.method!=="HEAD"){const K=await g.text();K===""||(this.headers.get("Accept")==="text/csv"||this.headers.get("Accept")&&(!((_=this.headers.get("Accept"))===null||_===void 0)&&_.includes("application/vnd.pgrst.plan+text"))?A=K:A=JSON.parse(K))}const W=(j=this.headers.get("Prefer"))===null||j===void 0?void 0:j.match(/count=(exact|planned|estimated)/),V=(N=g.headers.get("content-range"))===null||N===void 0?void 0:N.split("/");W&&V&&V.length>1&&(I=parseInt(V[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(A)&&(A.length>1?(P={code:"PGRST116",details:`Results contain ${A.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},A=null,I=null,O=406,R="Not Acceptable"):A.length===1?A=A[0]:A=null)}else{const W=await g.text();try{P=JSON.parse(W),Array.isArray(P)&&g.status===404&&(A=[],P=null,O=200,R="OK")}catch{g.status===404&&W===""?(O=204,R="No Content"):P={message:W}}if(P&&this.isMaybeSingle&&(!((C=P==null?void 0:P.details)===null||C===void 0)&&C.includes("0 rows"))&&(P=null,O=200,R="OK"),P&&this.shouldThrowOnError)throw new r.default(P)}return{error:P,data:A,count:I,status:O,statusText:R}});return this.shouldThrowOnError||(m=m.catch(g=>{var _,j,N;return{error:{message:`${(_=g==null?void 0:g.name)!==null&&_!==void 0?_:"FetchError"}: ${g==null?void 0:g.message}`,details:`${(j=g==null?void 0:g.stack)!==null&&j!==void 0?j:""}`,hint:"",code:`${(N=g==null?void 0:g.code)!==null&&N!==void 0?N:""}`},data:null,count:null,status:0,statusText:""}})),m.then(o,c)}returns(){return this}overrideTypes(){return this}}return wP.default=n,wP}var zY;function _ce(){if(zY)return bP;zY=1,Object.defineProperty(bP,"__esModule",{value:!0});const e=Fj.__importDefault(vce());class r extends e.default{select(i){let o=!1;const c=(i??"*").split("").map(a=>/\s/.test(a)&&!o?"":(a==='"'&&(o=!o),a)).join("");return this.url.searchParams.set("select",c),this.headers.append("Prefer","return=representation"),this}order(i,{ascending:o=!0,nullsFirst:c,foreignTable:a,referencedTable:m=a}={}){const g=m?`${m}.order`:"order",_=this.url.searchParams.get(g);return this.url.searchParams.set(g,`${_?`${_},`:""}${i}.${o?"asc":"desc"}${c===void 0?"":c?".nullsfirst":".nullslast"}`),this}limit(i,{foreignTable:o,referencedTable:c=o}={}){const a=typeof c>"u"?"limit":`${c}.limit`;return this.url.searchParams.set(a,`${i}`),this}range(i,o,{foreignTable:c,referencedTable:a=c}={}){const m=typeof a>"u"?"offset":`${a}.offset`,g=typeof a>"u"?"limit":`${a}.limit`;return this.url.searchParams.set(m,`${i}`),this.url.searchParams.set(g,`${o-i+1}`),this}abortSignal(i){return this.signal=i,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.method==="GET"?this.headers.set("Accept","application/json"):this.headers.set("Accept","application/vnd.pgrst.object+json"),this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:i=!1,verbose:o=!1,settings:c=!1,buffers:a=!1,wal:m=!1,format:g="text"}={}){var _;const j=[i?"analyze":null,o?"verbose":null,c?"settings":null,a?"buffers":null,m?"wal":null].filter(Boolean).join("|"),N=(_=this.headers.get("Accept"))!==null&&_!==void 0?_:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${g}; for="${N}"; options=${j};`),g==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(i){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${i}`),this}}return bP.default=r,bP}var BY;function b8(){if(BY)return _P;BY=1,Object.defineProperty(_P,"__esModule",{value:!0});const e=Fj.__importDefault(_ce()),r=new RegExp("[,()]");class n extends e.default{eq(o,c){return this.url.searchParams.append(o,`eq.${c}`),this}neq(o,c){return this.url.searchParams.append(o,`neq.${c}`),this}gt(o,c){return this.url.searchParams.append(o,`gt.${c}`),this}gte(o,c){return this.url.searchParams.append(o,`gte.${c}`),this}lt(o,c){return this.url.searchParams.append(o,`lt.${c}`),this}lte(o,c){return this.url.searchParams.append(o,`lte.${c}`),this}like(o,c){return this.url.searchParams.append(o,`like.${c}`),this}likeAllOf(o,c){return this.url.searchParams.append(o,`like(all).{${c.join(",")}}`),this}likeAnyOf(o,c){return this.url.searchParams.append(o,`like(any).{${c.join(",")}}`),this}ilike(o,c){return this.url.searchParams.append(o,`ilike.${c}`),this}ilikeAllOf(o,c){return this.url.searchParams.append(o,`ilike(all).{${c.join(",")}}`),this}ilikeAnyOf(o,c){return this.url.searchParams.append(o,`ilike(any).{${c.join(",")}}`),this}is(o,c){return this.url.searchParams.append(o,`is.${c}`),this}in(o,c){const a=Array.from(new Set(c)).map(m=>typeof m=="string"&&r.test(m)?`"${m}"`:`${m}`).join(",");return this.url.searchParams.append(o,`in.(${a})`),this}contains(o,c){return typeof c=="string"?this.url.searchParams.append(o,`cs.${c}`):Array.isArray(c)?this.url.searchParams.append(o,`cs.{${c.join(",")}}`):this.url.searchParams.append(o,`cs.${JSON.stringify(c)}`),this}containedBy(o,c){return typeof c=="string"?this.url.searchParams.append(o,`cd.${c}`):Array.isArray(c)?this.url.searchParams.append(o,`cd.{${c.join(",")}}`):this.url.searchParams.append(o,`cd.${JSON.stringify(c)}`),this}rangeGt(o,c){return this.url.searchParams.append(o,`sr.${c}`),this}rangeGte(o,c){return this.url.searchParams.append(o,`nxl.${c}`),this}rangeLt(o,c){return this.url.searchParams.append(o,`sl.${c}`),this}rangeLte(o,c){return this.url.searchParams.append(o,`nxr.${c}`),this}rangeAdjacent(o,c){return this.url.searchParams.append(o,`adj.${c}`),this}overlaps(o,c){return typeof c=="string"?this.url.searchParams.append(o,`ov.${c}`):this.url.searchParams.append(o,`ov.{${c.join(",")}}`),this}textSearch(o,c,{config:a,type:m}={}){let g="";m==="plain"?g="pl":m==="phrase"?g="ph":m==="websearch"&&(g="w");const _=a===void 0?"":`(${a})`;return this.url.searchParams.append(o,`${g}fts${_}.${c}`),this}match(o){return Object.entries(o).forEach(([c,a])=>{this.url.searchParams.append(c,`eq.${a}`)}),this}not(o,c,a){return this.url.searchParams.append(o,`not.${c}.${a}`),this}or(o,{foreignTable:c,referencedTable:a=c}={}){const m=a?`${a}.or`:"or";return this.url.searchParams.append(m,`(${o})`),this}filter(o,c,a){return this.url.searchParams.append(o,`${c}.${a}`),this}}return _P.default=n,_P}var $Y;function bce(){if($Y)return vP;$Y=1,Object.defineProperty(vP,"__esModule",{value:!0});const e=Fj.__importDefault(b8());class r{constructor(i,{headers:o={},schema:c,fetch:a}){this.url=i,this.headers=new Headers(o),this.schema=c,this.fetch=a}select(i,o){const{head:c=!1,count:a}=o??{},m=c?"HEAD":"GET";let g=!1;const _=(i??"*").split("").map(j=>/\s/.test(j)&&!g?"":(j==='"'&&(g=!g),j)).join("");return this.url.searchParams.set("select",_),a&&this.headers.append("Prefer",`count=${a}`),new e.default({method:m,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch})}insert(i,{count:o,defaultToNull:c=!0}={}){var a;const m="POST";if(o&&this.headers.append("Prefer",`count=${o}`),c||this.headers.append("Prefer","missing=default"),Array.isArray(i)){const g=i.reduce((_,j)=>_.concat(Object.keys(j)),[]);if(g.length>0){const _=[...new Set(g)].map(j=>`"${j}"`);this.url.searchParams.set("columns",_.join(","))}}return new e.default({method:m,url:this.url,headers:this.headers,schema:this.schema,body:i,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch})}upsert(i,{onConflict:o,ignoreDuplicates:c=!1,count:a,defaultToNull:m=!0}={}){var g;const _="POST";if(this.headers.append("Prefer",`resolution=${c?"ignore":"merge"}-duplicates`),o!==void 0&&this.url.searchParams.set("on_conflict",o),a&&this.headers.append("Prefer",`count=${a}`),m||this.headers.append("Prefer","missing=default"),Array.isArray(i)){const j=i.reduce((N,C)=>N.concat(Object.keys(C)),[]);if(j.length>0){const N=[...new Set(j)].map(C=>`"${C}"`);this.url.searchParams.set("columns",N.join(","))}}return new e.default({method:_,url:this.url,headers:this.headers,schema:this.schema,body:i,fetch:(g=this.fetch)!==null&&g!==void 0?g:fetch})}update(i,{count:o}={}){var c;const a="PATCH";return o&&this.headers.append("Prefer",`count=${o}`),new e.default({method:a,url:this.url,headers:this.headers,schema:this.schema,body:i,fetch:(c=this.fetch)!==null&&c!==void 0?c:fetch})}delete({count:i}={}){var o;const c="DELETE";return i&&this.headers.append("Prefer",`count=${i}`),new e.default({method:c,url:this.url,headers:this.headers,schema:this.schema,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch})}}return vP.default=r,vP}var UY;function mIe(){if(UY)return xP;UY=1,Object.defineProperty(xP,"__esModule",{value:!0});const t=Fj,e=t.__importDefault(bce()),r=t.__importDefault(b8());class n{constructor(o,{headers:c={},schema:a,fetch:m}={}){this.url=o,this.headers=new Headers(c),this.schemaName=a,this.fetch=m}from(o){const c=new URL(`${this.url}/${o}`);return new e.default(c,{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch})}schema(o){return new n(this.url,{headers:this.headers,schema:o,fetch:this.fetch})}rpc(o,c={},{head:a=!1,get:m=!1,count:g}={}){var _;let j;const N=new URL(`${this.url}/rpc/${o}`);let C;a||m?(j=a?"HEAD":"GET",Object.entries(c).filter(([A,I])=>I!==void 0).map(([A,I])=>[A,Array.isArray(I)?`{${I.join(",")}}`:`${I}`]).forEach(([A,I])=>{N.searchParams.append(A,I)})):(j="POST",C=c);const P=new Headers(this.headers);return g&&P.set("Prefer",`count=${g}`),new r.default({method:j,url:N,headers:P,schema:this.schemaName,body:C,fetch:(_=this.fetch)!==null&&_!==void 0?_:fetch})}}return xP.default=n,xP}Object.defineProperty(tu,"__esModule",{value:!0});var wce=tu.PostgrestError=Ice=tu.PostgrestBuilder=Ace=tu.PostgrestTransformBuilder=Tce=tu.PostgrestFilterBuilder=Cce=tu.PostgrestQueryBuilder=Sce=tu.PostgrestClient=void 0;const zj=Fj,jce=zj.__importDefault(mIe());var Sce=tu.PostgrestClient=jce.default;const Nce=zj.__importDefault(bce());var Cce=tu.PostgrestQueryBuilder=Nce.default;const kce=zj.__importDefault(b8());var Tce=tu.PostgrestFilterBuilder=kce.default;const Ece=zj.__importDefault(_ce());var Ace=tu.PostgrestTransformBuilder=Ece.default;const Pce=zj.__importDefault(vce());var Ice=tu.PostgrestBuilder=Pce.default;const Mce=zj.__importDefault(xce());wce=tu.PostgrestError=Mce.default;var Oce=tu.default={PostgrestClient:jce.default,PostgrestQueryBuilder:Nce.default,PostgrestFilterBuilder:kce.default,PostgrestTransformBuilder:Ece.default,PostgrestBuilder:Pce.default,PostgrestError:Mce.default};const gIe=dse({__proto__:null,get PostgrestBuilder(){return Ice},get PostgrestClient(){return Sce},get PostgrestError(){return wce},get PostgrestFilterBuilder(){return Tce},get PostgrestQueryBuilder(){return Cce},get PostgrestTransformBuilder(){return Ace},default:Oce},[tu]),{PostgrestClient:yIe,PostgrestQueryBuilder:rwt,PostgrestFilterBuilder:nwt,PostgrestTransformBuilder:swt,PostgrestBuilder:iwt,PostgrestError:awt}=Oce||gIe;class xIe{static detectEnvironment(){var e;if(typeof WebSocket<"u")return{type:"native",constructor:WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocket<"u")return{type:"native",constructor:globalThis.WebSocket};if(typeof global<"u"&&typeof global.WebSocket<"u")return{type:"native",constructor:global.WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocketPair<"u"&&typeof globalThis.WebSocket>"u")return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if(typeof globalThis<"u"&&globalThis.EdgeRuntime||typeof navigator<"u"&&(!((e=navigator.userAgent)===null||e===void 0)&&e.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};if(typeof process<"u"){const r=process.versions;if(r&&r.node){const n=r.node,i=parseInt(n.replace(/^v/,"").split(".")[0]);return i>=22?typeof globalThis.WebSocket<"u"?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${i} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${i} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option: import ws from "ws" new RealtimeClient(url, { transport: ws })`}}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){const e=this.detectEnvironment();if(e.constructor)return e.constructor;let r=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(r+=` Suggested solution: ${e.workaround}`),new Error(r)}static createWebSocket(e,r){const n=this.getWebSocketConstructor();return new n(e,r)}static isWebSocketSupported(){try{const e=this.detectEnvironment();return e.type==="native"||e.type==="ws"}catch{return!1}}}const vIe="2.78.0",_Ie=`realtime-js/${vIe}`,bIe="1.0.0",i$=1e4,wIe=1e3,jIe=100;var s2;(function(t){t[t.connecting=0]="connecting",t[t.open=1]="open",t[t.closing=2]="closing",t[t.closed=3]="closed"})(s2||(s2={}));var wl;(function(t){t.closed="closed",t.errored="errored",t.joined="joined",t.joining="joining",t.leaving="leaving"})(wl||(wl={}));var of;(function(t){t.close="phx_close",t.error="phx_error",t.join="phx_join",t.reply="phx_reply",t.leave="phx_leave",t.access_token="access_token"})(of||(of={}));var a$;(function(t){t.websocket="websocket"})(a$||(a$={}));var zv;(function(t){t.Connecting="connecting",t.Open="open",t.Closing="closing",t.Closed="closed"})(zv||(zv={}));class SIe{constructor(){this.HEADER_LENGTH=1}decode(e,r){return e.constructor===ArrayBuffer?r(this._binaryDecode(e)):r(typeof e=="string"?JSON.parse(e):{})}_binaryDecode(e){const r=new DataView(e),n=new TextDecoder;return this._decodeBroadcast(e,r,n)}_decodeBroadcast(e,r,n){const i=r.getUint8(1),o=r.getUint8(2);let c=this.HEADER_LENGTH+2;const a=n.decode(e.slice(c,c+i));c=c+i;const m=n.decode(e.slice(c,c+o));c=c+o;const g=JSON.parse(n.decode(e.slice(c,e.byteLength)));return{ref:null,topic:a,event:m,payload:g}}}class Rce{constructor(e,r){this.callback=e,this.timerCalc=r,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=r}reset(){this.tries=0,clearTimeout(this.timer),this.timer=void 0}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}}var Va;(function(t){t.abstime="abstime",t.bool="bool",t.date="date",t.daterange="daterange",t.float4="float4",t.float8="float8",t.int2="int2",t.int4="int4",t.int4range="int4range",t.int8="int8",t.int8range="int8range",t.json="json",t.jsonb="jsonb",t.money="money",t.numeric="numeric",t.oid="oid",t.reltime="reltime",t.text="text",t.time="time",t.timestamp="timestamp",t.timestamptz="timestamptz",t.timetz="timetz",t.tsrange="tsrange",t.tstzrange="tstzrange"})(Va||(Va={}));const VY=(t,e,r={})=>{var n;const i=(n=r.skipTypes)!==null&&n!==void 0?n:[];return e?Object.keys(e).reduce((o,c)=>(o[c]=NIe(c,t,e,i),o),{}):{}},NIe=(t,e,r,n)=>{const i=e.find(a=>a.name===t),o=i==null?void 0:i.type,c=r[t];return o&&!n.includes(o)?Dce(o,c):o$(c)},Dce=(t,e)=>{if(t.charAt(0)==="_"){const r=t.slice(1,t.length);return EIe(e,r)}switch(t){case Va.bool:return CIe(e);case Va.float4:case Va.float8:case Va.int2:case Va.int4:case Va.int8:case Va.numeric:case Va.oid:return kIe(e);case Va.json:case Va.jsonb:return TIe(e);case Va.timestamp:return AIe(e);case Va.abstime:case Va.date:case Va.daterange:case Va.int4range:case Va.int8range:case Va.money:case Va.reltime:case Va.text:case Va.time:case Va.timestamptz:case Va.timetz:case Va.tsrange:case Va.tstzrange:return o$(e);default:return o$(e)}},o$=t=>t,CIe=t=>{switch(t){case"t":return!0;case"f":return!1;default:return t}},kIe=t=>{if(typeof t=="string"){const e=parseFloat(t);if(!Number.isNaN(e))return e}return t},TIe=t=>{if(typeof t=="string")try{return JSON.parse(t)}catch(e){return console.log(`JSON parse error: ${e}`),t}return t},EIe=(t,e)=>{if(typeof t!="string")return t;const r=t.length-1,n=t[r];if(t[0]==="{"&&n==="}"){let o;const c=t.slice(1,r);try{o=JSON.parse("["+c+"]")}catch{o=c?c.split(","):[]}return o.map(a=>Dce(e,a))}return t},AIe=t=>typeof t=="string"?t.replace(" ","T"):t,Lce=t=>{const e=new URL(t);return e.protocol=e.protocol.replace(/^ws/i,"http"),e.pathname=e.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),e.pathname===""||e.pathname==="/"?e.pathname="/api/broadcast":e.pathname=e.pathname+"/api/broadcast",e.href};class HF{constructor(e,r,n={},i=i$){this.channel=e,this.event=r,this.payload=n,this.timeout=i,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,r){var n;return this._hasReceived(e)&&r((n=this.receivedResp)===null||n===void 0?void 0:n.response),this.recHooks.push({status:e,callback:r}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);const e=r=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=r,this._matchReceive(r)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,r){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:r})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:r}){this.recHooks.filter(n=>n.status===e).forEach(n=>n.callback(r))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}}var qY;(function(t){t.SYNC="sync",t.JOIN="join",t.LEAVE="leave"})(qY||(qY={}));class i2{constructor(e,r){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.enabled=!1,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const n=(r==null?void 0:r.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(n.state,{},i=>{const{onJoin:o,onLeave:c,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=i2.syncState(this.state,i,o,c),this.pendingDiffs.forEach(m=>{this.state=i2.syncDiff(this.state,m,o,c)}),this.pendingDiffs=[],a()}),this.channel._on(n.diff,{},i=>{const{onJoin:o,onLeave:c,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(i):(this.state=i2.syncDiff(this.state,i,o,c),a())}),this.onJoin((i,o,c)=>{this.channel._trigger("presence",{event:"join",key:i,currentPresences:o,newPresences:c})}),this.onLeave((i,o,c)=>{this.channel._trigger("presence",{event:"leave",key:i,currentPresences:o,leftPresences:c})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,r,n,i){const o=this.cloneDeep(e),c=this.transformState(r),a={},m={};return this.map(o,(g,_)=>{c[g]||(m[g]=_)}),this.map(c,(g,_)=>{const j=o[g];if(j){const N=_.map(I=>I.presence_ref),C=j.map(I=>I.presence_ref),P=_.filter(I=>C.indexOf(I.presence_ref)<0),A=j.filter(I=>N.indexOf(I.presence_ref)<0);P.length>0&&(a[g]=P),A.length>0&&(m[g]=A)}else a[g]=_}),this.syncDiff(o,{joins:a,leaves:m},n,i)}static syncDiff(e,r,n,i){const{joins:o,leaves:c}={joins:this.transformState(r.joins),leaves:this.transformState(r.leaves)};return n||(n=()=>{}),i||(i=()=>{}),this.map(o,(a,m)=>{var g;const _=(g=e[a])!==null&&g!==void 0?g:[];if(e[a]=this.cloneDeep(m),_.length>0){const j=e[a].map(C=>C.presence_ref),N=_.filter(C=>j.indexOf(C.presence_ref)<0);e[a].unshift(...N)}n(a,_,m)}),this.map(c,(a,m)=>{let g=e[a];if(!g)return;const _=m.map(j=>j.presence_ref);g=g.filter(j=>_.indexOf(j.presence_ref)<0),e[a]=g,i(a,g,m),g.length===0&&delete e[a]}),e}static map(e,r){return Object.getOwnPropertyNames(e).map(n=>r(n,e[n]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((r,n)=>{const i=e[n];return"metas"in i?r[n]=i.metas.map(o=>(o.presence_ref=o.phx_ref,delete o.phx_ref,delete o.phx_ref_prev,o)):r[n]=i,r},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}var HY;(function(t){t.ALL="*",t.INSERT="INSERT",t.UPDATE="UPDATE",t.DELETE="DELETE"})(HY||(HY={}));var a2;(function(t){t.BROADCAST="broadcast",t.PRESENCE="presence",t.POSTGRES_CHANGES="postgres_changes",t.SYSTEM="system"})(a2||(a2={}));var bm;(function(t){t.SUBSCRIBED="SUBSCRIBED",t.TIMED_OUT="TIMED_OUT",t.CLOSED="CLOSED",t.CHANNEL_ERROR="CHANNEL_ERROR"})(bm||(bm={}));class w8{constructor(e,r={config:{}},n){var i,o;if(this.topic=e,this.params=r,this.socket=n,this.bindings={},this.state=wl.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},r.config),this.timeout=this.socket.timeout,this.joinPush=new HF(this,of.join,this.params,this.timeout),this.rejoinTimer=new Rce(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=wl.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(c=>c.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=wl.closed,this.socket._remove(this)}),this._onError(c=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,c),this.state=wl.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=wl.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("error",c=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,c),this.state=wl.errored,this.rejoinTimer.scheduleTimeout())}),this._on(of.reply,{},(c,a)=>{this._trigger(this._replyEventName(a),c)}),this.presence=new i2(this),this.broadcastEndpointURL=Lce(this.socket.endPoint),this.private=this.params.config.private||!1,!this.private&&(!((o=(i=this.params.config)===null||i===void 0?void 0:i.broadcast)===null||o===void 0)&&o.replay))throw`tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(e,r=this.timeout){var n,i,o;if(this.socket.isConnected()||this.socket.connect(),this.state==wl.closed){const{config:{broadcast:c,presence:a,private:m}}=this.params,g=(i=(n=this.bindings.postgres_changes)===null||n===void 0?void 0:n.map(C=>C.filter))!==null&&i!==void 0?i:[],_=!!this.bindings[a2.PRESENCE]&&this.bindings[a2.PRESENCE].length>0||((o=this.params.config.presence)===null||o===void 0?void 0:o.enabled)===!0,j={},N={broadcast:c,presence:Object.assign(Object.assign({},a),{enabled:_}),postgres_changes:g,private:m};this.socket.accessTokenValue&&(j.access_token=this.socket.accessTokenValue),this._onError(C=>e==null?void 0:e(bm.CHANNEL_ERROR,C)),this._onClose(()=>e==null?void 0:e(bm.CLOSED)),this.updateJoinPayload(Object.assign({config:N},j)),this.joinedOnce=!0,this._rejoin(r),this.joinPush.receive("ok",async({postgres_changes:C})=>{var P;if(this.socket.setAuth(),C===void 0){e==null||e(bm.SUBSCRIBED);return}else{const A=this.bindings.postgres_changes,I=(P=A==null?void 0:A.length)!==null&&P!==void 0?P:0,O=[];for(let R=0;R{this.state=wl.errored,e==null||e(bm.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(C).join(", ")||"error")))}).receive("timeout",()=>{e==null||e(bm.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track(e,r={}){return await this.send({type:"presence",event:"track",payload:e},r.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,r,n){return this.state===wl.joined&&e===a2.PRESENCE&&(this.socket.log("channel",`resubscribe to ${this.topic} due to change in presence callbacks on joined channel`),this.unsubscribe().then(()=>this.subscribe())),this._on(e,r,n)}async httpSend(e,r,n={}){var i;const o=this.socket.accessTokenValue?`Bearer ${this.socket.accessTokenValue}`:"";if(r==null)return Promise.reject("Payload is required for httpSend()");const c={method:"POST",headers:{Authorization:o,apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:r,private:this.private}]})},a=await this._fetchWithTimeout(this.broadcastEndpointURL,c,(i=n.timeout)!==null&&i!==void 0?i:this.timeout);if(a.status===202)return{success:!0};let m=a.statusText;try{const g=await a.json();m=g.error||g.message||m}catch{}return Promise.reject(new Error(m))}async send(e,r={}){var n,i;if(!this._canPush()&&e.type==="broadcast"){console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");const{event:o,payload:c}=e,m={method:"POST",headers:{Authorization:this.socket.accessTokenValue?`Bearer ${this.socket.accessTokenValue}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:o,payload:c,private:this.private}]})};try{const g=await this._fetchWithTimeout(this.broadcastEndpointURL,m,(n=r.timeout)!==null&&n!==void 0?n:this.timeout);return await((i=g.body)===null||i===void 0?void 0:i.cancel()),g.ok?"ok":"error"}catch(g){return g.name==="AbortError"?"timed out":"error"}}else return new Promise(o=>{var c,a,m;const g=this._push(e.type,e,r.timeout||this.timeout);e.type==="broadcast"&&!(!((m=(a=(c=this.params)===null||c===void 0?void 0:c.config)===null||a===void 0?void 0:a.broadcast)===null||m===void 0)&&m.ack)&&o("ok"),g.receive("ok",()=>o("ok")),g.receive("error",()=>o("error")),g.receive("timeout",()=>o("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=wl.leaving;const r=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(of.close,"leave",this._joinRef())};this.joinPush.destroy();let n=null;return new Promise(i=>{n=new HF(this,of.leave,{},e),n.receive("ok",()=>{r(),i("ok")}).receive("timeout",()=>{r(),i("timed out")}).receive("error",()=>{i("error")}),n.send(),this._canPush()||n.trigger("ok",{})}).finally(()=>{n==null||n.destroy()})}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=wl.closed,this.bindings={}}async _fetchWithTimeout(e,r,n){const i=new AbortController,o=setTimeout(()=>i.abort(),n),c=await this.socket.fetch(e,Object.assign(Object.assign({},r),{signal:i.signal}));return clearTimeout(o),c}_push(e,r,n=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let i=new HF(this,e,r,n);return this._canPush()?i.send():this._addToPushBuffer(i),i}_addToPushBuffer(e){if(e.startTimeout(),this.pushBuffer.push(e),this.pushBuffer.length>jIe){const r=this.pushBuffer.shift();r&&(r.destroy(),this.socket.log("channel",`discarded push due to buffer overflow: ${r.event}`,r.payload))}}_onMessage(e,r,n){return r}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,r,n){var i,o;const c=e.toLocaleLowerCase(),{close:a,error:m,leave:g,join:_}=of;if(n&&[a,m,g,_].indexOf(c)>=0&&n!==this._joinRef())return;let N=this._onMessage(c,r,n);if(r&&!N)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(c)?(i=this.bindings.postgres_changes)===null||i===void 0||i.filter(C=>{var P,A,I;return((P=C.filter)===null||P===void 0?void 0:P.event)==="*"||((I=(A=C.filter)===null||A===void 0?void 0:A.event)===null||I===void 0?void 0:I.toLocaleLowerCase())===c}).map(C=>C.callback(N,n)):(o=this.bindings[c])===null||o===void 0||o.filter(C=>{var P,A,I,O,R,z;if(["broadcast","presence","postgres_changes"].includes(c))if("id"in C){const W=C.id,V=(P=C.filter)===null||P===void 0?void 0:P.event;return W&&((A=r.ids)===null||A===void 0?void 0:A.includes(W))&&(V==="*"||(V==null?void 0:V.toLocaleLowerCase())===((I=r.data)===null||I===void 0?void 0:I.type.toLocaleLowerCase()))}else{const W=(R=(O=C==null?void 0:C.filter)===null||O===void 0?void 0:O.event)===null||R===void 0?void 0:R.toLocaleLowerCase();return W==="*"||W===((z=r==null?void 0:r.event)===null||z===void 0?void 0:z.toLocaleLowerCase())}else return C.type.toLocaleLowerCase()===c}).map(C=>{if(typeof N=="object"&&"ids"in N){const P=N.data,{schema:A,table:I,commit_timestamp:O,type:R,errors:z}=P;N=Object.assign(Object.assign({},{schema:A,table:I,commit_timestamp:O,eventType:R,new:{},old:{},errors:z}),this._getPayloadRecords(P))}C.callback(N,n)})}_isClosed(){return this.state===wl.closed}_isJoined(){return this.state===wl.joined}_isJoining(){return this.state===wl.joining}_isLeaving(){return this.state===wl.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,r,n){const i=e.toLocaleLowerCase(),o={type:i,filter:r,callback:n};return this.bindings[i]?this.bindings[i].push(o):this.bindings[i]=[o],this}_off(e,r){const n=e.toLocaleLowerCase();return this.bindings[n]&&(this.bindings[n]=this.bindings[n].filter(i=>{var o;return!(((o=i.type)===null||o===void 0?void 0:o.toLocaleLowerCase())===n&&w8.isEqual(i.filter,r))})),this}static isEqual(e,r){if(Object.keys(e).length!==Object.keys(r).length)return!1;for(const n in e)if(e[n]!==r[n])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(of.close,{},e)}_onError(e){this._on(of.error,{},r=>e(r))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=wl.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const r={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(r.new=VY(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(r.old=VY(e.columns,e.old_record)),r}}const WF=()=>{},SP={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},PIe=[1e3,2e3,5e3,1e4],IIe=1e4,MIe=` addEventListener("message", (e) => { if (e.data.event === "start") { setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); } });`;class OIe{constructor(e,r){var n;if(this.accessTokenValue=null,this.apiKey=null,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers={},this.params={},this.timeout=i$,this.transport=null,this.heartbeatIntervalMs=SP.HEARTBEAT_INTERVAL,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=WF,this.ref=0,this.reconnectTimer=null,this.logger=WF,this.conn=null,this.sendBuffer=[],this.serializer=new SIe,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._connectionState="disconnected",this._wasManualDisconnect=!1,this._authPromise=null,this._resolveFetch=i=>{let o;return i?o=i:typeof fetch>"u"?o=(...c)=>Lj(async()=>{const{default:a}=await Promise.resolve().then(()=>s0);return{default:a}},void 0).then(({default:a})=>a(...c)).catch(a=>{throw new Error(`Failed to load @supabase/node-fetch: ${a.message}. This is required for HTTP requests in Node.js environments without native fetch.`)}):o=fetch,(...c)=>o(...c)},!(!((n=r==null?void 0:r.params)===null||n===void 0)&&n.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=r.params.apikey,this.endPoint=`${e}/${a$.websocket}`,this.httpEndpoint=Lce(e),this._initializeOptions(r),this._setupReconnectionTimer(),this.fetch=this._resolveFetch(r==null?void 0:r.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.conn!==null&&this.isConnected())){if(this._setConnectionState("connecting"),this._setAuthSafely("connect"),this.transport)this.conn=new this.transport(this.endpointURL());else try{this.conn=xIe.createWebSocket(this.endpointURL())}catch(e){this._setConnectionState("disconnected");const r=e.message;throw r.includes("Node.js")?new Error(`${r} To use Realtime in Node.js, you need to provide a WebSocket implementation: Option 1: Use Node.js 22+ which has native WebSocket support Option 2: Install and provide the "ws" package: npm install ws import ws from "ws" const client = new RealtimeClient(url, { ...options, transport: ws })`):new Error(`WebSocket not available: ${r}`)}this._setupConnectionHandlers()}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:bIe}))}disconnect(e,r){if(!this.isDisconnecting())if(this._setConnectionState("disconnecting",!0),this.conn){const n=setTimeout(()=>{this._setConnectionState("disconnected")},100);this.conn.onclose=()=>{clearTimeout(n),this._setConnectionState("disconnected")},e?this.conn.close(e,r??""):this.conn.close(),this._teardownConnection()}else this._setConnectionState("disconnected")}getChannels(){return this.channels}async removeChannel(e){const r=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),r}async removeAllChannels(){const e=await Promise.all(this.channels.map(r=>r.unsubscribe()));return this.channels=[],this.disconnect(),e}log(e,r,n){this.logger(e,r,n)}connectionState(){switch(this.conn&&this.conn.readyState){case s2.connecting:return zv.Connecting;case s2.open:return zv.Open;case s2.closing:return zv.Closing;default:return zv.Closed}}isConnected(){return this.connectionState()===zv.Open}isConnecting(){return this._connectionState==="connecting"}isDisconnecting(){return this._connectionState==="disconnecting"}channel(e,r={config:{}}){const n=`realtime:${e}`,i=this.getChannels().find(o=>o.topic===n);if(i)return i;{const o=new w8(`realtime:${e}`,r,this);return this.channels.push(o),o}}push(e){const{topic:r,event:n,payload:i,ref:o}=e,c=()=>{this.encode(e,a=>{var m;(m=this.conn)===null||m===void 0||m.send(a)})};this.log("push",`${r} ${n} (${o})`,i),this.isConnected()?c():this.sendBuffer.push(c)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}async sendHeartbeat(){var e;if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(r){this.log("error","error in heartbeat callback",r)}return}if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(r){this.log("error","error in heartbeat callback",r)}this._wasManualDisconnect=!1,(e=this.conn)===null||e===void 0||e.close(wIe,"heartbeat timeout"),setTimeout(()=>{var r;this.isConnected()||(r=this.reconnectTimer)===null||r===void 0||r.scheduleTimeout()},SP.HEARTBEAT_TIMEOUT_FALLBACK);return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(r){this.log("error","error in heartbeat callback",r)}this._setAuthSafely("heartbeat")}onHeartbeat(e){this.heartbeatCallback=e}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let r=this.channels.find(n=>n.topic===e&&(n._isJoined()||n._isJoining()));r&&(this.log("transport",`leaving duplicate topic "${e}"`),r.unsubscribe())}_remove(e){this.channels=this.channels.filter(r=>r.topic!==e.topic)}_onConnMessage(e){this.decode(e.data,r=>{if(r.topic==="phoenix"&&r.event==="phx_reply")try{this.heartbeatCallback(r.payload.status==="ok"?"ok":"error")}catch(g){this.log("error","error in heartbeat callback",g)}r.ref&&r.ref===this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null);const{topic:n,event:i,payload:o,ref:c}=r,a=c?`(${c})`:"",m=o.status||"";this.log("receive",`${m} ${n} ${i} ${a}`.trim(),o),this.channels.filter(g=>g._isMember(n)).forEach(g=>g._trigger(i,o,c)),this._triggerStateCallbacks("message",r)})}_clearTimer(e){var r;e==="heartbeat"&&this.heartbeatTimer?(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0):e==="reconnect"&&((r=this.reconnectTimer)===null||r===void 0||r.reset())}_clearAllTimers(){this._clearTimer("heartbeat"),this._clearTimer("reconnect")}_setupConnectionHandlers(){this.conn&&("binaryType"in this.conn&&(this.conn.binaryType="arraybuffer"),this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e))}_teardownConnection(){this.conn&&(this.conn.onopen=null,this.conn.onerror=null,this.conn.onmessage=null,this.conn.onclose=null,this.conn=null),this._clearAllTimers(),this.channels.forEach(e=>e.teardown())}_onConnOpen(){this._setConnectionState("connected"),this.log("transport",`connected to ${this.endpointURL()}`),this.flushSendBuffer(),this._clearTimer("reconnect"),this.worker?this.workerRef||this._startWorkerHeartbeat():this._startHeartbeat(),this._triggerStateCallbacks("open")}_startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=r=>{this.log("worker","worker error",r.message),this.workerRef.terminate()},this.workerRef.onmessage=r=>{r.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_onConnClose(e){var r;this._setConnectionState("disconnected"),this.log("transport","close",e),this._triggerChanError(),this._clearTimer("heartbeat"),this._wasManualDisconnect||(r=this.reconnectTimer)===null||r===void 0||r.scheduleTimeout(),this._triggerStateCallbacks("close",e)}_onConnError(e){this._setConnectionState("disconnected"),this.log("transport",`${e}`),this._triggerChanError(),this._triggerStateCallbacks("error",e)}_triggerChanError(){this.channels.forEach(e=>e._trigger(of.error))}_appendParams(e,r){if(Object.keys(r).length===0)return e;const n=e.match(/\?/)?"&":"?",i=new URLSearchParams(r);return`${e}${n}${i}`}_workerObjectUrl(e){let r;if(e)r=e;else{const n=new Blob([MIe],{type:"application/javascript"});r=URL.createObjectURL(n)}return r}_setConnectionState(e,r=!1){this._connectionState=e,e==="connecting"?this._wasManualDisconnect=!1:e==="disconnecting"&&(this._wasManualDisconnect=r)}async _performAuth(e=null){let r;e?r=e:this.accessToken?r=await this.accessToken():r=this.accessTokenValue,this.accessTokenValue!=r&&(this.accessTokenValue=r,this.channels.forEach(n=>{const i={access_token:r,version:_Ie};r&&n.updateJoinPayload(i),n.joinedOnce&&n._isJoined()&&n._push(of.access_token,{access_token:r})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this.setAuth().catch(r=>{this.log("error",`error setting auth in ${e}`,r)})}_triggerStateCallbacks(e,r){try{this.stateChangeCallbacks[e].forEach(n=>{try{n(r)}catch(i){this.log("error",`error in ${e} callback`,i)}})}catch(n){this.log("error",`error triggering ${e} callbacks`,n)}}_setupReconnectionTimer(){this.reconnectTimer=new Rce(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},SP.RECONNECT_DELAY)},this.reconnectAfterMs)}_initializeOptions(e){var r,n,i,o,c,a,m,g,_;if(this.transport=(r=e==null?void 0:e.transport)!==null&&r!==void 0?r:null,this.timeout=(n=e==null?void 0:e.timeout)!==null&&n!==void 0?n:i$,this.heartbeatIntervalMs=(i=e==null?void 0:e.heartbeatIntervalMs)!==null&&i!==void 0?i:SP.HEARTBEAT_INTERVAL,this.worker=(o=e==null?void 0:e.worker)!==null&&o!==void 0?o:!1,this.accessToken=(c=e==null?void 0:e.accessToken)!==null&&c!==void 0?c:null,this.heartbeatCallback=(a=e==null?void 0:e.heartbeatCallback)!==null&&a!==void 0?a:WF,e!=null&&e.params&&(this.params=e.params),e!=null&&e.logger&&(this.logger=e.logger),(e!=null&&e.logLevel||e!=null&&e.log_level)&&(this.logLevel=e.logLevel||e.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),this.reconnectAfterMs=(m=e==null?void 0:e.reconnectAfterMs)!==null&&m!==void 0?m:j=>PIe[j-1]||IIe,this.encode=(g=e==null?void 0:e.encode)!==null&&g!==void 0?g:(j,N)=>N(JSON.stringify(j)),this.decode=(_=e==null?void 0:e.decode)!==null&&_!==void 0?_:this.serializer.decode.bind(this.serializer),this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e==null?void 0:e.workerUrl}}}class j8 extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}}function wo(t){return typeof t=="object"&&t!==null&&"__isStorageError"in t}class RIe extends j8{constructor(e,r,n){super(e),this.name="StorageApiError",this.status=r,this.statusCode=n}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}}class l$ extends j8{constructor(e,r){super(e),this.name="StorageUnknownError",this.originalError=r}}const S8=t=>{let e;return t?e=t:typeof fetch>"u"?e=(...r)=>Lj(async()=>{const{default:n}=await Promise.resolve().then(()=>s0);return{default:n}},void 0).then(({default:n})=>n(...r)):e=fetch,(...r)=>e(...r)},DIe=()=>ss(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Lj(()=>Promise.resolve().then(()=>s0),void 0)).Response:Response}),c$=t=>{if(Array.isArray(t))return t.map(r=>c$(r));if(typeof t=="function"||t!==Object(t))return t;const e={};return Object.entries(t).forEach(([r,n])=>{const i=r.replace(/([-_][a-z])/gi,o=>o.toUpperCase().replace(/[-_]/g,""));e[i]=c$(n)}),e},LIe=t=>{if(typeof t!="object"||t===null)return!1;const e=Object.getPrototypeOf(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)},GF=t=>{var e;return t.msg||t.message||t.error_description||(typeof t.error=="string"?t.error:(e=t.error)===null||e===void 0?void 0:e.message)||JSON.stringify(t)},FIe=(t,e,r)=>ss(void 0,void 0,void 0,function*(){const n=yield DIe();t instanceof n&&!(r!=null&&r.noResolveJson)?t.json().then(i=>{const o=t.status||500,c=(i==null?void 0:i.statusCode)||o+"";e(new RIe(GF(i),o,c))}).catch(i=>{e(new l$(GF(i),i))}):e(new l$(GF(t),t))}),zIe=(t,e,r,n)=>{const i={method:t,headers:(e==null?void 0:e.headers)||{}};return t==="GET"||!n?i:(LIe(n)?(i.headers=Object.assign({"Content-Type":"application/json"},e==null?void 0:e.headers),i.body=JSON.stringify(n)):i.body=n,e!=null&&e.duplex&&(i.duplex=e.duplex),Object.assign(Object.assign({},i),r))};function wT(t,e,r,n,i,o){return ss(this,void 0,void 0,function*(){return new Promise((c,a)=>{t(r,zIe(e,n,i,o)).then(m=>{if(!m.ok)throw m;return n!=null&&n.noResolveJson?m:m.json()}).then(m=>c(m)).catch(m=>FIe(m,a,n))})})}function tk(t,e,r,n){return ss(this,void 0,void 0,function*(){return wT(t,"GET",e,r,n)})}function rf(t,e,r,n,i){return ss(this,void 0,void 0,function*(){return wT(t,"POST",e,n,i,r)})}function u$(t,e,r,n,i){return ss(this,void 0,void 0,function*(){return wT(t,"PUT",e,n,i,r)})}function BIe(t,e,r,n){return ss(this,void 0,void 0,function*(){return wT(t,"HEAD",e,Object.assign(Object.assign({},r),{noResolveJson:!0}),n)})}function N8(t,e,r,n,i){return ss(this,void 0,void 0,function*(){return wT(t,"DELETE",e,n,i,r)})}class $Ie{constructor(e,r){this.downloadFn=e,this.shouldThrowOnError=r}then(e,r){return this.execute().then(e,r)}execute(){return ss(this,void 0,void 0,function*(){try{return{data:(yield this.downloadFn()).body,error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(wo(e))return{data:null,error:e};throw e}})}}var Fce;class UIe{constructor(e,r){this.downloadFn=e,this.shouldThrowOnError=r,this[Fce]="BlobDownloadBuilder",this.promise=null}asStream(){return new $Ie(this.downloadFn,this.shouldThrowOnError)}then(e,r){return this.getPromise().then(e,r)}catch(e){return this.getPromise().catch(e)}finally(e){return this.getPromise().finally(e)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}execute(){return ss(this,void 0,void 0,function*(){try{return{data:yield(yield this.downloadFn()).blob(),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(wo(e))return{data:null,error:e};throw e}})}}Fce=Symbol.toStringTag;const VIe={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},WY={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class qIe{constructor(e,r={},n,i){this.shouldThrowOnError=!1,this.url=e,this.headers=r,this.bucketId=n,this.fetch=S8(i)}throwOnError(){return this.shouldThrowOnError=!0,this}uploadOrUpdate(e,r,n,i){return ss(this,void 0,void 0,function*(){try{let o;const c=Object.assign(Object.assign({},WY),i);let a=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(c.upsert)});const m=c.metadata;typeof Blob<"u"&&n instanceof Blob?(o=new FormData,o.append("cacheControl",c.cacheControl),m&&o.append("metadata",this.encodeMetadata(m)),o.append("",n)):typeof FormData<"u"&&n instanceof FormData?(o=n,o.append("cacheControl",c.cacheControl),m&&o.append("metadata",this.encodeMetadata(m))):(o=n,a["cache-control"]=`max-age=${c.cacheControl}`,a["content-type"]=c.contentType,m&&(a["x-metadata"]=this.toBase64(this.encodeMetadata(m)))),i!=null&&i.headers&&(a=Object.assign(Object.assign({},a),i.headers));const g=this._removeEmptyFolders(r),_=this._getFinalPath(g),j=yield(e=="PUT"?u$:rf)(this.fetch,`${this.url}/object/${_}`,o,Object.assign({headers:a},c!=null&&c.duplex?{duplex:c.duplex}:{}));return{data:{path:g,id:j.Id,fullPath:j.Key},error:null}}catch(o){if(this.shouldThrowOnError)throw o;if(wo(o))return{data:null,error:o};throw o}})}upload(e,r,n){return ss(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,r,n)})}uploadToSignedUrl(e,r,n,i){return ss(this,void 0,void 0,function*(){const o=this._removeEmptyFolders(e),c=this._getFinalPath(o),a=new URL(this.url+`/object/upload/sign/${c}`);a.searchParams.set("token",r);try{let m;const g=Object.assign({upsert:WY.upsert},i),_=Object.assign(Object.assign({},this.headers),{"x-upsert":String(g.upsert)});typeof Blob<"u"&&n instanceof Blob?(m=new FormData,m.append("cacheControl",g.cacheControl),m.append("",n)):typeof FormData<"u"&&n instanceof FormData?(m=n,m.append("cacheControl",g.cacheControl)):(m=n,_["cache-control"]=`max-age=${g.cacheControl}`,_["content-type"]=g.contentType);const j=yield u$(this.fetch,a.toString(),m,{headers:_});return{data:{path:o,fullPath:j.Key},error:null}}catch(m){if(this.shouldThrowOnError)throw m;if(wo(m))return{data:null,error:m};throw m}})}createSignedUploadUrl(e,r){return ss(this,void 0,void 0,function*(){try{let n=this._getFinalPath(e);const i=Object.assign({},this.headers);r!=null&&r.upsert&&(i["x-upsert"]="true");const o=yield rf(this.fetch,`${this.url}/object/upload/sign/${n}`,{},{headers:i}),c=new URL(this.url+o.url),a=c.searchParams.get("token");if(!a)throw new j8("No token returned by API");return{data:{signedUrl:c.toString(),path:e,token:a},error:null}}catch(n){if(this.shouldThrowOnError)throw n;if(wo(n))return{data:null,error:n};throw n}})}update(e,r,n){return ss(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,r,n)})}move(e,r,n){return ss(this,void 0,void 0,function*(){try{return{data:yield rf(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:r,destinationBucket:n==null?void 0:n.destinationBucket},{headers:this.headers}),error:null}}catch(i){if(this.shouldThrowOnError)throw i;if(wo(i))return{data:null,error:i};throw i}})}copy(e,r,n){return ss(this,void 0,void 0,function*(){try{return{data:{path:(yield rf(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:r,destinationBucket:n==null?void 0:n.destinationBucket},{headers:this.headers})).Key},error:null}}catch(i){if(this.shouldThrowOnError)throw i;if(wo(i))return{data:null,error:i};throw i}})}createSignedUrl(e,r,n){return ss(this,void 0,void 0,function*(){try{let i=this._getFinalPath(e),o=yield rf(this.fetch,`${this.url}/object/sign/${i}`,Object.assign({expiresIn:r},n!=null&&n.transform?{transform:n.transform}:{}),{headers:this.headers});const c=n!=null&&n.download?`&download=${n.download===!0?"":n.download}`:"";return o={signedUrl:encodeURI(`${this.url}${o.signedURL}${c}`)},{data:o,error:null}}catch(i){if(this.shouldThrowOnError)throw i;if(wo(i))return{data:null,error:i};throw i}})}createSignedUrls(e,r,n){return ss(this,void 0,void 0,function*(){try{const i=yield rf(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:r,paths:e},{headers:this.headers}),o=n!=null&&n.download?`&download=${n.download===!0?"":n.download}`:"";return{data:i.map(c=>Object.assign(Object.assign({},c),{signedUrl:c.signedURL?encodeURI(`${this.url}${c.signedURL}${o}`):null})),error:null}}catch(i){if(this.shouldThrowOnError)throw i;if(wo(i))return{data:null,error:i};throw i}})}download(e,r){const i=typeof(r==null?void 0:r.transform)<"u"?"render/image/authenticated":"object",o=this.transformOptsToQueryString((r==null?void 0:r.transform)||{}),c=o?`?${o}`:"",a=this._getFinalPath(e),m=()=>tk(this.fetch,`${this.url}/${i}/${a}${c}`,{headers:this.headers,noResolveJson:!0});return new UIe(m,this.shouldThrowOnError)}info(e){return ss(this,void 0,void 0,function*(){const r=this._getFinalPath(e);try{const n=yield tk(this.fetch,`${this.url}/object/info/${r}`,{headers:this.headers});return{data:c$(n),error:null}}catch(n){if(this.shouldThrowOnError)throw n;if(wo(n))return{data:null,error:n};throw n}})}exists(e){return ss(this,void 0,void 0,function*(){const r=this._getFinalPath(e);try{return yield BIe(this.fetch,`${this.url}/object/${r}`,{headers:this.headers}),{data:!0,error:null}}catch(n){if(this.shouldThrowOnError)throw n;if(wo(n)&&n instanceof l$){const i=n.originalError;if([400,404].includes(i==null?void 0:i.status))return{data:!1,error:n}}throw n}})}getPublicUrl(e,r){const n=this._getFinalPath(e),i=[],o=r!=null&&r.download?`download=${r.download===!0?"":r.download}`:"";o!==""&&i.push(o);const a=typeof(r==null?void 0:r.transform)<"u"?"render/image":"object",m=this.transformOptsToQueryString((r==null?void 0:r.transform)||{});m!==""&&i.push(m);let g=i.join("&");return g!==""&&(g=`?${g}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${n}${g}`)}}}remove(e){return ss(this,void 0,void 0,function*(){try{return{data:yield N8(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(wo(r))return{data:null,error:r};throw r}})}list(e,r,n){return ss(this,void 0,void 0,function*(){try{const i=Object.assign(Object.assign(Object.assign({},VIe),r),{prefix:e||""});return{data:yield rf(this.fetch,`${this.url}/object/list/${this.bucketId}`,i,{headers:this.headers},n),error:null}}catch(i){if(this.shouldThrowOnError)throw i;if(wo(i))return{data:null,error:i};throw i}})}listV2(e,r){return ss(this,void 0,void 0,function*(){try{const n=Object.assign({},e);return{data:yield rf(this.fetch,`${this.url}/object/list-v2/${this.bucketId}`,n,{headers:this.headers},r),error:null}}catch(n){if(this.shouldThrowOnError)throw n;if(wo(n))return{data:null,error:n};throw n}})}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return typeof Buffer<"u"?Buffer.from(e).toString("base64"):btoa(e)}_getFinalPath(e){return`${this.bucketId}/${e.replace(/^\/+/,"")}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){const r=[];return e.width&&r.push(`width=${e.width}`),e.height&&r.push(`height=${e.height}`),e.resize&&r.push(`resize=${e.resize}`),e.format&&r.push(`format=${e.format}`),e.quality&&r.push(`quality=${e.quality}`),r.join("&")}}const zce="2.78.0",Bce={"X-Client-Info":`storage-js/${zce}`};class HIe{constructor(e,r={},n,i){this.shouldThrowOnError=!1;const o=new URL(e);i!=null&&i.useNewHostname&&/supabase\.(co|in|red)$/.test(o.hostname)&&!o.hostname.includes("storage.supabase.")&&(o.hostname=o.hostname.replace("supabase.","storage.supabase.")),this.url=o.href.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},Bce),r),this.fetch=S8(n)}throwOnError(){return this.shouldThrowOnError=!0,this}listBuckets(e){return ss(this,void 0,void 0,function*(){try{const r=this.listBucketOptionsToQueryString(e);return{data:yield tk(this.fetch,`${this.url}/bucket${r}`,{headers:this.headers}),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(wo(r))return{data:null,error:r};throw r}})}getBucket(e){return ss(this,void 0,void 0,function*(){try{return{data:yield tk(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(wo(r))return{data:null,error:r};throw r}})}createBucket(e){return ss(this,arguments,void 0,function*(r,n={public:!1}){try{return{data:yield rf(this.fetch,`${this.url}/bucket`,{id:r,name:r,type:n.type,public:n.public,file_size_limit:n.fileSizeLimit,allowed_mime_types:n.allowedMimeTypes},{headers:this.headers}),error:null}}catch(i){if(this.shouldThrowOnError)throw i;if(wo(i))return{data:null,error:i};throw i}})}updateBucket(e,r){return ss(this,void 0,void 0,function*(){try{return{data:yield u$(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:r.public,file_size_limit:r.fileSizeLimit,allowed_mime_types:r.allowedMimeTypes},{headers:this.headers}),error:null}}catch(n){if(this.shouldThrowOnError)throw n;if(wo(n))return{data:null,error:n};throw n}})}emptyBucket(e){return ss(this,void 0,void 0,function*(){try{return{data:yield rf(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(wo(r))return{data:null,error:r};throw r}})}deleteBucket(e){return ss(this,void 0,void 0,function*(){try{return{data:yield N8(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(wo(r))return{data:null,error:r};throw r}})}listBucketOptionsToQueryString(e){const r={};return e&&("limit"in e&&(r.limit=String(e.limit)),"offset"in e&&(r.offset=String(e.offset)),e.search&&(r.search=e.search),e.sortColumn&&(r.sortColumn=e.sortColumn),e.sortOrder&&(r.sortOrder=e.sortOrder)),Object.keys(r).length>0?"?"+new URLSearchParams(r).toString():""}}class WIe{constructor(e,r={},n){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},Bce),r),this.fetch=S8(n)}throwOnError(){return this.shouldThrowOnError=!0,this}createBucket(e){return ss(this,void 0,void 0,function*(){try{return{data:yield rf(this.fetch,`${this.url}/bucket`,{name:e},{headers:this.headers}),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(wo(r))return{data:null,error:r};throw r}})}listBuckets(e){return ss(this,void 0,void 0,function*(){try{const r=new URLSearchParams;(e==null?void 0:e.limit)!==void 0&&r.set("limit",e.limit.toString()),(e==null?void 0:e.offset)!==void 0&&r.set("offset",e.offset.toString()),e!=null&&e.sortColumn&&r.set("sortColumn",e.sortColumn),e!=null&&e.sortOrder&&r.set("sortOrder",e.sortOrder),e!=null&&e.search&&r.set("search",e.search);const n=r.toString(),i=n?`${this.url}/bucket?${n}`:`${this.url}/bucket`;return{data:yield tk(this.fetch,i,{headers:this.headers}),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(wo(r))return{data:null,error:r};throw r}})}deleteBucket(e){return ss(this,void 0,void 0,function*(){try{return{data:yield N8(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(wo(r))return{data:null,error:r};throw r}})}}const C8={"X-Client-Info":`storage-js/${zce}`,"Content-Type":"application/json"};class $ce extends Error{constructor(e){super(e),this.__isStorageVectorsError=!0,this.name="StorageVectorsError"}}function dd(t){return typeof t=="object"&&t!==null&&"__isStorageVectorsError"in t}class KF extends $ce{constructor(e,r,n){super(e),this.name="StorageVectorsApiError",this.status=r,this.statusCode=n}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}}class GIe extends $ce{constructor(e,r){super(e),this.name="StorageVectorsUnknownError",this.originalError=r}}var GY;(function(t){t.InternalError="InternalError",t.S3VectorConflictException="S3VectorConflictException",t.S3VectorNotFoundException="S3VectorNotFoundException",t.S3VectorBucketNotEmpty="S3VectorBucketNotEmpty",t.S3VectorMaxBucketsExceeded="S3VectorMaxBucketsExceeded",t.S3VectorMaxIndexesExceeded="S3VectorMaxIndexesExceeded"})(GY||(GY={}));const k8=t=>{let e;return t?e=t:typeof fetch>"u"?e=(...r)=>Lj(async()=>{const{default:n}=await Promise.resolve().then(()=>s0);return{default:n}},void 0).then(({default:n})=>n(...r)):e=fetch,(...r)=>e(...r)},KIe=t=>{if(typeof t!="object"||t===null)return!1;const e=Object.getPrototypeOf(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)},KY=t=>t.msg||t.message||t.error_description||t.error||JSON.stringify(t),ZIe=(t,e,r)=>ss(void 0,void 0,void 0,function*(){if(t&&typeof t=="object"&&"status"in t&&"ok"in t&&typeof t.status=="number"&&!(r!=null&&r.noResolveJson)){const i=t.status||500,o=t;if(typeof o.json=="function")o.json().then(c=>{const a=(c==null?void 0:c.statusCode)||(c==null?void 0:c.code)||i+"";e(new KF(KY(c),i,a))}).catch(()=>{const c=i+"",a=o.statusText||`HTTP ${i} error`;e(new KF(a,i,c))});else{const c=i+"",a=o.statusText||`HTTP ${i} error`;e(new KF(a,i,c))}}else e(new GIe(KY(t),t))}),YIe=(t,e,r,n)=>{const i={method:t,headers:(e==null?void 0:e.headers)||{}};return n?(KIe(n)?(i.headers=Object.assign({"Content-Type":"application/json"},e==null?void 0:e.headers),i.body=JSON.stringify(n)):i.body=n,Object.assign(Object.assign({},i),r)):i};function XIe(t,e,r,n,i,o){return ss(this,void 0,void 0,function*(){return new Promise((c,a)=>{t(r,YIe(e,n,i,o)).then(m=>{if(!m.ok)throw m;if(n!=null&&n.noResolveJson)return m;const g=m.headers.get("content-type");return!g||!g.includes("application/json")?{}:m.json()}).then(m=>c(m)).catch(m=>ZIe(m,a,n))})})}function hd(t,e,r,n,i){return ss(this,void 0,void 0,function*(){return XIe(t,"POST",e,n,i,r)})}class QIe{constructor(e,r={},n){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},C8),r),this.fetch=k8(n)}throwOnError(){return this.shouldThrowOnError=!0,this}createIndex(e){return ss(this,void 0,void 0,function*(){try{return{data:(yield hd(this.fetch,`${this.url}/CreateIndex`,e,{headers:this.headers}))||{},error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(dd(r))return{data:null,error:r};throw r}})}getIndex(e,r){return ss(this,void 0,void 0,function*(){try{return{data:yield hd(this.fetch,`${this.url}/GetIndex`,{vectorBucketName:e,indexName:r},{headers:this.headers}),error:null}}catch(n){if(this.shouldThrowOnError)throw n;if(dd(n))return{data:null,error:n};throw n}})}listIndexes(e){return ss(this,void 0,void 0,function*(){try{return{data:yield hd(this.fetch,`${this.url}/ListIndexes`,e,{headers:this.headers}),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(dd(r))return{data:null,error:r};throw r}})}deleteIndex(e,r){return ss(this,void 0,void 0,function*(){try{return{data:(yield hd(this.fetch,`${this.url}/DeleteIndex`,{vectorBucketName:e,indexName:r},{headers:this.headers}))||{},error:null}}catch(n){if(this.shouldThrowOnError)throw n;if(dd(n))return{data:null,error:n};throw n}})}}class JIe{constructor(e,r={},n){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},C8),r),this.fetch=k8(n)}throwOnError(){return this.shouldThrowOnError=!0,this}putVectors(e){return ss(this,void 0,void 0,function*(){try{if(e.vectors.length<1||e.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return{data:(yield hd(this.fetch,`${this.url}/PutVectors`,e,{headers:this.headers}))||{},error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(dd(r))return{data:null,error:r};throw r}})}getVectors(e){return ss(this,void 0,void 0,function*(){try{return{data:yield hd(this.fetch,`${this.url}/GetVectors`,e,{headers:this.headers}),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(dd(r))return{data:null,error:r};throw r}})}listVectors(e){return ss(this,void 0,void 0,function*(){try{if(e.segmentCount!==void 0){if(e.segmentCount<1||e.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(e.segmentIndex!==void 0&&(e.segmentIndex<0||e.segmentIndex>=e.segmentCount))throw new Error(`segmentIndex must be between 0 and ${e.segmentCount-1}`)}return{data:yield hd(this.fetch,`${this.url}/ListVectors`,e,{headers:this.headers}),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(dd(r))return{data:null,error:r};throw r}})}queryVectors(e){return ss(this,void 0,void 0,function*(){try{return{data:yield hd(this.fetch,`${this.url}/QueryVectors`,e,{headers:this.headers}),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(dd(r))return{data:null,error:r};throw r}})}deleteVectors(e){return ss(this,void 0,void 0,function*(){try{if(e.keys.length<1||e.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return{data:(yield hd(this.fetch,`${this.url}/DeleteVectors`,e,{headers:this.headers}))||{},error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(dd(r))return{data:null,error:r};throw r}})}}class eMe{constructor(e,r={},n){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},C8),r),this.fetch=k8(n)}throwOnError(){return this.shouldThrowOnError=!0,this}createBucket(e){return ss(this,void 0,void 0,function*(){try{return{data:(yield hd(this.fetch,`${this.url}/CreateVectorBucket`,{vectorBucketName:e},{headers:this.headers}))||{},error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(dd(r))return{data:null,error:r};throw r}})}getBucket(e){return ss(this,void 0,void 0,function*(){try{return{data:yield hd(this.fetch,`${this.url}/GetVectorBucket`,{vectorBucketName:e},{headers:this.headers}),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(dd(r))return{data:null,error:r};throw r}})}listBuckets(){return ss(this,arguments,void 0,function*(e={}){try{return{data:yield hd(this.fetch,`${this.url}/ListVectorBuckets`,e,{headers:this.headers}),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(dd(r))return{data:null,error:r};throw r}})}deleteBucket(e){return ss(this,void 0,void 0,function*(){try{return{data:(yield hd(this.fetch,`${this.url}/DeleteVectorBucket`,{vectorBucketName:e},{headers:this.headers}))||{},error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(dd(r))return{data:null,error:r};throw r}})}}class tMe extends eMe{constructor(e,r={}){super(e,r.headers||{},r.fetch)}from(e){return new rMe(this.url,this.headers,e,this.fetch)}}class rMe extends QIe{constructor(e,r,n,i){super(e,r,i),this.vectorBucketName=n}createIndex(e){const r=Object.create(null,{createIndex:{get:()=>super.createIndex}});return ss(this,void 0,void 0,function*(){return r.createIndex.call(this,Object.assign(Object.assign({},e),{vectorBucketName:this.vectorBucketName}))})}listIndexes(){const e=Object.create(null,{listIndexes:{get:()=>super.listIndexes}});return ss(this,arguments,void 0,function*(r={}){return e.listIndexes.call(this,Object.assign(Object.assign({},r),{vectorBucketName:this.vectorBucketName}))})}getIndex(e){const r=Object.create(null,{getIndex:{get:()=>super.getIndex}});return ss(this,void 0,void 0,function*(){return r.getIndex.call(this,this.vectorBucketName,e)})}deleteIndex(e){const r=Object.create(null,{deleteIndex:{get:()=>super.deleteIndex}});return ss(this,void 0,void 0,function*(){return r.deleteIndex.call(this,this.vectorBucketName,e)})}index(e){return new nMe(this.url,this.headers,this.vectorBucketName,e,this.fetch)}}class nMe extends JIe{constructor(e,r,n,i,o){super(e,r,o),this.vectorBucketName=n,this.indexName=i}putVectors(e){const r=Object.create(null,{putVectors:{get:()=>super.putVectors}});return ss(this,void 0,void 0,function*(){return r.putVectors.call(this,Object.assign(Object.assign({},e),{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))})}getVectors(e){const r=Object.create(null,{getVectors:{get:()=>super.getVectors}});return ss(this,void 0,void 0,function*(){return r.getVectors.call(this,Object.assign(Object.assign({},e),{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))})}listVectors(){const e=Object.create(null,{listVectors:{get:()=>super.listVectors}});return ss(this,arguments,void 0,function*(r={}){return e.listVectors.call(this,Object.assign(Object.assign({},r),{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))})}queryVectors(e){const r=Object.create(null,{queryVectors:{get:()=>super.queryVectors}});return ss(this,void 0,void 0,function*(){return r.queryVectors.call(this,Object.assign(Object.assign({},e),{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))})}deleteVectors(e){const r=Object.create(null,{deleteVectors:{get:()=>super.deleteVectors}});return ss(this,void 0,void 0,function*(){return r.deleteVectors.call(this,Object.assign(Object.assign({},e),{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))})}}class sMe extends HIe{constructor(e,r={},n,i){super(e,r,n,i)}from(e){return new qIe(this.url,this.headers,e,this.fetch)}get vectors(){return new tMe(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new WIe(this.url+"/iceberg",this.headers,this.fetch)}}const iMe="2.78.0";let FC="";typeof Deno<"u"?FC="deno":typeof document<"u"?FC="web":typeof navigator<"u"&&navigator.product==="ReactNative"?FC="react-native":FC="node";const aMe={"X-Client-Info":`supabase-js-${FC}/${iMe}`},oMe={headers:aMe},lMe={schema:"public"},cMe={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},uMe={},dMe=t=>{let e;return t?e=t:typeof fetch>"u"?e=gce:e=fetch,(...r)=>e(...r)},hMe=()=>typeof Headers>"u"?yce:Headers,fMe=(t,e,r)=>{const n=dMe(r),i=hMe();return async(o,c)=>{var a;const m=(a=await e())!==null&&a!==void 0?a:t;let g=new i(c==null?void 0:c.headers);return g.has("apikey")||g.set("apikey",t),g.has("Authorization")||g.set("Authorization",`Bearer ${m}`),n(o,Object.assign(Object.assign({},c),{headers:g}))}};function pMe(t){return t.endsWith("/")?t:t+"/"}function mMe(t,e){var r,n;const{db:i,auth:o,realtime:c,global:a}=t,{db:m,auth:g,realtime:_,global:j}=e,N={db:Object.assign(Object.assign({},m),i),auth:Object.assign(Object.assign({},g),o),realtime:Object.assign(Object.assign({},_),c),storage:{},global:Object.assign(Object.assign(Object.assign({},j),a),{headers:Object.assign(Object.assign({},(r=j==null?void 0:j.headers)!==null&&r!==void 0?r:{}),(n=a==null?void 0:a.headers)!==null&&n!==void 0?n:{})}),accessToken:async()=>""};return t.accessToken?N.accessToken=t.accessToken:delete N.accessToken,N}function gMe(t){const e=t==null?void 0:t.trim();if(!e)throw new Error("supabaseUrl is required.");if(!e.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(pMe(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}const Uce="2.78.0",vw=30*1e3,d$=3,ZF=d$*vw,yMe="http://localhost:9999",xMe="supabase.auth.token",vMe={"X-Client-Info":`gotrue-js/${Uce}`},h$="X-Supabase-Api-Version",Vce={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},_Me=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,bMe=10*60*1e3;class rk extends Error{constructor(e,r,n){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=r,this.code=n}}function gs(t){return typeof t=="object"&&t!==null&&"__isAuthError"in t}class wMe extends rk{constructor(e,r,n){super(e,r,n),this.name="AuthApiError",this.status=r,this.code=n}}function jMe(t){return gs(t)&&t.name==="AuthApiError"}class Bv extends rk{constructor(e,r){super(e),this.name="AuthUnknownError",this.originalError=r}}class _x extends rk{constructor(e,r,n,i){super(e,n,i),this.name=r,this.status=n}}class Xh extends _x{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function SMe(t){return gs(t)&&t.name==="AuthSessionMissingError"}class tw extends _x{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class NP extends _x{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class CP extends _x{constructor(e,r=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=r}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}function NMe(t){return gs(t)&&t.name==="AuthImplicitGrantRedirectError"}class ZY extends _x{constructor(e,r=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=r}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class f$ extends _x{constructor(e,r){super(e,"AuthRetryableFetchError",r,void 0)}}function YF(t){return gs(t)&&t.name==="AuthRetryableFetchError"}class YY extends _x{constructor(e,r,n){super(e,"AuthWeakPasswordError",r,"weak_password"),this.reasons=n}}class p$ extends _x{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const CM="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),XY=` \r=`.split(""),CMe=(()=>{const t=new Array(128);for(let e=0;e=6;){const n=e.queue>>e.queuedBits-6&63;r(CM[n]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){const n=e.queue>>e.queuedBits-6&63;r(CM[n]),e.queuedBits-=6}}function qce(t,e,r){const n=CMe[t];if(n>-1)for(e.queue=e.queue<<6|n,e.queuedBits+=6;e.queuedBits>=8;)r(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(n===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(t)}"`)}}function JY(t){const e=[],r=c=>{e.push(String.fromCodePoint(c))},n={utf8seq:0,codepoint:0},i={queue:0,queuedBits:0},o=c=>{EMe(c,n,r)};for(let c=0;c>6),e(128|t&63);return}else if(t<=65535){e(224|t>>12),e(128|t>>6&63),e(128|t&63);return}else if(t<=1114111){e(240|t>>18),e(128|t>>12&63),e(128|t>>6&63),e(128|t&63);return}throw new Error(`Unrecognized Unicode codepoint: ${t.toString(16)}`)}function TMe(t,e){for(let r=0;r55295&&n<=56319){const i=(n-55296)*1024&65535;n=(t.charCodeAt(r+1)-56320&65535|i)+65536,r+=1}kMe(n,e)}}function EMe(t,e,r){if(e.utf8seq===0){if(t<=127){r(t);return}for(let n=1;n<6;n+=1)if(!(t>>7-n&1)){e.utf8seq=n;break}if(e.utf8seq===2)e.codepoint=t&31;else if(e.utf8seq===3)e.codepoint=t&15;else if(e.utf8seq===4)e.codepoint=t&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(t<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|t&63,e.utf8seq-=1,e.utf8seq===0&&r(e.codepoint)}}function s1(t){const e=[],r={queue:0,queuedBits:0},n=i=>{e.push(i)};for(let i=0;ie.push(r)),new Uint8Array(e)}function Gv(t){const e=[],r={queue:0,queuedBits:0},n=i=>{e.push(i)};return t.forEach(i=>QY(i,r,n)),QY(null,r,n),e.join("")}function PMe(t){return Math.round(Date.now()/1e3)+t}function IMe(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){const e=Math.random()*16|0;return(t=="x"?e:e&3|8).toString(16)})}const Zc=()=>typeof window<"u"&&typeof document<"u",Cv={tested:!1,writable:!1},Hce=()=>{if(!Zc())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Cv.tested)return Cv.writable;const t=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(t,t),globalThis.localStorage.removeItem(t),Cv.tested=!0,Cv.writable=!0}catch{Cv.tested=!0,Cv.writable=!1}return Cv.writable};function MMe(t){const e={},r=new URL(t);if(r.hash&&r.hash[0]==="#")try{new URLSearchParams(r.hash.substring(1)).forEach((i,o)=>{e[o]=i})}catch{}return r.searchParams.forEach((n,i)=>{e[i]=n}),e}const Wce=t=>{let e;return t?e=t:typeof fetch>"u"?e=(...r)=>Lj(async()=>{const{default:n}=await Promise.resolve().then(()=>s0);return{default:n}},void 0).then(({default:n})=>n(...r)):e=fetch,(...r)=>e(...r)},OMe=t=>typeof t=="object"&&t!==null&&"status"in t&&"ok"in t&&"json"in t&&typeof t.json=="function",_w=async(t,e,r)=>{await t.setItem(e,JSON.stringify(r))},kv=async(t,e)=>{const r=await t.getItem(e);if(!r)return null;try{return JSON.parse(r)}catch{return r}},Zg=async(t,e)=>{await t.removeItem(e)};class pD{constructor(){this.promise=new pD.promiseConstructor((e,r)=>{this.resolve=e,this.reject=r})}}pD.promiseConstructor=Promise;function XF(t){const e=t.split(".");if(e.length!==3)throw new p$("Invalid JWT structure");for(let n=0;n{setTimeout(()=>e(null),t)})}function DMe(t,e){return new Promise((n,i)=>{(async()=>{for(let o=0;o<1/0;o++)try{const c=await t(o);if(!e(o,null,c)){n(c);return}}catch(c){if(!e(o,c)){i(c);return}}})()})}function LMe(t){return("0"+t.toString(16)).substr(-2)}function FMe(){const e=new Uint32Array(56);if(typeof crypto>"u"){const r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",n=r.length;let i="";for(let o=0;o<56;o++)i+=r.charAt(Math.floor(Math.random()*n));return i}return crypto.getRandomValues(e),Array.from(e,LMe).join("")}async function zMe(t){const r=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",r),i=new Uint8Array(n);return Array.from(i).map(o=>String.fromCharCode(o)).join("")}async function BMe(t){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),t;const r=await zMe(t);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function rw(t,e,r=!1){const n=FMe();let i=n;r&&(i+="/PASSWORD_RECOVERY"),await _w(t,`${e}-code-verifier`,i);const o=await BMe(n);return[o,n===o?"plain":"s256"]}const $Me=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function UMe(t){const e=t.headers.get(h$);if(!e||!e.match($Me))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function VMe(t){if(!t)throw new Error("Missing exp claim");const e=Math.floor(Date.now()/1e3);if(t<=e)throw new Error("JWT has expired")}function qMe(t){switch(t){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}const HMe=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function nw(t){if(!HMe.test(t))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function QF(){const t={};return new Proxy(t,{get:(e,r)=>{if(r==="__isUserNotAvailableProxy")return!0;if(typeof r=="symbol"){const n=r.toString();if(n==="Symbol(Symbol.toPrimitive)"||n==="Symbol(Symbol.toStringTag)"||n==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${r}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function WMe(t,e){return new Proxy(t,{get:(r,n,i)=>{if(n==="__isInsecureUserWarningProxy")return!0;if(typeof n=="symbol"){const o=n.toString();if(o==="Symbol(Symbol.toPrimitive)"||o==="Symbol(Symbol.toStringTag)"||o==="Symbol(util.inspect.custom)"||o==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(r,n,i)}return!e.value&&typeof n=="string"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),e.value=!0),Reflect.get(r,n,i)}})}function eX(t){return JSON.parse(JSON.stringify(t))}const Ov=t=>t.msg||t.message||t.error_description||t.error||JSON.stringify(t),GMe=[502,503,504];async function tX(t){var e;if(!OMe(t))throw new f$(Ov(t),0);if(GMe.includes(t.status))throw new f$(Ov(t),t.status);let r;try{r=await t.json()}catch(o){throw new Bv(Ov(o),o)}let n;const i=UMe(t);if(i&&i.getTime()>=Vce["2024-01-01"].timestamp&&typeof r=="object"&&r&&typeof r.code=="string"?n=r.code:typeof r=="object"&&r&&typeof r.error_code=="string"&&(n=r.error_code),n){if(n==="weak_password")throw new YY(Ov(r),t.status,((e=r.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(n==="session_not_found")throw new Xh}else if(typeof r=="object"&&r&&typeof r.weak_password=="object"&&r.weak_password&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.reasons.reduce((o,c)=>o&&typeof c=="string",!0))throw new YY(Ov(r),t.status,r.weak_password.reasons);throw new wMe(Ov(r),t.status||500,n)}const KMe=(t,e,r,n)=>{const i={method:t,headers:(e==null?void 0:e.headers)||{}};return t==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e==null?void 0:e.headers),i.body=JSON.stringify(n),Object.assign(Object.assign({},i),r))};async function Ws(t,e,r,n){var i;const o=Object.assign({},n==null?void 0:n.headers);o[h$]||(o[h$]=Vce["2024-01-01"].name),n!=null&&n.jwt&&(o.Authorization=`Bearer ${n.jwt}`);const c=(i=n==null?void 0:n.query)!==null&&i!==void 0?i:{};n!=null&&n.redirectTo&&(c.redirect_to=n.redirectTo);const a=Object.keys(c).length?"?"+new URLSearchParams(c).toString():"",m=await ZMe(t,e,r+a,{headers:o,noResolveJson:n==null?void 0:n.noResolveJson},{},n==null?void 0:n.body);return n!=null&&n.xform?n==null?void 0:n.xform(m):{data:Object.assign({},m),error:null}}async function ZMe(t,e,r,n,i,o){const c=KMe(e,n,i,o);let a;try{a=await t(r,Object.assign({},c))}catch(m){throw console.error(m),new f$(Ov(m),0)}if(a.ok||await tX(a),n!=null&&n.noResolveJson)return a;try{return await a.json()}catch(m){await tX(m)}}function Qh(t){var e;let r=null;QMe(t)&&(r=Object.assign({},t),t.expires_at||(r.expires_at=PMe(t.expires_in)));const n=(e=t.user)!==null&&e!==void 0?e:t;return{data:{session:r,user:n},error:null}}function rX(t){const e=Qh(t);return!e.error&&t.weak_password&&typeof t.weak_password=="object"&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.message&&typeof t.weak_password.message=="string"&&t.weak_password.reasons.reduce((r,n)=>r&&typeof n=="string",!0)&&(e.data.weak_password=t.weak_password),e}function py(t){var e;return{data:{user:(e=t.user)!==null&&e!==void 0?e:t},error:null}}function YMe(t){return{data:t,error:null}}function XMe(t){const{action_link:e,email_otp:r,hashed_token:n,redirect_to:i,verification_type:o}=t,c=vx(t,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:r,hashed_token:n,redirect_to:i,verification_type:o},m=Object.assign({},c);return{data:{properties:a,user:m},error:null}}function nX(t){return t}function QMe(t){return t.access_token&&t.refresh_token&&t.expires_in}const JF=["global","local","others"];class JMe{constructor({url:e="",headers:r={},fetch:n}){this.url=e,this.headers=r,this.fetch=Wce(n),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)}}async signOut(e,r=JF[0]){if(JF.indexOf(r)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${JF.join(", ")}`);try{return await Ws(this.fetch,"POST",`${this.url}/logout?scope=${r}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(n){if(gs(n))return{data:null,error:n};throw n}}async inviteUserByEmail(e,r={}){try{return await Ws(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:r.data},headers:this.headers,redirectTo:r.redirectTo,xform:py})}catch(n){if(gs(n))return{data:{user:null},error:n};throw n}}async generateLink(e){try{const{options:r}=e,n=vx(e,["options"]),i=Object.assign(Object.assign({},n),r);return"newEmail"in n&&(i.new_email=n==null?void 0:n.newEmail,delete i.newEmail),await Ws(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:i,headers:this.headers,xform:XMe,redirectTo:r==null?void 0:r.redirectTo})}catch(r){if(gs(r))return{data:{properties:null,user:null},error:r};throw r}}async createUser(e){try{return await Ws(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:py})}catch(r){if(gs(r))return{data:{user:null},error:r};throw r}}async listUsers(e){var r,n,i,o,c,a,m;try{const g={nextPage:null,lastPage:0,total:0},_=await Ws(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(n=(r=e==null?void 0:e.page)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:"",per_page:(o=(i=e==null?void 0:e.perPage)===null||i===void 0?void 0:i.toString())!==null&&o!==void 0?o:""},xform:nX});if(_.error)throw _.error;const j=await _.json(),N=(c=_.headers.get("x-total-count"))!==null&&c!==void 0?c:0,C=(m=(a=_.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&m!==void 0?m:[];return C.length>0&&(C.forEach(P=>{const A=parseInt(P.split(";")[0].split("=")[1].substring(0,1)),I=JSON.parse(P.split(";")[1].split("=")[1]);g[`${I}Page`]=A}),g.total=parseInt(N)),{data:Object.assign(Object.assign({},j),g),error:null}}catch(g){if(gs(g))return{data:{users:[]},error:g};throw g}}async getUserById(e){nw(e);try{return await Ws(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:py})}catch(r){if(gs(r))return{data:{user:null},error:r};throw r}}async updateUserById(e,r){nw(e);try{return await Ws(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:r,headers:this.headers,xform:py})}catch(n){if(gs(n))return{data:{user:null},error:n};throw n}}async deleteUser(e,r=!1){nw(e);try{return await Ws(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:r},xform:py})}catch(n){if(gs(n))return{data:{user:null},error:n};throw n}}async _listFactors(e){nw(e.userId);try{const{data:r,error:n}=await Ws(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:i=>({data:{factors:i},error:null})});return{data:r,error:n}}catch(r){if(gs(r))return{data:null,error:r};throw r}}async _deleteFactor(e){nw(e.userId),nw(e.id);try{return{data:await Ws(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(r){if(gs(r))return{data:null,error:r};throw r}}async _listOAuthClients(e){var r,n,i,o,c,a,m;try{const g={nextPage:null,lastPage:0,total:0},_=await Ws(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(n=(r=e==null?void 0:e.page)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:"",per_page:(o=(i=e==null?void 0:e.perPage)===null||i===void 0?void 0:i.toString())!==null&&o!==void 0?o:""},xform:nX});if(_.error)throw _.error;const j=await _.json(),N=(c=_.headers.get("x-total-count"))!==null&&c!==void 0?c:0,C=(m=(a=_.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&m!==void 0?m:[];return C.length>0&&(C.forEach(P=>{const A=parseInt(P.split(";")[0].split("=")[1].substring(0,1)),I=JSON.parse(P.split(";")[1].split("=")[1]);g[`${I}Page`]=A}),g.total=parseInt(N)),{data:Object.assign(Object.assign({},j),g),error:null}}catch(g){if(gs(g))return{data:{clients:[]},error:g};throw g}}async _createOAuthClient(e){try{return await Ws(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(gs(r))return{data:null,error:r};throw r}}async _getOAuthClient(e){try{return await Ws(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(gs(r))return{data:null,error:r};throw r}}async _updateOAuthClient(e,r){try{return await Ws(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:r,headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(gs(n))return{data:null,error:n};throw n}}async _deleteOAuthClient(e){try{return await Ws(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(gs(r))return{data:null,error:r};throw r}}async _regenerateOAuthClientSecret(e){try{return await Ws(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(gs(r))return{data:null,error:r};throw r}}}function sX(t={}){return{getItem:e=>t[e]||null,setItem:(e,r)=>{t[e]=r},removeItem:e=>{delete t[e]}}}const sw={debug:!!(globalThis&&Hce()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class Gce extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class eOe extends Gce{}async function tOe(t,e,r){sw.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",t,e);const n=new globalThis.AbortController;return e>0&&setTimeout(()=>{n.abort(),sw.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",t)},e),await Promise.resolve().then(()=>globalThis.navigator.locks.request(t,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:n.signal},async i=>{if(i){sw.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",t,i.name);try{return await r()}finally{sw.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",t,i.name)}}else{if(e===0)throw sw.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",t),new eOe(`Acquiring an exclusive Navigator LockManager lock "${t}" immediately failed`);if(sw.debug)try{const o=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(o,null," "))}catch(o){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",o)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await r()}}))}function rOe(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}function Kce(t){if(!/^0x[a-fA-F0-9]{40}$/.test(t))throw new Error(`@supabase/auth-js: Address "${t}" is invalid.`);return t.toLowerCase()}function nOe(t){return parseInt(t,16)}function sOe(t){const e=new TextEncoder().encode(t);return"0x"+Array.from(e,n=>n.toString(16).padStart(2,"0")).join("")}function iOe(t){var e;const{chainId:r,domain:n,expirationTime:i,issuedAt:o=new Date,nonce:c,notBefore:a,requestId:m,resources:g,scheme:_,uri:j,version:N}=t;{if(!Number.isInteger(r))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${r}`);if(!n)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(c&&c.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${c}`);if(!j)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(N!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${N}`);if(!((e=t.statement)===null||e===void 0)&&e.includes(` `))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${t.statement}`)}const C=Kce(t.address),P=_?`${_}://${n}`:n,A=t.statement?`${t.statement} `:"",I=`${P} wants you to sign in with your Ethereum account: ${C} ${A}`;let O=`URI: ${j} Version: ${N} Chain ID: ${r}${c?` Nonce: ${c}`:""} Issued At: ${o.toISOString()}`;if(i&&(O+=` Expiration Time: ${i.toISOString()}`),a&&(O+=` Not Before: ${a.toISOString()}`),m&&(O+=` Request ID: ${m}`),g){let R=` Resources:`;for(const z of g){if(!z||typeof z!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${z}`);R+=` - ${z}`}O+=R}return`${I} ${O}`}class ll extends Error{constructor({message:e,code:r,cause:n,name:i}){var o;super(e,{cause:n}),this.__isWebAuthnError=!0,this.name=(o=i??(n instanceof Error?n.name:void 0))!==null&&o!==void 0?o:"Unknown Error",this.code=r}}class kM extends ll{constructor(e,r){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r,message:e}),this.name="WebAuthnUnknownError",this.originalError=r}}function aOe({error:t,options:e}){var r,n,i;const{publicKey:o}=e;if(!o)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new ll({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else if(t.name==="ConstraintError"){if(((r=o.authenticatorSelection)===null||r===void 0?void 0:r.requireResidentKey)===!0)return new ll({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:t});if(e.mediation==="conditional"&&((n=o.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new ll({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:t});if(((i=o.authenticatorSelection)===null||i===void 0?void 0:i.userVerification)==="required")return new ll({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:t})}else{if(t.name==="InvalidStateError")return new ll({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if(t.name==="NotAllowedError")return new ll({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="NotSupportedError")return o.pubKeyCredParams.filter(a=>a.type==="public-key").length===0?new ll({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new ll({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:t});if(t.name==="SecurityError"){const c=window.location.hostname;if(Zce(c)){if(o.rp.id!==c)return new ll({message:`The RP ID "${o.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new ll({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="TypeError"){if(o.user.id.byteLength<1||o.user.id.byteLength>64)return new ll({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:t})}else if(t.name==="UnknownError")return new ll({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new ll({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}function oOe({error:t,options:e}){const{publicKey:r}=e;if(!r)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new ll({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else{if(t.name==="NotAllowedError")return new ll({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="SecurityError"){const n=window.location.hostname;if(Zce(n)){if(r.rpId!==n)return new ll({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new ll({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="UnknownError")return new ll({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new ll({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}class lOe{createNewAbortSignal(){if(this.controller){const r=new Error("Cancelling existing WebAuthn API call for new one");r.name="AbortError",this.controller.abort(r)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}}const cOe=new lOe;function uOe(t){if(!t)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(t);const{challenge:e,user:r,excludeCredentials:n}=t,i=vx(t,["challenge","user","excludeCredentials"]),o=s1(e).buffer,c=Object.assign(Object.assign({},r),{id:s1(r.id).buffer}),a=Object.assign(Object.assign({},i),{challenge:o,user:c});if(n&&n.length>0){a.excludeCredentials=new Array(n.length);for(let m=0;m0){o.allowCredentials=new Array(r.length);for(let c=0;ci!==null&&typeof i=="object"&&!Array.isArray(i),r=i=>i instanceof ArrayBuffer||ArrayBuffer.isView(i),n={};for(const i of t)if(i)for(const o in i){const c=i[o];if(c!==void 0)if(Array.isArray(c))n[o]=c;else if(r(c))n[o]=c;else if(e(c)){const a=n[o];e(a)?n[o]=TM(a,c):n[o]=TM(c)}else n[o]=c}return n}function xOe(t,e){return TM(gOe,t,e||{})}function vOe(t,e){return TM(yOe,t,e||{})}class _Oe{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:r,friendlyName:n,signal:i},o){try{const{data:c,error:a}=await this.client.mfa.challenge({factorId:e,webauthn:r});if(!c)return{data:null,error:a};const m=i??cOe.createNewAbortSignal();if(c.webauthn.type==="create"){const{user:g}=c.webauthn.credential_options.publicKey;g.name||(g.name=`${g.id}:${n}`),g.displayName||(g.displayName=g.name)}switch(c.webauthn.type){case"create":{const g=xOe(c.webauthn.credential_options.publicKey,o==null?void 0:o.create),{data:_,error:j}=await pOe({publicKey:g,signal:m});return _?{data:{factorId:e,challengeId:c.id,webauthn:{type:c.webauthn.type,credential_response:_}},error:null}:{data:null,error:j}}case"request":{const g=vOe(c.webauthn.credential_options.publicKey,o==null?void 0:o.request),{data:_,error:j}=await mOe(Object.assign(Object.assign({},c.webauthn.credential_options),{publicKey:g,signal:m}));return _?{data:{factorId:e,challengeId:c.id,webauthn:{type:c.webauthn.type,credential_response:_}},error:null}:{data:null,error:j}}}}catch(c){return gs(c)?{data:null,error:c}:{data:null,error:new Bv("Unexpected error in challenge",c)}}}async _verify({challengeId:e,factorId:r,webauthn:n}){return this.client.mfa.verify({factorId:r,challengeId:e,webauthn:n})}async _authenticate({factorId:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:n=typeof window<"u"?[window.location.origin]:void 0,signal:i}},o){if(!r)return{data:null,error:new rk("rpId is required for WebAuthn authentication")};try{if(!iX())return{data:null,error:new Bv("Browser does not support WebAuthn",null)};const{data:c,error:a}=await this.challenge({factorId:e,webauthn:{rpId:r,rpOrigins:n},signal:i},{request:o});if(!c)return{data:null,error:a};const{webauthn:m}=c;return this._verify({factorId:e,challengeId:c.challengeId,webauthn:{type:m.type,rpId:r,rpOrigins:n,credential_response:m.credential_response}})}catch(c){return gs(c)?{data:null,error:c}:{data:null,error:new Bv("Unexpected error in authenticate",c)}}}async _register({friendlyName:e,rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:n=typeof window<"u"?[window.location.origin]:void 0,signal:i},o){if(!r)return{data:null,error:new rk("rpId is required for WebAuthn registration")};try{if(!iX())return{data:null,error:new Bv("Browser does not support WebAuthn",null)};const{data:c,error:a}=await this._enroll({friendlyName:e});if(!c)return await this.client.mfa.listFactors().then(_=>{var j;return(j=_.data)===null||j===void 0?void 0:j.all.find(N=>N.factor_type==="webauthn"&&N.friendly_name===e&&N.status!=="unverified")}).then(_=>_?this.client.mfa.unenroll({factorId:_==null?void 0:_.id}):void 0),{data:null,error:a};const{data:m,error:g}=await this._challenge({factorId:c.id,friendlyName:c.friendly_name,webauthn:{rpId:r,rpOrigins:n},signal:i},{create:o});return m?this._verify({factorId:c.id,challengeId:m.challengeId,webauthn:{rpId:r,rpOrigins:n,type:m.webauthn.type,credential_response:m.webauthn.credential_response}}):{data:null,error:g}}catch(c){return gs(c)?{data:null,error:c}:{data:null,error:new Bv("Unexpected error in register",c)}}}}rOe();const bOe={url:yMe,storageKey:xMe,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:vMe,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1};async function aX(t,e,r){return await r()}const iw={};class nk{get jwks(){var e,r;return(r=(e=iw[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&r!==void 0?r:{keys:[]}}set jwks(e){iw[this.storageKey]=Object.assign(Object.assign({},iw[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,r;return(r=(e=iw[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&r!==void 0?r:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){iw[this.storageKey]=Object.assign(Object.assign({},iw[this.storageKey]),{cachedAt:e})}constructor(e){var r,n;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=nk.nextInstanceID,nk.nextInstanceID+=1,this.instanceID>0&&Zc()&&console.warn("Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.");const i=Object.assign(Object.assign({},bOe),e);if(this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.persistSession=i.persistSession,this.storageKey=i.storageKey,this.autoRefreshToken=i.autoRefreshToken,this.admin=new JMe({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=Wce(i.fetch),this.lock=i.lock||aX,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,i.lock?this.lock=i.lock:Zc()&&(!((r=globalThis==null?void 0:globalThis.navigator)===null||r===void 0)&&r.locks)?this.lock=tOe:this.lock=aX,this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER),this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this),webauthn:new _Oe(this)},this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this)},this.persistSession?(i.storage?this.storage=i.storage:Hce()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=sX(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=sX(this.memoryStorage)),Zc()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(o){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",o)}(n=this.broadcastChannel)===null||n===void 0||n.addEventListener("message",async o=>{this._debug("received broadcast notification from other tab or client",o),await this._notifyAllSubscribers(o.data.event,o.data.session,!1)})}this.initialize()}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${Uce}) ${new Date().toISOString()}`,...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var e;try{const r=MMe(window.location.href);let n="none";if(this._isImplicitGrantCallback(r)?n="implicit":await this._isPKCECallback(r)&&(n="pkce"),Zc()&&this.detectSessionInUrl&&n!=="none"){const{data:i,error:o}=await this._getSessionFromURL(r,n);if(o){if(this._debug("#_initialize()","error detecting session from URL",o),NMe(o)){const m=(e=o.details)===null||e===void 0?void 0:e.code;if(m==="identity_already_exists"||m==="identity_not_found"||m==="single_identity_not_deletable")return{error:o}}return await this._removeSession(),{error:o}}const{session:c,redirectType:a}=i;return this._debug("#_initialize()","detected session in URL",c,"redirect type",a),await this._saveSession(c),setTimeout(async()=>{a==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",c):await this._notifyAllSubscribers("SIGNED_IN",c)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(r){return gs(r)?{error:r}:{error:new Bv("Unexpected error during initialization",r)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var r,n,i;try{const o=await Ws(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(n=(r=e==null?void 0:e.options)===null||r===void 0?void 0:r.data)!==null&&n!==void 0?n:{},gotrue_meta_security:{captcha_token:(i=e==null?void 0:e.options)===null||i===void 0?void 0:i.captchaToken}},xform:Qh}),{data:c,error:a}=o;if(a||!c)return{data:{user:null,session:null},error:a};const m=c.session,g=c.user;return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",m)),{data:{user:g,session:m},error:null}}catch(o){if(gs(o))return{data:{user:null,session:null},error:o};throw o}}async signUp(e){var r,n,i;try{let o;if("email"in e){const{email:_,password:j,options:N}=e;let C=null,P=null;this.flowType==="pkce"&&([C,P]=await rw(this.storage,this.storageKey)),o=await Ws(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:N==null?void 0:N.emailRedirectTo,body:{email:_,password:j,data:(r=N==null?void 0:N.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:N==null?void 0:N.captchaToken},code_challenge:C,code_challenge_method:P},xform:Qh})}else if("phone"in e){const{phone:_,password:j,options:N}=e;o=await Ws(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:_,password:j,data:(n=N==null?void 0:N.data)!==null&&n!==void 0?n:{},channel:(i=N==null?void 0:N.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:N==null?void 0:N.captchaToken}},xform:Qh})}else throw new NP("You must provide either an email or phone number and a password");const{data:c,error:a}=o;if(a||!c)return{data:{user:null,session:null},error:a};const m=c.session,g=c.user;return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",m)),{data:{user:g,session:m},error:null}}catch(o){if(gs(o))return{data:{user:null,session:null},error:o};throw o}}async signInWithPassword(e){try{let r;if("email"in e){const{email:o,password:c,options:a}=e;r=await Ws(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:o,password:c,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}},xform:rX})}else if("phone"in e){const{phone:o,password:c,options:a}=e;r=await Ws(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:o,password:c,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}},xform:rX})}else throw new NP("You must provide either an email or phone number and a password");const{data:n,error:i}=r;return i?{data:{user:null,session:null},error:i}:!n||!n.session||!n.user?{data:{user:null,session:null},error:new tw}:(n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),{data:Object.assign({user:n.user,session:n.session},n.weak_password?{weakPassword:n.weak_password}:null),error:i})}catch(r){if(gs(r))return{data:{user:null,session:null},error:r};throw r}}async signInWithOAuth(e){var r,n,i,o;return await this._handleProviderSignIn(e.provider,{redirectTo:(r=e.options)===null||r===void 0?void 0:r.redirectTo,scopes:(n=e.options)===null||n===void 0?void 0:n.scopes,queryParams:(i=e.options)===null||i===void 0?void 0:i.queryParams,skipBrowserRedirect:(o=e.options)===null||o===void 0?void 0:o.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){const{chain:r}=e;switch(r){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${r}"`)}}async signInWithEthereum(e){var r,n,i,o,c,a,m,g,_,j,N;let C,P;if("message"in e)C=e.message,P=e.signature;else{const{chain:A,wallet:I,statement:O,options:R}=e;let z;if(Zc())if(typeof I=="object")z=I;else{const X=window;if("ethereum"in X&&typeof X.ethereum=="object"&&"request"in X.ethereum&&typeof X.ethereum.request=="function")z=X.ethereum;else throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}else{if(typeof I!="object"||!(R!=null&&R.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");z=I}const W=new URL((r=R==null?void 0:R.url)!==null&&r!==void 0?r:window.location.href),V=await z.request({method:"eth_requestAccounts"}).then(X=>X).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!V||V.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const K=Kce(V[0]);let Q=(n=R==null?void 0:R.signInWithEthereum)===null||n===void 0?void 0:n.chainId;if(!Q){const X=await z.request({method:"eth_chainId"});Q=nOe(X)}const te={domain:W.host,address:K,statement:O,uri:W.href,version:"1",chainId:Q,nonce:(i=R==null?void 0:R.signInWithEthereum)===null||i===void 0?void 0:i.nonce,issuedAt:(c=(o=R==null?void 0:R.signInWithEthereum)===null||o===void 0?void 0:o.issuedAt)!==null&&c!==void 0?c:new Date,expirationTime:(a=R==null?void 0:R.signInWithEthereum)===null||a===void 0?void 0:a.expirationTime,notBefore:(m=R==null?void 0:R.signInWithEthereum)===null||m===void 0?void 0:m.notBefore,requestId:(g=R==null?void 0:R.signInWithEthereum)===null||g===void 0?void 0:g.requestId,resources:(_=R==null?void 0:R.signInWithEthereum)===null||_===void 0?void 0:_.resources};C=iOe(te),P=await z.request({method:"personal_sign",params:[sOe(C),K]})}try{const{data:A,error:I}=await Ws(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:C,signature:P},!((j=e.options)===null||j===void 0)&&j.captchaToken?{gotrue_meta_security:{captcha_token:(N=e.options)===null||N===void 0?void 0:N.captchaToken}}:null),xform:Qh});if(I)throw I;return!A||!A.session||!A.user?{data:{user:null,session:null},error:new tw}:(A.session&&(await this._saveSession(A.session),await this._notifyAllSubscribers("SIGNED_IN",A.session)),{data:Object.assign({},A),error:I})}catch(A){if(gs(A))return{data:{user:null,session:null},error:A};throw A}}async signInWithSolana(e){var r,n,i,o,c,a,m,g,_,j,N,C;let P,A;if("message"in e)P=e.message,A=e.signature;else{const{chain:I,wallet:O,statement:R,options:z}=e;let W;if(Zc())if(typeof O=="object")W=O;else{const K=window;if("solana"in K&&typeof K.solana=="object"&&("signIn"in K.solana&&typeof K.solana.signIn=="function"||"signMessage"in K.solana&&typeof K.solana.signMessage=="function"))W=K.solana;else throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}else{if(typeof O!="object"||!(z!=null&&z.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");W=O}const V=new URL((r=z==null?void 0:z.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in W&&W.signIn){const K=await W.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},z==null?void 0:z.signInWithSolana),{version:"1",domain:V.host,uri:V.href}),R?{statement:R}:null));let Q;if(Array.isArray(K)&&K[0]&&typeof K[0]=="object")Q=K[0];else if(K&&typeof K=="object"&&"signedMessage"in K&&"signature"in K)Q=K;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in Q&&"signature"in Q&&(typeof Q.signedMessage=="string"||Q.signedMessage instanceof Uint8Array)&&Q.signature instanceof Uint8Array)P=typeof Q.signedMessage=="string"?Q.signedMessage:new TextDecoder().decode(Q.signedMessage),A=Q.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in W)||typeof W.signMessage!="function"||!("publicKey"in W)||typeof W!="object"||!W.publicKey||!("toBase58"in W.publicKey)||typeof W.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");P=[`${V.host} wants you to sign in with your Solana account:`,W.publicKey.toBase58(),...R?["",R,""]:[""],"Version: 1",`URI: ${V.href}`,`Issued At: ${(i=(n=z==null?void 0:z.signInWithSolana)===null||n===void 0?void 0:n.issuedAt)!==null&&i!==void 0?i:new Date().toISOString()}`,...!((o=z==null?void 0:z.signInWithSolana)===null||o===void 0)&&o.notBefore?[`Not Before: ${z.signInWithSolana.notBefore}`]:[],...!((c=z==null?void 0:z.signInWithSolana)===null||c===void 0)&&c.expirationTime?[`Expiration Time: ${z.signInWithSolana.expirationTime}`]:[],...!((a=z==null?void 0:z.signInWithSolana)===null||a===void 0)&&a.chainId?[`Chain ID: ${z.signInWithSolana.chainId}`]:[],...!((m=z==null?void 0:z.signInWithSolana)===null||m===void 0)&&m.nonce?[`Nonce: ${z.signInWithSolana.nonce}`]:[],...!((g=z==null?void 0:z.signInWithSolana)===null||g===void 0)&&g.requestId?[`Request ID: ${z.signInWithSolana.requestId}`]:[],...!((j=(_=z==null?void 0:z.signInWithSolana)===null||_===void 0?void 0:_.resources)===null||j===void 0)&&j.length?["Resources",...z.signInWithSolana.resources.map(Q=>`- ${Q}`)]:[]].join(` `);const K=await W.signMessage(new TextEncoder().encode(P),"utf8");if(!K||!(K instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");A=K}}try{const{data:I,error:O}=await Ws(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:P,signature:Gv(A)},!((N=e.options)===null||N===void 0)&&N.captchaToken?{gotrue_meta_security:{captcha_token:(C=e.options)===null||C===void 0?void 0:C.captchaToken}}:null),xform:Qh});if(O)throw O;return!I||!I.session||!I.user?{data:{user:null,session:null},error:new tw}:(I.session&&(await this._saveSession(I.session),await this._notifyAllSubscribers("SIGNED_IN",I.session)),{data:Object.assign({},I),error:O})}catch(I){if(gs(I))return{data:{user:null,session:null},error:I};throw I}}async _exchangeCodeForSession(e){const r=await kv(this.storage,`${this.storageKey}-code-verifier`),[n,i]=(r??"").split("/");try{const{data:o,error:c}=await Ws(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:n},xform:Qh});if(await Zg(this.storage,`${this.storageKey}-code-verifier`),c)throw c;return!o||!o.session||!o.user?{data:{user:null,session:null,redirectType:null},error:new tw}:(o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",o.session)),{data:Object.assign(Object.assign({},o),{redirectType:i??null}),error:c})}catch(o){if(gs(o))return{data:{user:null,session:null,redirectType:null},error:o};throw o}}async signInWithIdToken(e){try{const{options:r,provider:n,token:i,access_token:o,nonce:c}=e,a=await Ws(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:n,id_token:i,access_token:o,nonce:c,gotrue_meta_security:{captcha_token:r==null?void 0:r.captchaToken}},xform:Qh}),{data:m,error:g}=a;return g?{data:{user:null,session:null},error:g}:!m||!m.session||!m.user?{data:{user:null,session:null},error:new tw}:(m.session&&(await this._saveSession(m.session),await this._notifyAllSubscribers("SIGNED_IN",m.session)),{data:m,error:g})}catch(r){if(gs(r))return{data:{user:null,session:null},error:r};throw r}}async signInWithOtp(e){var r,n,i,o,c;try{if("email"in e){const{email:a,options:m}=e;let g=null,_=null;this.flowType==="pkce"&&([g,_]=await rw(this.storage,this.storageKey));const{error:j}=await Ws(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(r=m==null?void 0:m.data)!==null&&r!==void 0?r:{},create_user:(n=m==null?void 0:m.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:m==null?void 0:m.captchaToken},code_challenge:g,code_challenge_method:_},redirectTo:m==null?void 0:m.emailRedirectTo});return{data:{user:null,session:null},error:j}}if("phone"in e){const{phone:a,options:m}=e,{data:g,error:_}=await Ws(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(i=m==null?void 0:m.data)!==null&&i!==void 0?i:{},create_user:(o=m==null?void 0:m.shouldCreateUser)!==null&&o!==void 0?o:!0,gotrue_meta_security:{captcha_token:m==null?void 0:m.captchaToken},channel:(c=m==null?void 0:m.channel)!==null&&c!==void 0?c:"sms"}});return{data:{user:null,session:null,messageId:g==null?void 0:g.message_id},error:_}}throw new NP("You must provide either an email or phone number.")}catch(a){if(gs(a))return{data:{user:null,session:null},error:a};throw a}}async verifyOtp(e){var r,n;try{let i,o;"options"in e&&(i=(r=e.options)===null||r===void 0?void 0:r.redirectTo,o=(n=e.options)===null||n===void 0?void 0:n.captchaToken);const{data:c,error:a}=await Ws(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:o}}),redirectTo:i,xform:Qh});if(a)throw a;if(!c)throw new Error("An error occurred on token verification.");const m=c.session,g=c.user;return m!=null&&m.access_token&&(await this._saveSession(m),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",m)),{data:{user:g,session:m},error:null}}catch(i){if(gs(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithSSO(e){var r,n,i;try{let o=null,c=null;return this.flowType==="pkce"&&([o,c]=await rw(this.storage,this.storageKey)),await Ws(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(n=(r=e.options)===null||r===void 0?void 0:r.redirectTo)!==null&&n!==void 0?n:void 0}),!((i=e==null?void 0:e.options)===null||i===void 0)&&i.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:o,code_challenge_method:c}),headers:this.headers,xform:YMe})}catch(o){if(gs(o))return{data:null,error:o};throw o}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:r},error:n}=e;if(n)throw n;if(!r)throw new Xh;const{error:i}=await Ws(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return{data:{user:null,session:null},error:i}})}catch(e){if(gs(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{const r=`${this.url}/resend`;if("email"in e){const{email:n,type:i,options:o}=e,{error:c}=await Ws(this.fetch,"POST",r,{headers:this.headers,body:{email:n,type:i,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}},redirectTo:o==null?void 0:o.emailRedirectTo});return{data:{user:null,session:null},error:c}}else if("phone"in e){const{phone:n,type:i,options:o}=e,{data:c,error:a}=await Ws(this.fetch,"POST",r,{headers:this.headers,body:{phone:n,type:i,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}}});return{data:{user:null,session:null,messageId:c==null?void 0:c.message_id},error:a}}throw new NP("You must provide either an email or phone number and a type")}catch(r){if(gs(r))return{data:{user:null,session:null},error:r};throw r}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async r=>r))}async _acquireLock(e,r){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const n=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),i=(async()=>(await n,await r()))();return this.pendingInLock.push((async()=>{try{await i}catch{}})()),i}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const n=r();for(this.pendingInLock.push((async()=>{try{await n}catch{}})()),await n;this.pendingInLock.length;){const i=[...this.pendingInLock];await Promise.all(i),this.pendingInLock.splice(0,i.length)}return await n}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{const r=await this.__loadSession();return await e(r)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null;const r=await kv(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",r),r!==null&&(this._isValidSession(r)?e=r:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};const n=e.expires_at?e.expires_at*1e3-Date.now()await this._getUser()))}async _getUser(e){try{return e?await Ws(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:py}):await this._useSession(async r=>{var n,i,o;const{data:c,error:a}=r;if(a)throw a;return!(!((n=c.session)===null||n===void 0)&&n.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new Xh}:await Ws(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(o=(i=c.session)===null||i===void 0?void 0:i.access_token)!==null&&o!==void 0?o:void 0,xform:py})})}catch(r){if(gs(r))return SMe(r)&&(await this._removeSession(),await Zg(this.storage,`${this.storageKey}-code-verifier`)),{data:{user:null},error:r};throw r}}async updateUser(e,r={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,r))}async _updateUser(e,r={}){try{return await this._useSession(async n=>{const{data:i,error:o}=n;if(o)throw o;if(!i.session)throw new Xh;const c=i.session;let a=null,m=null;this.flowType==="pkce"&&e.email!=null&&([a,m]=await rw(this.storage,this.storageKey));const{data:g,error:_}=await Ws(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:r==null?void 0:r.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:m}),jwt:c.access_token,xform:py});if(_)throw _;return c.user=g.user,await this._saveSession(c),await this._notifyAllSubscribers("USER_UPDATED",c),{data:{user:c.user},error:null}})}catch(n){if(gs(n))return{data:{user:null},error:n};throw n}}async setSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new Xh;const r=Date.now()/1e3;let n=r,i=!0,o=null;const{payload:c}=XF(e.access_token);if(c.exp&&(n=c.exp,i=n<=r),i){const{data:a,error:m}=await this._callRefreshToken(e.refresh_token);if(m)return{data:{user:null,session:null},error:m};if(!a)return{data:{user:null,session:null},error:null};o=a}else{const{data:a,error:m}=await this._getUser(e.access_token);if(m)throw m;o={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:n-r,expires_at:n},await this._saveSession(o),await this._notifyAllSubscribers("SIGNED_IN",o)}return{data:{user:o.user,session:o},error:null}}catch(r){if(gs(r))return{data:{session:null,user:null},error:r};throw r}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async r=>{var n;if(!e){const{data:c,error:a}=r;if(a)throw a;e=(n=c.session)!==null&&n!==void 0?n:void 0}if(!(e!=null&&e.refresh_token))throw new Xh;const{data:i,error:o}=await this._callRefreshToken(e.refresh_token);return o?{data:{user:null,session:null},error:o}:i?{data:{user:i.user,session:i},error:null}:{data:{user:null,session:null},error:null}})}catch(r){if(gs(r))return{data:{user:null,session:null},error:r};throw r}}async _getSessionFromURL(e,r){try{if(!Zc())throw new CP("No browser detected.");if(e.error||e.error_description||e.error_code)throw new CP(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(r){case"implicit":if(this.flowType==="pkce")throw new ZY("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new CP("Not a valid implicit grant flow url.");break;default:}if(r==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new ZY("No code detected.");const{data:R,error:z}=await this._exchangeCodeForSession(e.code);if(z)throw z;const W=new URL(window.location.href);return W.searchParams.delete("code"),window.history.replaceState(window.history.state,"",W.toString()),{data:{session:R.session,redirectType:null},error:null}}const{provider_token:n,provider_refresh_token:i,access_token:o,refresh_token:c,expires_in:a,expires_at:m,token_type:g}=e;if(!o||!a||!c||!g)throw new CP("No session defined in URL");const _=Math.round(Date.now()/1e3),j=parseInt(a);let N=_+j;m&&(N=parseInt(m));const C=N-_;C*1e3<=vw&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${C}s, should have been closer to ${j}s`);const P=N-j;_-P>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",P,N,_):_-P<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",P,N,_);const{data:A,error:I}=await this._getUser(o);if(I)throw I;const O={provider_token:n,provider_refresh_token:i,access_token:o,expires_in:j,expires_at:N,refresh_token:c,token_type:g,user:A.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:O,redirectType:e.type},error:null}}catch(n){if(gs(n))return{data:{session:null,redirectType:null},error:n};throw n}}_isImplicitGrantCallback(e){return!!(e.access_token||e.error_description)}async _isPKCECallback(e){const r=await kv(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&r)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async r=>{var n;const{data:i,error:o}=r;if(o)return{error:o};const c=(n=i.session)===null||n===void 0?void 0:n.access_token;if(c){const{error:a}=await this.admin.signOut(c,e);if(a&&!(jMe(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await Zg(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(e){const r=IMe(),n={id:r,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",r),this.stateChangeEmitters.delete(r)}};return this._debug("#onAuthStateChange()","registered callback with id",r),this.stateChangeEmitters.set(r,n),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(r)})))(),{data:{subscription:n}}}async _emitInitialSession(e){return await this._useSession(async r=>{var n,i;try{const{data:{session:o},error:c}=r;if(c)throw c;await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",o)),this._debug("INITIAL_SESSION","callback id",e,"session",o)}catch(o){await((i=this.stateChangeEmitters.get(e))===null||i===void 0?void 0:i.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",o),console.error(o)}})}async resetPasswordForEmail(e,r={}){let n=null,i=null;this.flowType==="pkce"&&([n,i]=await rw(this.storage,this.storageKey,!0));try{return await Ws(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:n,code_challenge_method:i,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:r.redirectTo})}catch(o){if(gs(o))return{data:null,error:o};throw o}}async getUserIdentities(){var e;try{const{data:r,error:n}=await this.getUser();if(n)throw n;return{data:{identities:(e=r.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(r){if(gs(r))return{data:null,error:r};throw r}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var r;try{const{data:n,error:i}=await this._useSession(async o=>{var c,a,m,g,_;const{data:j,error:N}=o;if(N)throw N;const C=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(c=e.options)===null||c===void 0?void 0:c.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(m=e.options)===null||m===void 0?void 0:m.queryParams,skipBrowserRedirect:!0});return await Ws(this.fetch,"GET",C,{headers:this.headers,jwt:(_=(g=j.session)===null||g===void 0?void 0:g.access_token)!==null&&_!==void 0?_:void 0})});if(i)throw i;return Zc()&&!(!((r=e.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(n==null?void 0:n.url),{data:{provider:e.provider,url:n==null?void 0:n.url},error:null}}catch(n){if(gs(n))return{data:{provider:e.provider,url:null},error:n};throw n}}async linkIdentityIdToken(e){return await this._useSession(async r=>{var n;try{const{error:i,data:{session:o}}=r;if(i)throw i;const{options:c,provider:a,token:m,access_token:g,nonce:_}=e,j=await Ws(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(n=o==null?void 0:o.access_token)!==null&&n!==void 0?n:void 0,body:{provider:a,id_token:m,access_token:g,nonce:_,link_identity:!0,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken}},xform:Qh}),{data:N,error:C}=j;return C?{data:{user:null,session:null},error:C}:!N||!N.session||!N.user?{data:{user:null,session:null},error:new tw}:(N.session&&(await this._saveSession(N.session),await this._notifyAllSubscribers("USER_UPDATED",N.session)),{data:N,error:C})}catch(i){if(gs(i))return{data:{user:null,session:null},error:i};throw i}})}async unlinkIdentity(e){try{return await this._useSession(async r=>{var n,i;const{data:o,error:c}=r;if(c)throw c;return await Ws(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(i=(n=o.session)===null||n===void 0?void 0:n.access_token)!==null&&i!==void 0?i:void 0})})}catch(r){if(gs(r))return{data:null,error:r};throw r}}async _refreshAccessToken(e){const r=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{const n=Date.now();return await DMe(async i=>(i>0&&await RMe(200*Math.pow(2,i-1)),this._debug(r,"refreshing attempt",i),await Ws(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:Qh})),(i,o)=>{const c=200*Math.pow(2,i);return o&&YF(o)&&Date.now()+c-n{try{await a.callback(e,r)}catch(m){o.push(m)}});if(await Promise.all(c),o.length>0){for(let a=0;athis._autoRefreshTokenTick(),vw);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{const e=Date.now();try{return await this._useSession(async r=>{const{data:{session:n}}=r;if(!n||!n.refresh_token||!n.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const i=Math.floor((n.expires_at*1e3-e)/vw);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${vw}ms, refresh threshold is ${d$} ticks`),i<=d$&&await this._callRefreshToken(n.refresh_token)})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof Gce)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Zc()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const r=`#_onVisibilityChanged(${e})`;this._debug(r,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(r,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,r,n){const i=[`provider=${encodeURIComponent(r)}`];if(n!=null&&n.redirectTo&&i.push(`redirect_to=${encodeURIComponent(n.redirectTo)}`),n!=null&&n.scopes&&i.push(`scopes=${encodeURIComponent(n.scopes)}`),this.flowType==="pkce"){const[o,c]=await rw(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(o)}`,code_challenge_method:`${encodeURIComponent(c)}`});i.push(a.toString())}if(n!=null&&n.queryParams){const o=new URLSearchParams(n.queryParams);i.push(o.toString())}return n!=null&&n.skipBrowserRedirect&&i.push(`skip_http_redirect=${n.skipBrowserRedirect}`),`${e}?${i.join("&")}`}async _unenroll(e){try{return await this._useSession(async r=>{var n;const{data:i,error:o}=r;return o?{data:null,error:o}:await Ws(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(n=i==null?void 0:i.session)===null||n===void 0?void 0:n.access_token})})}catch(r){if(gs(r))return{data:null,error:r};throw r}}async _enroll(e){try{return await this._useSession(async r=>{var n,i;const{data:o,error:c}=r;if(c)return{data:null,error:c};const a=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:m,error:g}=await Ws(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:(n=o==null?void 0:o.session)===null||n===void 0?void 0:n.access_token});return g?{data:null,error:g}:(e.factorType==="totp"&&m.type==="totp"&&(!((i=m==null?void 0:m.totp)===null||i===void 0)&&i.qr_code)&&(m.totp.qr_code=`data:image/svg+xml;utf-8,${m.totp.qr_code}`),{data:m,error:null})})}catch(r){if(gs(r))return{data:null,error:r};throw r}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async r=>{var n;const{data:i,error:o}=r;if(o)return{data:null,error:o};const c=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?hOe(e.webauthn.credential_response):fOe(e.webauthn.credential_response)})}:{code:e.code}),{data:a,error:m}=await Ws(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:c,headers:this.headers,jwt:(n=i==null?void 0:i.session)===null||n===void 0?void 0:n.access_token});return m?{data:null,error:m}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+a.expires_in},a)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",a),{data:a,error:m})})}catch(r){if(gs(r))return{data:null,error:r};throw r}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async r=>{var n;const{data:i,error:o}=r;if(o)return{data:null,error:o};const c=await Ws(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(n=i==null?void 0:i.session)===null||n===void 0?void 0:n.access_token});if(c.error)return c;const{data:a}=c;if(a.type!=="webauthn")return{data:a,error:null};switch(a.webauthn.type){case"create":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:uOe(a.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:dOe(a.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if(gs(r))return{data:null,error:r};throw r}})}async _challengeAndVerify(e){const{data:r,error:n}=await this._challenge({factorId:e.factorId});return n?{data:null,error:n}:await this._verify({factorId:e.factorId,challengeId:r.id,code:e.code})}async _listFactors(){var e;const{data:{user:r},error:n}=await this.getUser();if(n)return{data:null,error:n};const i={all:[],phone:[],totp:[],webauthn:[]};for(const o of(e=r==null?void 0:r.factors)!==null&&e!==void 0?e:[])i.all.push(o),o.status==="verified"&&i[o.factor_type].push(o);return{data:i,error:null}}async _getAuthenticatorAssuranceLevel(){var e,r;const{data:{session:n},error:i}=await this.getSession();if(i)return{data:null,error:i};if(!n)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:o}=XF(n.access_token);let c=null;o.aal&&(c=o.aal);let a=c;((r=(e=n.user.factors)===null||e===void 0?void 0:e.filter(_=>_.status==="verified"))!==null&&r!==void 0?r:[]).length>0&&(a="aal2");const g=o.amr||[];return{data:{currentLevel:c,nextLevel:a,currentAuthenticationMethods:g},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async r=>{const{data:{session:n},error:i}=r;return i?{data:null,error:i}:n?await Ws(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:n.access_token,xform:o=>({data:o,error:null})}):{data:null,error:new Xh}})}catch(r){if(gs(r))return{data:null,error:r};throw r}}async _approveAuthorization(e,r){try{return await this._useSession(async n=>{const{data:{session:i},error:o}=n;if(o)return{data:null,error:o};if(!i)return{data:null,error:new Xh};const c=await Ws(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:i.access_token,body:{action:"approve"},xform:a=>({data:a,error:null})});return c.data&&c.data.redirect_url&&Zc()&&!(r!=null&&r.skipBrowserRedirect)&&window.location.assign(c.data.redirect_url),c})}catch(n){if(gs(n))return{data:null,error:n};throw n}}async _denyAuthorization(e,r){try{return await this._useSession(async n=>{const{data:{session:i},error:o}=n;if(o)return{data:null,error:o};if(!i)return{data:null,error:new Xh};const c=await Ws(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:i.access_token,body:{action:"deny"},xform:a=>({data:a,error:null})});return c.data&&c.data.redirect_url&&Zc()&&!(r!=null&&r.skipBrowserRedirect)&&window.location.assign(c.data.redirect_url),c})}catch(n){if(gs(n))return{data:null,error:n};throw n}}async fetchJwk(e,r={keys:[]}){let n=r.keys.find(a=>a.kid===e);if(n)return n;const i=Date.now();if(n=this.jwks.keys.find(a=>a.kid===e),n&&this.jwks_cached_at+bMe>i)return n;const{data:o,error:c}=await Ws(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(c)throw c;return!o.keys||o.keys.length===0||(this.jwks=o,this.jwks_cached_at=i,n=o.keys.find(a=>a.kid===e),!n)?null:n}async getClaims(e,r={}){try{let n=e;if(!n){const{data:C,error:P}=await this.getSession();if(P||!C.session)return{data:null,error:P};n=C.session.access_token}const{header:i,payload:o,signature:c,raw:{header:a,payload:m}}=XF(n);r!=null&&r.allowExpired||VMe(o.exp);const g=!i.alg||i.alg.startsWith("HS")||!i.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(i.kid,r!=null&&r.keys?{keys:r.keys}:r==null?void 0:r.jwks);if(!g){const{error:C}=await this.getUser(n);if(C)throw C;return{data:{claims:o,header:i,signature:c},error:null}}const _=qMe(i.alg),j=await crypto.subtle.importKey("jwk",g,_,!0,["verify"]);if(!await crypto.subtle.verify(_,j,c,AMe(`${a}.${m}`)))throw new p$("Invalid JWT signature");return{data:{claims:o,header:i,signature:c},error:null}}catch(n){if(gs(n))return{data:null,error:n};throw n}}}nk.nextInstanceID=0;const wOe=nk;class jOe extends wOe{constructor(e){super(e)}}class SOe{constructor(e,r,n){var i,o,c;this.supabaseUrl=e,this.supabaseKey=r;const a=gMe(e);if(!r)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",a),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",a),this.storageUrl=new URL("storage/v1",a),this.functionsUrl=new URL("functions/v1",a);const m=`sb-${a.hostname.split(".")[0]}-auth-token`,g={db:lMe,realtime:uMe,auth:Object.assign(Object.assign({},cMe),{storageKey:m}),global:oMe},_=mMe(n??{},g);this.storageKey=(i=_.auth.storageKey)!==null&&i!==void 0?i:"",this.headers=(o=_.global.headers)!==null&&o!==void 0?o:{},_.accessToken?(this.accessToken=_.accessToken,this.auth=new Proxy({},{get:(j,N)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(N)} is not possible`)}})):this.auth=this._initSupabaseAuthClient((c=_.auth)!==null&&c!==void 0?c:{},this.headers,_.global.fetch),this.fetch=fMe(r,this._getAccessToken.bind(this),_.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers,accessToken:this._getAccessToken.bind(this)},_.realtime)),this.rest=new yIe(new URL("rest/v1",a).href,{headers:this.headers,schema:_.db.schema,fetch:this.fetch}),this.storage=new sMe(this.storageUrl.href,this.headers,this.fetch,n==null?void 0:n.storage),_.accessToken||this._listenForAuthEvents()}get functions(){return new cIe(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,r={},n={head:!1,get:!1,count:void 0}){return this.rest.rpc(e,r,n)}channel(e,r={config:{}}){return this.realtime.channel(e,r)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var e,r;if(this.accessToken)return await this.accessToken();const{data:n}=await this.auth.getSession();return(r=(e=n.session)===null||e===void 0?void 0:e.access_token)!==null&&r!==void 0?r:this.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:r,detectSessionInUrl:n,storage:i,userStorage:o,storageKey:c,flowType:a,lock:m,debug:g},_,j){const N={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new jOe({url:this.authUrl.href,headers:Object.assign(Object.assign({},N),_),storageKey:c,autoRefreshToken:e,persistSession:r,detectSessionInUrl:n,storage:i,userStorage:o,flowType:a,lock:m,debug:g,fetch:j,hasCustomAuthorizationHeader:Object.keys(this.headers).some(C=>C.toLowerCase()==="authorization")})}_initRealtimeClient(e){return new OIe(this.realtimeUrl.href,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e==null?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((r,n)=>{this._handleTokenChanged(r,"CLIENT",n==null?void 0:n.access_token)})}_handleTokenChanged(e,r,n){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==n?(this.changedAccessToken=n,this.realtime.setAuth(n)):e==="SIGNED_OUT"&&(this.realtime.setAuth(),r=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}}const NOe=(t,e,r)=>new SOe(t,e,r);function COe(){if(typeof window<"u"||typeof process>"u")return!1;const t=process.version;if(t==null)return!1;const e=t.match(/^v(\d+)\./);return e?parseInt(e[1],10)<=18:!1}COe()&&console.warn("⚠️ Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");const kOe="https://relzejiswnotikjgvjhz.supabase.co",TOe="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM",ae=NOe(kOe,TOe,{auth:{storage:localStorage,persistSession:!0,autoRefreshToken:!0}}),Yce=D.createContext(void 0),EOe=({children:t})=>{const[e,r]=D.useState(null),[n,i]=D.useState(null),[o,c]=D.useState(!0),[a,m]=D.useState(!1),[g,_]=D.useState(!1),[j,N]=D.useState(null),C=Bs(),P=async R=>{try{console.log("Checking roles via RPC for user:",R);const[{data:z,error:W},{data:V,error:K}]=await Promise.all([ae.rpc("has_role",{_user_id:R,_role:"admin"}),ae.rpc("has_role",{_user_id:R,_role:"brokerage_manager"})]);if(W||K)console.error("Role RPC errors:",{isAdminError:W,isBrokerError:K}),m(!1),_(!1);else{const X=!!z,ie=!!V;console.log("RPC roles result:",{adminValue:X,brokerValue:ie}),m(X),_(ie)}const{data:Q,error:te}=await ae.from("profiles").select("brokerage_id").eq("id",R).single();N(!te&&Q?Q.brokerage_id:null)}catch(z){console.error("Unexpected error in checkRoles:",z),m(!1),_(!1),N(null)}};D.useEffect(()=>{const{data:{subscription:R}}=ae.auth.onAuthStateChange((z,W)=>{i(W),r((W==null?void 0:W.user)??null),W!=null&&W.user?setTimeout(()=>{P(W.user.id)},0):(m(!1),_(!1),N(null))});return ae.auth.getSession().then(({data:{session:z}})=>{i(z),r((z==null?void 0:z.user)??null),z!=null&&z.user?P(z.user.id).finally(()=>{c(!1)}):c(!1)}),()=>R.unsubscribe()},[]);const A=async(R,z)=>{const{error:W}=await ae.auth.signInWithPassword({email:R,password:z});if(W)throw Dt.error(W.message),W;Dt.success("Welcome back!"),C("/dashboard")},I=async(R,z,W)=>{const V=`${window.location.origin}/dashboard`,{error:K}=await ae.auth.signUp({email:R,password:z,options:{emailRedirectTo:V,data:{name:W}}});if(K)throw Dt.error(K.message),K;Dt.success("Account created! Welcome to LevelUp."),C("/dashboard")},O=async()=>{try{const{data:{session:R}}=await ae.auth.getSession();if(R){const{error:z}=await ae.auth.signOut();z?z.message==="Auth session missing!"?console.warn("Sign out warning (ignored):",z.message):(console.error("Sign out error:",z),Dt.error(z.message)):Dt.success("Signed out successfully")}else console.log("No active session found, redirecting to auth");r(null),i(null),m(!1),_(!1),N(null),C("/auth")}catch(R){console.error("Unexpected sign out error:",R),C("/auth")}};return s.jsx(Yce.Provider,{value:{user:e,session:n,loading:o,signIn:A,signUp:I,signOut:O,isAdmin:a,isBrokerageManager:g,brokerageId:j},children:t})},rn=()=>{const t=D.useContext(Yce);if(t===void 0)throw new Error("useAuth must be used within an AuthProvider");return t},Un=({children:t,requireAdmin:e=!1,requireBrokerageManager:r=!1})=>{const{user:n,loading:i,isAdmin:o,isBrokerageManager:c}=rn();return i?s.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background",children:s.jsxs("div",{className:"text-center",children:[s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent mx-auto mb-4"}),s.jsx("p",{className:"text-muted-foreground",children:"Loading..."})]})}):n?e&&!o?s.jsx($F,{to:"/dashboard",replace:!0}):r&&!c&&!o?s.jsx($F,{to:"/dashboard",replace:!0}):s.jsx(s.Fragment,{children:t}):s.jsx($F,{to:"/auth",replace:!0})},m$="levelup_affiliate_ref",AOe=30,POe=()=>{const[t]=n0();D.useEffect(()=>{const e=t.get("ref");if(e){const r={code:e.toUpperCase(),timestamp:Date.now()};localStorage.setItem(m$,JSON.stringify(r)),console.log("[Affiliate] Stored referral code:",e)}},[t])},IOe=()=>{try{const t=localStorage.getItem(m$);if(!t)return null;const e=JSON.parse(t),r=AOe*24*60*60*1e3;return Date.now()-e.timestamp>r?(localStorage.removeItem(m$),console.log("[Affiliate] Referral code expired"),null):e.code}catch{return null}},sk=Ej("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-full text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),de=D.forwardRef(({className:t,variant:e,size:r,asChild:n=!1,...i},o)=>{const c=n?Cae:"button";return s.jsx(c,{className:ar(sk({variant:e,size:r,className:t})),ref:o,...i})});de.displayName="Button";const at=D.forwardRef(({className:t,...e},r)=>s.jsx("div",{ref:r,className:ar("rounded-lg border bg-card text-card-foreground shadow-sm",t),...e}));at.displayName="Card";const xr=D.forwardRef(({className:t,...e},r)=>s.jsx("div",{ref:r,className:ar("flex flex-col space-y-1.5 p-6",t),...e}));xr.displayName="CardHeader";const wr=D.forwardRef(({className:t,...e},r)=>s.jsx("h3",{ref:r,className:ar("text-2xl font-semibold leading-none tracking-tight",t),...e}));wr.displayName="CardTitle";const us=D.forwardRef(({className:t,...e},r)=>s.jsx("p",{ref:r,className:ar("text-sm text-muted-foreground",t),...e}));us.displayName="CardDescription";const ct=D.forwardRef(({className:t,...e},r)=>s.jsx("div",{ref:r,className:ar("p-6 pt-0",t),...e}));ct.displayName="CardContent";const o2=D.forwardRef(({className:t,...e},r)=>s.jsx("div",{ref:r,className:ar("flex items-center p-6 pt-0",t),...e}));o2.displayName="CardFooter";const Et=D.forwardRef(({className:t,type:e,...r},n)=>s.jsx("input",{type:e,className:ar("flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",t),ref:n,...r}));Et.displayName="Input";var MOe="Label",Xce=D.forwardRef((t,e)=>s.jsx(yn.label,{...t,ref:e,onMouseDown:r=>{var i;r.target.closest("button, input, select, textarea")||((i=t.onMouseDown)==null||i.call(t,r),!r.defaultPrevented&&r.detail>1&&r.preventDefault())}}));Xce.displayName=MOe;var Qce=Xce;const OOe=Ej("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),mt=D.forwardRef(({className:t,...e},r)=>s.jsx(Qce,{ref:r,className:ar(OOe(),t),...e}));mt.displayName=Qce.displayName;const kI="/assets/levelup-logo-horizontal-DEFNc0ms.png";var ez="focusScope.autoFocusOnMount",tz="focusScope.autoFocusOnUnmount",oX={bubbles:!1,cancelable:!0},ROe="FocusScope",jT=D.forwardRef((t,e)=>{const{loop:r=!1,trapped:n=!1,onMountAutoFocus:i,onUnmountAutoFocus:o,...c}=t,[a,m]=D.useState(null),g=Oo(i),_=Oo(o),j=D.useRef(null),N=vs(e,A=>m(A)),C=D.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;D.useEffect(()=>{if(n){let A=function(z){if(C.paused||!a)return;const W=z.target;a.contains(W)?j.current=W:Jg(j.current,{select:!0})},I=function(z){if(C.paused||!a)return;const W=z.relatedTarget;W!==null&&(a.contains(W)||Jg(j.current,{select:!0}))},O=function(z){if(document.activeElement===document.body)for(const V of z)V.removedNodes.length>0&&Jg(a)};document.addEventListener("focusin",A),document.addEventListener("focusout",I);const R=new MutationObserver(O);return a&&R.observe(a,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",A),document.removeEventListener("focusout",I),R.disconnect()}}},[n,a,C.paused]),D.useEffect(()=>{if(a){cX.add(C);const A=document.activeElement;if(!a.contains(A)){const O=new CustomEvent(ez,oX);a.addEventListener(ez,g),a.dispatchEvent(O),O.defaultPrevented||(DOe($Oe(Jce(a)),{select:!0}),document.activeElement===A&&Jg(a))}return()=>{a.removeEventListener(ez,g),setTimeout(()=>{const O=new CustomEvent(tz,oX);a.addEventListener(tz,_),a.dispatchEvent(O),O.defaultPrevented||Jg(A??document.body,{select:!0}),a.removeEventListener(tz,_),cX.remove(C)},0)}}},[a,g,_,C]);const P=D.useCallback(A=>{if(!r&&!n||C.paused)return;const I=A.key==="Tab"&&!A.altKey&&!A.ctrlKey&&!A.metaKey,O=document.activeElement;if(I&&O){const R=A.currentTarget,[z,W]=LOe(R);z&&W?!A.shiftKey&&O===W?(A.preventDefault(),r&&Jg(z,{select:!0})):A.shiftKey&&O===z&&(A.preventDefault(),r&&Jg(W,{select:!0})):O===R&&A.preventDefault()}},[r,n,C.paused]);return s.jsx(yn.div,{tabIndex:-1,...c,ref:N,onKeyDown:P})});jT.displayName=ROe;function DOe(t,{select:e=!1}={}){const r=document.activeElement;for(const n of t)if(Jg(n,{select:e}),document.activeElement!==r)return}function LOe(t){const e=Jce(t),r=lX(e,t),n=lX(e.reverse(),t);return[r,n]}function Jce(t){const e=[],r=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode:n=>{const i=n.tagName==="INPUT"&&n.type==="hidden";return n.disabled||n.hidden||i?NodeFilter.FILTER_SKIP:n.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;r.nextNode();)e.push(r.currentNode);return e}function lX(t,e){for(const r of t)if(!FOe(r,{upTo:e}))return r}function FOe(t,{upTo:e}){if(getComputedStyle(t).visibility==="hidden")return!0;for(;t;){if(e!==void 0&&t===e)return!1;if(getComputedStyle(t).display==="none")return!0;t=t.parentElement}return!1}function zOe(t){return t instanceof HTMLInputElement&&"select"in t}function Jg(t,{select:e=!1}={}){if(t&&t.focus){const r=document.activeElement;t.focus({preventScroll:!0}),t!==r&&zOe(t)&&e&&t.select()}}var cX=BOe();function BOe(){let t=[];return{add(e){const r=t[0];e!==r&&(r==null||r.pause()),t=uX(t,e),t.unshift(e)},remove(e){var r;t=uX(t,e),(r=t[0])==null||r.resume()}}}function uX(t,e){const r=[...t],n=r.indexOf(e);return n!==-1&&r.splice(n,1),r}function $Oe(t){return t.filter(e=>e.tagName!=="A")}var rz=0;function mD(){D.useEffect(()=>{const t=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",t[0]??dX()),document.body.insertAdjacentElement("beforeend",t[1]??dX()),rz++,()=>{rz===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(e=>e.remove()),rz--}},[])}function dX(){const t=document.createElement("span");return t.setAttribute("data-radix-focus-guard",""),t.tabIndex=0,t.style.outline="none",t.style.opacity="0",t.style.position="fixed",t.style.pointerEvents="none",t}var TI="right-scroll-bar-position",EI="width-before-scroll-bar",UOe="with-scroll-bars-hidden",VOe="--removed-body-scroll-bar-size";function nz(t,e){return typeof t=="function"?t(e):t&&(t.current=e),t}function qOe(t,e){var r=D.useState(function(){return{value:t,callback:e,facade:{get current(){return r.value},set current(n){var i=r.value;i!==n&&(r.value=n,r.callback(n,i))}}}})[0];return r.callback=e,r.facade}var HOe=typeof window<"u"?D.useLayoutEffect:D.useEffect,hX=new WeakMap;function WOe(t,e){var r=qOe(null,function(n){return t.forEach(function(i){return nz(i,n)})});return HOe(function(){var n=hX.get(r);if(n){var i=new Set(n),o=new Set(t),c=r.current;i.forEach(function(a){o.has(a)||nz(a,null)}),o.forEach(function(a){i.has(a)||nz(a,c)})}hX.set(r,t)},[t]),r}function GOe(t){return t}function KOe(t,e){e===void 0&&(e=GOe);var r=[],n=!1,i={read:function(){if(n)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return r.length?r[r.length-1]:t},useMedium:function(o){var c=e(o,n);return r.push(c),function(){r=r.filter(function(a){return a!==c})}},assignSyncMedium:function(o){for(n=!0;r.length;){var c=r;r=[],c.forEach(o)}r={push:function(a){return o(a)},filter:function(){return r}}},assignMedium:function(o){n=!0;var c=[];if(r.length){var a=r;r=[],a.forEach(o),c=r}var m=function(){var _=c;c=[],_.forEach(o)},g=function(){return Promise.resolve().then(m)};g(),r={push:function(_){c.push(_),g()},filter:function(_){return c=c.filter(_),r}}}};return i}function ZOe(t){t===void 0&&(t={});var e=KOe(null);return e.options=th({async:!0,ssr:!1},t),e}var eue=function(t){var e=t.sideCar,r=vx(t,["sideCar"]);if(!e)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var n=e.read();if(!n)throw new Error("Sidecar medium not found");return D.createElement(n,th({},r))};eue.isSideCarExport=!0;function YOe(t,e){return t.useMedium(e),eue}var tue=ZOe(),sz=function(){},gD=D.forwardRef(function(t,e){var r=D.useRef(null),n=D.useState({onScrollCapture:sz,onWheelCapture:sz,onTouchMoveCapture:sz}),i=n[0],o=n[1],c=t.forwardProps,a=t.children,m=t.className,g=t.removeScrollBar,_=t.enabled,j=t.shards,N=t.sideCar,C=t.noRelative,P=t.noIsolation,A=t.inert,I=t.allowPinchZoom,O=t.as,R=O===void 0?"div":O,z=t.gapMode,W=vx(t,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),V=N,K=WOe([r,e]),Q=th(th({},W),i);return D.createElement(D.Fragment,null,_&&D.createElement(V,{sideCar:tue,removeScrollBar:g,shards:j,noRelative:C,noIsolation:P,inert:A,setCallbacks:o,allowPinchZoom:!!I,lockRef:r,gapMode:z}),c?D.cloneElement(D.Children.only(a),th(th({},Q),{ref:K})):D.createElement(R,th({},Q,{className:m,ref:K}),a))});gD.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};gD.classNames={fullWidth:EI,zeroRight:TI};var XOe=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function QOe(){if(!document)return null;var t=document.createElement("style");t.type="text/css";var e=XOe();return e&&t.setAttribute("nonce",e),t}function JOe(t,e){t.styleSheet?t.styleSheet.cssText=e:t.appendChild(document.createTextNode(e))}function eRe(t){var e=document.head||document.getElementsByTagName("head")[0];e.appendChild(t)}var tRe=function(){var t=0,e=null;return{add:function(r){t==0&&(e=QOe())&&(JOe(e,r),eRe(e)),t++},remove:function(){t--,!t&&e&&(e.parentNode&&e.parentNode.removeChild(e),e=null)}}},rRe=function(){var t=tRe();return function(e,r){D.useEffect(function(){return t.add(e),function(){t.remove()}},[e&&r])}},rue=function(){var t=rRe(),e=function(r){var n=r.styles,i=r.dynamic;return t(n,i),null};return e},nRe={left:0,top:0,right:0,gap:0},iz=function(t){return parseInt(t||"",10)||0},sRe=function(t){var e=window.getComputedStyle(document.body),r=e[t==="padding"?"paddingLeft":"marginLeft"],n=e[t==="padding"?"paddingTop":"marginTop"],i=e[t==="padding"?"paddingRight":"marginRight"];return[iz(r),iz(n),iz(i)]},iRe=function(t){if(t===void 0&&(t="margin"),typeof window>"u")return nRe;var e=sRe(t),r=document.documentElement.clientWidth,n=window.innerWidth;return{left:e[0],top:e[1],right:e[2],gap:Math.max(0,n-r+e[2]-e[0])}},aRe=rue(),i1="data-scroll-locked",oRe=function(t,e,r,n){var i=t.left,o=t.top,c=t.right,a=t.gap;return r===void 0&&(r="margin"),` .`.concat(UOe,` { overflow: hidden `).concat(n,`; padding-right: `).concat(a,"px ").concat(n,`; } body[`).concat(i1,`] { overflow: hidden `).concat(n,`; overscroll-behavior: contain; `).concat([e&&"position: relative ".concat(n,";"),r==="margin"&&` padding-left: `.concat(i,`px; padding-top: `).concat(o,`px; padding-right: `).concat(c,`px; margin-left:0; margin-top:0; margin-right: `).concat(a,"px ").concat(n,`; `),r==="padding"&&"padding-right: ".concat(a,"px ").concat(n,";")].filter(Boolean).join(""),` } .`).concat(TI,` { right: `).concat(a,"px ").concat(n,`; } .`).concat(EI,` { margin-right: `).concat(a,"px ").concat(n,`; } .`).concat(TI," .").concat(TI,` { right: 0 `).concat(n,`; } .`).concat(EI," .").concat(EI,` { margin-right: 0 `).concat(n,`; } body[`).concat(i1,`] { `).concat(VOe,": ").concat(a,`px; } `)},fX=function(){var t=parseInt(document.body.getAttribute(i1)||"0",10);return isFinite(t)?t:0},lRe=function(){D.useEffect(function(){return document.body.setAttribute(i1,(fX()+1).toString()),function(){var t=fX()-1;t<=0?document.body.removeAttribute(i1):document.body.setAttribute(i1,t.toString())}},[])},cRe=function(t){var e=t.noRelative,r=t.noImportant,n=t.gapMode,i=n===void 0?"margin":n;lRe();var o=D.useMemo(function(){return iRe(i)},[i]);return D.createElement(aRe,{styles:oRe(o,!e,i,r?"":"!important")})},g$=!1;if(typeof window<"u")try{var kP=Object.defineProperty({},"passive",{get:function(){return g$=!0,!0}});window.addEventListener("test",kP,kP),window.removeEventListener("test",kP,kP)}catch{g$=!1}var aw=g$?{passive:!1}:!1,uRe=function(t){return t.tagName==="TEXTAREA"},nue=function(t,e){if(!(t instanceof Element))return!1;var r=window.getComputedStyle(t);return r[e]!=="hidden"&&!(r.overflowY===r.overflowX&&!uRe(t)&&r[e]==="visible")},dRe=function(t){return nue(t,"overflowY")},hRe=function(t){return nue(t,"overflowX")},pX=function(t,e){var r=e.ownerDocument,n=e;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var i=sue(t,n);if(i){var o=iue(t,n),c=o[1],a=o[2];if(c>a)return!0}n=n.parentNode}while(n&&n!==r.body);return!1},fRe=function(t){var e=t.scrollTop,r=t.scrollHeight,n=t.clientHeight;return[e,r,n]},pRe=function(t){var e=t.scrollLeft,r=t.scrollWidth,n=t.clientWidth;return[e,r,n]},sue=function(t,e){return t==="v"?dRe(e):hRe(e)},iue=function(t,e){return t==="v"?fRe(e):pRe(e)},mRe=function(t,e){return t==="h"&&e==="rtl"?-1:1},gRe=function(t,e,r,n,i){var o=mRe(t,window.getComputedStyle(e).direction),c=o*n,a=r.target,m=e.contains(a),g=!1,_=c>0,j=0,N=0;do{if(!a)break;var C=iue(t,a),P=C[0],A=C[1],I=C[2],O=A-I-o*P;(P||O)&&sue(t,a)&&(j+=O,N+=P);var R=a.parentNode;a=R&&R.nodeType===Node.DOCUMENT_FRAGMENT_NODE?R.host:R}while(!m&&a!==document.body||m&&(e.contains(a)||e===a));return(_&&Math.abs(j)<1||!_&&Math.abs(N)<1)&&(g=!0),g},TP=function(t){return"changedTouches"in t?[t.changedTouches[0].clientX,t.changedTouches[0].clientY]:[0,0]},mX=function(t){return[t.deltaX,t.deltaY]},gX=function(t){return t&&"current"in t?t.current:t},yRe=function(t,e){return t[0]===e[0]&&t[1]===e[1]},xRe=function(t){return` .block-interactivity-`.concat(t,` {pointer-events: none;} .allow-interactivity-`).concat(t,` {pointer-events: all;} `)},vRe=0,ow=[];function _Re(t){var e=D.useRef([]),r=D.useRef([0,0]),n=D.useRef(),i=D.useState(vRe++)[0],o=D.useState(rue)[0],c=D.useRef(t);D.useEffect(function(){c.current=t},[t]),D.useEffect(function(){if(t.inert){document.body.classList.add("block-interactivity-".concat(i));var A=v8([t.lockRef.current],(t.shards||[]).map(gX),!0).filter(Boolean);return A.forEach(function(I){return I.classList.add("allow-interactivity-".concat(i))}),function(){document.body.classList.remove("block-interactivity-".concat(i)),A.forEach(function(I){return I.classList.remove("allow-interactivity-".concat(i))})}}},[t.inert,t.lockRef.current,t.shards]);var a=D.useCallback(function(A,I){if("touches"in A&&A.touches.length===2||A.type==="wheel"&&A.ctrlKey)return!c.current.allowPinchZoom;var O=TP(A),R=r.current,z="deltaX"in A?A.deltaX:R[0]-O[0],W="deltaY"in A?A.deltaY:R[1]-O[1],V,K=A.target,Q=Math.abs(z)>Math.abs(W)?"h":"v";if("touches"in A&&Q==="h"&&K.type==="range")return!1;var te=pX(Q,K);if(!te)return!0;if(te?V=Q:(V=Q==="v"?"h":"v",te=pX(Q,K)),!te)return!1;if(!n.current&&"changedTouches"in A&&(z||W)&&(n.current=V),!V)return!0;var X=n.current||V;return gRe(X,I,A,X==="h"?z:W)},[]),m=D.useCallback(function(A){var I=A;if(!(!ow.length||ow[ow.length-1]!==o)){var O="deltaY"in I?mX(I):TP(I),R=e.current.filter(function(V){return V.name===I.type&&(V.target===I.target||I.target===V.shadowParent)&&yRe(V.delta,O)})[0];if(R&&R.should){I.cancelable&&I.preventDefault();return}if(!R){var z=(c.current.shards||[]).map(gX).filter(Boolean).filter(function(V){return V.contains(I.target)}),W=z.length>0?a(I,z[0]):!c.current.noIsolation;W&&I.cancelable&&I.preventDefault()}}},[]),g=D.useCallback(function(A,I,O,R){var z={name:A,delta:I,target:O,should:R,shadowParent:bRe(O)};e.current.push(z),setTimeout(function(){e.current=e.current.filter(function(W){return W!==z})},1)},[]),_=D.useCallback(function(A){r.current=TP(A),n.current=void 0},[]),j=D.useCallback(function(A){g(A.type,mX(A),A.target,a(A,t.lockRef.current))},[]),N=D.useCallback(function(A){g(A.type,TP(A),A.target,a(A,t.lockRef.current))},[]);D.useEffect(function(){return ow.push(o),t.setCallbacks({onScrollCapture:j,onWheelCapture:j,onTouchMoveCapture:N}),document.addEventListener("wheel",m,aw),document.addEventListener("touchmove",m,aw),document.addEventListener("touchstart",_,aw),function(){ow=ow.filter(function(A){return A!==o}),document.removeEventListener("wheel",m,aw),document.removeEventListener("touchmove",m,aw),document.removeEventListener("touchstart",_,aw)}},[]);var C=t.removeScrollBar,P=t.inert;return D.createElement(D.Fragment,null,P?D.createElement(o,{styles:xRe(i)}):null,C?D.createElement(cRe,{noRelative:t.noRelative,gapMode:t.gapMode}):null)}function bRe(t){for(var e=null;t!==null;)t instanceof ShadowRoot&&(e=t.host,t=t.host),t=t.parentNode;return e}const wRe=YOe(tue,_Re);var ST=D.forwardRef(function(t,e){return D.createElement(gD,th({},t,{ref:e,sideCar:wRe}))});ST.classNames=gD.classNames;var jRe=function(t){if(typeof document>"u")return null;var e=Array.isArray(t)?t[0]:t;return e.ownerDocument.body},lw=new WeakMap,EP=new WeakMap,AP={},az=0,aue=function(t){return t&&(t.host||aue(t.parentNode))},SRe=function(t,e){return e.map(function(r){if(t.contains(r))return r;var n=aue(r);return n&&t.contains(n)?n:(console.error("aria-hidden",r,"in not contained inside",t,". Doing nothing"),null)}).filter(function(r){return!!r})},NRe=function(t,e,r,n){var i=SRe(e,Array.isArray(t)?t:[t]);AP[r]||(AP[r]=new WeakMap);var o=AP[r],c=[],a=new Set,m=new Set(i),g=function(j){!j||a.has(j)||(a.add(j),g(j.parentNode))};i.forEach(g);var _=function(j){!j||m.has(j)||Array.prototype.forEach.call(j.children,function(N){if(a.has(N))_(N);else try{var C=N.getAttribute(n),P=C!==null&&C!=="false",A=(lw.get(N)||0)+1,I=(o.get(N)||0)+1;lw.set(N,A),o.set(N,I),c.push(N),A===1&&P&&EP.set(N,!0),I===1&&N.setAttribute(r,"true"),P||N.setAttribute(n,"true")}catch(O){console.error("aria-hidden: cannot operate on ",N,O)}})};return _(e),a.clear(),az++,function(){c.forEach(function(j){var N=lw.get(j)-1,C=o.get(j)-1;lw.set(j,N),o.set(j,C),N||(EP.has(j)||j.removeAttribute(n),EP.delete(j)),C||j.removeAttribute(r)}),az--,az||(lw=new WeakMap,lw=new WeakMap,EP=new WeakMap,AP={})}},yD=function(t,e,r){r===void 0&&(r="data-aria-hidden");var n=Array.from(Array.isArray(t)?t:[t]),i=jRe(t);return i?(n.push.apply(n,Array.from(i.querySelectorAll("[aria-live]"))),NRe(n,i,r,"aria-hidden")):function(){return null}},xD="Dialog",[oue,lue]=Yo(xD),[CRe,Ef]=oue(xD),cue=t=>{const{__scopeDialog:e,children:r,open:n,defaultOpen:i,onOpenChange:o,modal:c=!0}=t,a=D.useRef(null),m=D.useRef(null),[g,_]=Uu({prop:n,defaultProp:i??!1,onChange:o,caller:xD});return s.jsx(CRe,{scope:e,triggerRef:a,contentRef:m,contentId:Al(),titleId:Al(),descriptionId:Al(),open:g,onOpenChange:_,onOpenToggle:D.useCallback(()=>_(j=>!j),[_]),modal:c,children:r})};cue.displayName=xD;var uue="DialogTrigger",due=D.forwardRef((t,e)=>{const{__scopeDialog:r,...n}=t,i=Ef(uue,r),o=vs(e,i.triggerRef);return s.jsx(yn.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":A8(i.open),...n,ref:o,onClick:Yr(t.onClick,i.onOpenToggle)})});due.displayName=uue;var T8="DialogPortal",[kRe,hue]=oue(T8,{forceMount:void 0}),fue=t=>{const{__scopeDialog:e,forceMount:r,children:n,container:i}=t,o=Ef(T8,e);return s.jsx(kRe,{scope:e,forceMount:r,children:D.Children.map(n,c=>s.jsx(gl,{present:r||o.open,children:s.jsx(Tj,{asChild:!0,container:i,children:c})}))})};fue.displayName=T8;var EM="DialogOverlay",pue=D.forwardRef((t,e)=>{const r=hue(EM,t.__scopeDialog),{forceMount:n=r.forceMount,...i}=t,o=Ef(EM,t.__scopeDialog);return o.modal?s.jsx(gl,{present:n||o.open,children:s.jsx(ERe,{...i,ref:e})}):null});pue.displayName=EM;var TRe=nx("DialogOverlay.RemoveScroll"),ERe=D.forwardRef((t,e)=>{const{__scopeDialog:r,...n}=t,i=Ef(EM,r);return s.jsx(ST,{as:TRe,allowPinchZoom:!0,shards:[i.contentRef],children:s.jsx(yn.div,{"data-state":A8(i.open),...n,ref:e,style:{pointerEvents:"auto",...n.style}})})}),R_="DialogContent",mue=D.forwardRef((t,e)=>{const r=hue(R_,t.__scopeDialog),{forceMount:n=r.forceMount,...i}=t,o=Ef(R_,t.__scopeDialog);return s.jsx(gl,{present:n||o.open,children:o.modal?s.jsx(ARe,{...i,ref:e}):s.jsx(PRe,{...i,ref:e})})});mue.displayName=R_;var ARe=D.forwardRef((t,e)=>{const r=Ef(R_,t.__scopeDialog),n=D.useRef(null),i=vs(e,r.contentRef,n);return D.useEffect(()=>{const o=n.current;if(o)return yD(o)},[]),s.jsx(gue,{...t,ref:i,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Yr(t.onCloseAutoFocus,o=>{var c;o.preventDefault(),(c=r.triggerRef.current)==null||c.focus()}),onPointerDownOutside:Yr(t.onPointerDownOutside,o=>{const c=o.detail.originalEvent,a=c.button===0&&c.ctrlKey===!0;(c.button===2||a)&&o.preventDefault()}),onFocusOutside:Yr(t.onFocusOutside,o=>o.preventDefault())})}),PRe=D.forwardRef((t,e)=>{const r=Ef(R_,t.__scopeDialog),n=D.useRef(!1),i=D.useRef(!1);return s.jsx(gue,{...t,ref:e,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:o=>{var c,a;(c=t.onCloseAutoFocus)==null||c.call(t,o),o.defaultPrevented||(n.current||(a=r.triggerRef.current)==null||a.focus(),o.preventDefault()),n.current=!1,i.current=!1},onInteractOutside:o=>{var m,g;(m=t.onInteractOutside)==null||m.call(t,o),o.defaultPrevented||(n.current=!0,o.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const c=o.target;((g=r.triggerRef.current)==null?void 0:g.contains(c))&&o.preventDefault(),o.detail.originalEvent.type==="focusin"&&i.current&&o.preventDefault()}})}),gue=D.forwardRef((t,e)=>{const{__scopeDialog:r,trapFocus:n,onOpenAutoFocus:i,onCloseAutoFocus:o,...c}=t,a=Ef(R_,r),m=D.useRef(null),g=vs(e,m);return mD(),s.jsxs(s.Fragment,{children:[s.jsx(jT,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:i,onUnmountAutoFocus:o,children:s.jsx(t0,{role:"dialog",id:a.contentId,"aria-describedby":a.descriptionId,"aria-labelledby":a.titleId,"data-state":A8(a.open),...c,ref:g,onDismiss:()=>a.onOpenChange(!1)})}),s.jsxs(s.Fragment,{children:[s.jsx(MRe,{titleId:a.titleId}),s.jsx(RRe,{contentRef:m,descriptionId:a.descriptionId})]})]})}),E8="DialogTitle",yue=D.forwardRef((t,e)=>{const{__scopeDialog:r,...n}=t,i=Ef(E8,r);return s.jsx(yn.h2,{id:i.titleId,...n,ref:e})});yue.displayName=E8;var xue="DialogDescription",vue=D.forwardRef((t,e)=>{const{__scopeDialog:r,...n}=t,i=Ef(xue,r);return s.jsx(yn.p,{id:i.descriptionId,...n,ref:e})});vue.displayName=xue;var _ue="DialogClose",bue=D.forwardRef((t,e)=>{const{__scopeDialog:r,...n}=t,i=Ef(_ue,r);return s.jsx(yn.button,{type:"button",...n,ref:e,onClick:Yr(t.onClick,()=>i.onOpenChange(!1))})});bue.displayName=_ue;function A8(t){return t?"open":"closed"}var wue="DialogTitleWarning",[IRe,jue]=ACe(wue,{contentName:R_,titleName:E8,docsSlug:"dialog"}),MRe=({titleId:t})=>{const e=jue(wue),r=`\`${e.contentName}\` requires a \`${e.titleName}\` for the component to be accessible for screen reader users. If you want to hide the \`${e.titleName}\`, you can wrap it with our VisuallyHidden component. For more information, see https://radix-ui.com/primitives/docs/components/${e.docsSlug}`;return D.useEffect(()=>{t&&(document.getElementById(t)||console.error(r))},[r,t]),null},ORe="DialogDescriptionWarning",RRe=({contentRef:t,descriptionId:e})=>{const n=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${jue(ORe).contentName}}.`;return D.useEffect(()=>{var o;const i=(o=t.current)==null?void 0:o.getAttribute("aria-describedby");e&&i&&(document.getElementById(e)||console.warn(n))},[n,t,e]),null},vD=cue,P8=due,_D=fue,Bj=pue,$j=mue,NT=yue,CT=vue,bD=bue;const mn=vD,Do=P8,DRe=_D,Sue=D.forwardRef(({className:t,...e},r)=>s.jsx(Bj,{ref:r,className:ar("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",t),...e}));Sue.displayName=Bj.displayName;const pn=D.forwardRef(({className:t,children:e,...r},n)=>s.jsxs(DRe,{children:[s.jsx(Sue,{}),s.jsxs($j,{ref:n,className:ar("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",t),...r,children:[e,s.jsxs(bD,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity data-[state=open]:bg-accent data-[state=open]:text-muted-foreground hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none",children:[s.jsx(Ni,{className:"h-4 w-4"}),s.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));pn.displayName=$j.displayName;const xn=({className:t,...e})=>s.jsx("div",{className:ar("flex flex-col space-y-1.5 text-center sm:text-left",t),...e});xn.displayName="DialogHeader";const zi=({className:t,...e})=>s.jsx("div",{className:ar("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",t),...e});zi.displayName="DialogFooter";const gn=D.forwardRef(({className:t,...e},r)=>s.jsx(NT,{ref:r,className:ar("text-lg font-semibold leading-none tracking-tight",t),...e}));gn.displayName=NT.displayName;const fi=D.forwardRef(({className:t,...e},r)=>s.jsx(CT,{ref:r,className:ar("text-sm text-muted-foreground",t),...e}));fi.displayName=CT.displayName;function LRe({open:t,onOpenChange:e}){return s.jsx(mn,{open:t,onOpenChange:e,children:s.jsxs(pn,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[s.jsx(xn,{children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"p-2 bg-[#4a6b6d]/10 rounded-lg",children:s.jsx(yc,{className:"h-5 w-5 text-[#4a6b6d]"})}),s.jsxs("div",{children:[s.jsx(gn,{children:"Schedule a Brokerage Interest Meeting"}),s.jsx(fi,{children:"Learn how LevelUp can empower your entire team"})]})]})}),t&&s.jsx("iframe",{src:"https://tidycal.com/jeremycollins/brokerinterestmeeting",className:"w-full border-0 rounded-lg",style:{height:"600px",minHeight:"500px"},title:"Schedule Brokerage Interest Meeting"})]})})}const zl={individual_agent:{name:"Individual Agent",price:"$39",period:"/month",description:"Perfect for independent agents ready to level up",features:["Full dashboard access","300+ professional templates","Academy training library","Community & networking","Live events & workshops","Social media content","Newsletter resources","Email support"],trial:"7-day free trial"},brokerage_under_25:{name:"Brokerage",subtitle:"Under 25 Agents",price:"$299",period:"/month",description:"Empower your entire team to succeed",features:["Everything in Individual","Brokerage manager dashboard","Invite & manage up to 25 agents","Exclusive brokerage resources","Team performance analytics","Agent onboarding tools","Resource sharing","Priority support"]},brokerage_over_25:{name:"Brokerage",subtitle:"Over 25 Agents",price:"$499",period:"/month",description:"Scale your brokerage without limits",features:["Everything in Brokerage","Unlimited agents","Advanced team analytics","Dedicated account manager","Custom onboarding sessions","White-glove support"]}},FRe=[{icon:dM,title:"Academy Training",description:"Access a library of on-demand video training covering lead generation, marketing, technology, and more."},{icon:A_,title:"300+ Templates",description:"Professional Canva templates for social media, flyers, postcards, and marketing materials."},{icon:ko,title:"Live Events",description:"Weekly live training sessions, workshops, and Q&A events with industry experts."},{icon:lu,title:"Agent Community",description:"Connect with fellow agents, share wins, ask questions, and network in our private community."},{icon:Ii,title:"Resource Kits",description:"Downloadable toolkits with scripts, checklists, guides, and everything you need to close more deals."},{icon:yd,title:"Social Swag",description:"Fresh social media content and designs updated regularly to help you stand out online."}],zRe=[{icon:_i,title:"Contact Management",description:"Organize your sphere into relationship tiers—Top 25, Past Clients, Referral Partners, and more."},{icon:cu,title:"Smart Touchpoint Plans",description:"Automated action plans that tell you exactly who to contact and how, based on relationship type."},{icon:Yl,title:"One-Tap Actions",description:"Call, text, or email contacts directly with pre-written scripts tailored to each relationship."},{icon:uM,title:"Birthday & Anniversary Alerts",description:"Never miss an important date—get reminders for birthdays and home anniversaries."},{icon:wp,title:"Pop-by Map",description:"See all your contacts on a map and plan efficient pop-by routes in your area."},{icon:_p,title:"Momentum Tracking",description:"Track your touch streaks, weekly goals, and relationship health scores."},{icon:bp,title:"Relationship Health",description:"Visual dashboard showing which contacts need attention based on last touch date."},{icon:koe,title:"Daily Action Cards",description:"Wake up to a prioritized list of exactly who to reach out to today."}],BRe=[{name:"Sarah M.",role:"Top Producer, RE/MAX",quote:"LevelUp completely transformed how I run my business. The templates alone save me hours every week."},{name:"Mike T.",role:"Brokerage Owner",quote:"Onboarding new agents used to take weeks. Now they're productive from day one with all the training resources."},{name:"Jessica L.",role:"Team Lead",quote:"The community is incredible. I've learned more from other agents here than any conference I've attended."}],$Re=()=>{const{user:t,loading:e}=rn(),r=Bs(),[n]=n0(),[i,o]=D.useState(null),[c,a]=D.useState(""),[m,g]=D.useState(""),[_,j]=D.useState(""),[N,C]=D.useState(!1),[P,A]=D.useState(!1);POe(),D.useEffect(()=>{!e&&t&&r("/dashboard")},[t,e,r]),D.useEffect(()=>{n.get("canceled")==="true"&&Dt.error("Checkout was canceled. Feel free to try again when you're ready!")},[n]);const I=async(O,R=!1)=>{if(!c){Dt.error("Please enter your email address");return}if(!m.trim()){Dt.error("Please enter your full name");return}C(!0),o(O+(R?"_direct":""));const z=IOe();try{const{data:W,error:V}=await ae.functions.invoke("create-checkout",{body:{tier:O,email:c,name:m.trim(),couponCode:_.trim()||void 0,skipTrial:R,referralCode:z}});if(V)throw V;if(W!=null&&W.url)window.open(W.url,"_blank","noopener,noreferrer"),Dt.success("Checkout opened in a new tab");else throw new Error("No checkout URL returned")}catch(W){console.error("Checkout error:",W),Dt.error(W.message||"Failed to start checkout. Please try again.")}finally{C(!1),o(null)}};return e?s.jsx("div",{className:"flex min-h-screen items-center justify-center bg-[#4a6b6d]",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-white border-t-transparent"})}):s.jsxs("div",{className:"min-h-screen bg-background overflow-hidden",children:[s.jsx("nav",{className:"fixed top-0 left-0 right-0 z-50 bg-[#4a6b6d] shadow-md",children:s.jsxs("div",{className:"container mx-auto px-4 py-3 flex items-center justify-between",children:[s.jsx("div",{className:"bg-white rounded-lg px-3 py-1.5",children:s.jsx("img",{src:kI,alt:"LevelUp",className:"h-8 md:h-10"})}),s.jsxs("div",{className:"flex items-center gap-2 md:gap-4",children:[s.jsx(de,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>{var O;return(O=document.getElementById("features"))==null?void 0:O.scrollIntoView({behavior:"smooth"})},children:"Features"}),s.jsx(de,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>{var O;return(O=document.getElementById("pricing"))==null?void 0:O.scrollIntoView({behavior:"smooth"})},children:"Pricing"}),s.jsx(de,{onClick:()=>r("/auth"),className:"bg-white text-[#4a6b6d] hover:bg-gray-100 font-medium shadow-md",children:"Sign In"})]})]})}),s.jsxs("section",{className:"relative pt-24 pb-20 bg-[#4a6b6d] overflow-hidden",children:[s.jsx("div",{className:"absolute inset-0 opacity-10",children:s.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),s.jsx("div",{className:"container mx-auto px-4 relative",children:s.jsxs("div",{className:"max-w-5xl mx-auto text-center space-y-8",children:[s.jsx("div",{className:"flex justify-center mb-8",children:s.jsx("div",{className:"bg-white rounded-xl px-6 py-3 shadow-lg",children:s.jsx("img",{src:kI,alt:"LevelUp Consulting Group",className:"h-14 md:h-16"})})}),s.jsx("h2",{className:"font-serif text-xl md:text-2xl tracking-[0.25em] text-white/90 uppercase",children:"Real Growth. Real Tools. Real Results."}),s.jsx("p",{className:"text-lg md:text-xl text-white/80 max-w-3xl mx-auto leading-relaxed",children:"Join the membership designed to help real estate agents thrive—with coaching from industry pros, done-for-you marketing tools, and the systems you need to scale."}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center items-center pt-4",children:[s.jsxs(de,{size:"lg",onClick:()=>{var O;return(O=document.getElementById("pricing"))==null?void 0:O.scrollIntoView({behavior:"smooth"})},className:"px-8 py-7 text-lg font-semibold bg-white text-[#4a6b6d] hover:bg-white/90 shadow-2xl transition-all hover:scale-105 group",children:["Start Your Free Trial",s.jsx(cd,{className:"ml-2 w-5 h-5 group-hover:translate-x-1 transition-transform"})]}),s.jsx(de,{size:"lg",variant:"outline",onClick:()=>{var O;return(O=document.getElementById("features"))==null?void 0:O.scrollIntoView({behavior:"smooth"})},className:"px-8 py-7 text-lg font-semibold border-2 border-white text-white bg-transparent hover:bg-white hover:text-[#4a6b6d]",children:"See What's Included"})]})]})})]}),s.jsx("section",{className:"py-20 bg-background",children:s.jsx("div",{className:"container mx-auto px-4",children:s.jsxs("div",{className:"max-w-4xl mx-auto text-center space-y-8",children:[s.jsxs("h2",{className:"font-serif text-3xl md:text-5xl text-foreground leading-tight",children:["Real estate moves fast —",s.jsx("br",{}),"your ",s.jsx("span",{className:"italic text-[#4a6b6d]",children:"support system"})," should too."]}),s.jsxs("div",{className:"space-y-4 text-lg text-muted-foreground",children:[s.jsxs("p",{children:[s.jsx("span",{className:"italic font-medium text-foreground",children:"Agents"})," are expected to be marketers, tech experts, negotiators, and more."]}),s.jsxs("p",{children:[s.jsx("span",{className:"italic font-medium text-foreground",children:"Brokerages"})," carry the weight of developing talent and keeping production high."]})]}),s.jsx("p",{className:"font-serif text-xl md:text-2xl italic text-[#4a6b6d] pt-4",children:"LEVELUP EQUIPS BOTH TO THRIVE."}),s.jsx("p",{className:"text-lg text-muted-foreground",children:"Learn how we support agents and empower brokerages to grow—together."}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center pt-4",children:[s.jsxs(de,{size:"lg",variant:"outline",onClick:()=>{var O;return(O=document.getElementById("brokerage"))==null?void 0:O.scrollIntoView({behavior:"smooth"})},className:"border-[#4a6b6d] text-[#4a6b6d] hover:bg-[#4a6b6d]/5",children:[s.jsx(yc,{className:"mr-2 h-5 w-5"}),"Brokerage Partnership"]}),s.jsxs(de,{size:"lg",onClick:()=>{var O;return(O=document.getElementById("pricing"))==null?void 0:O.scrollIntoView({behavior:"smooth"})},className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:[s.jsx(bf,{className:"mr-2 h-5 w-5"}),"Individual Membership"]})]})]})})}),s.jsx("section",{id:"features",className:"py-20 bg-muted/30",children:s.jsxs("div",{className:"container mx-auto px-4",children:[s.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-16",children:[s.jsx("h2",{className:"font-serif text-3xl md:text-4xl mb-6",children:"What's inside our members only portal?"}),s.jsx("p",{className:"text-lg text-muted-foreground",children:"Everything you need to grow your business, all in one place."})]}),s.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8 max-w-6xl mx-auto",children:FRe.map((O,R)=>s.jsxs(at,{className:"group relative overflow-hidden border hover:border-[#4a6b6d]/50 transition-all duration-300 hover:shadow-lg bg-background",children:[s.jsxs(xr,{children:[s.jsx("div",{className:"w-14 h-14 rounded-2xl bg-[#4a6b6d]/10 flex items-center justify-center mb-4",children:s.jsx(O.icon,{className:"w-7 h-7 text-[#4a6b6d]"})}),s.jsx(wr,{className:"text-xl font-serif",children:O.title})]}),s.jsx(ct,{children:s.jsx("p",{className:"text-muted-foreground leading-relaxed",children:O.description})})]},R))})]})}),s.jsxs("section",{id:"agent-os",className:"py-20 bg-gradient-to-br from-[#4a6b6d] to-[#3d5a5c] relative overflow-hidden",children:[s.jsx("div",{className:"absolute inset-0 opacity-10",children:s.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),s.jsxs("div",{className:"container mx-auto px-4 relative",children:[s.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-16",children:[s.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-2 rounded-full bg-white/10 text-white text-sm font-medium mb-6",children:[s.jsx(cu,{className:"w-4 h-4"}),"Included with Membership"]}),s.jsxs("h2",{className:"font-serif text-3xl md:text-4xl mb-6 text-white",children:["Meet ",s.jsx("span",{className:"italic",children:"Agent OS"})]}),s.jsx("p",{className:"text-lg text-white/80",children:"Your relationship-first operating system. Never forget a follow-up, track every touchpoint, and turn your sphere into a referral machine."})]}),s.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 max-w-6xl mx-auto",children:zRe.map((O,R)=>s.jsxs(at,{className:"group relative overflow-hidden border-0 bg-white/10 backdrop-blur-sm hover:bg-white/20 transition-all duration-300",children:[s.jsxs(xr,{className:"pb-3",children:[s.jsx("div",{className:"w-12 h-12 rounded-xl bg-white/20 flex items-center justify-center mb-3",children:s.jsx(O.icon,{className:"w-6 h-6 text-white"})}),s.jsx(wr,{className:"text-lg font-semibold text-white",children:O.title})]}),s.jsx(ct,{children:s.jsx("p",{className:"text-white/70 text-sm leading-relaxed",children:O.description})})]},R))}),s.jsx("div",{className:"text-center mt-12",children:s.jsxs(de,{size:"lg",onClick:()=>{var O;return(O=document.getElementById("pricing"))==null?void 0:O.scrollIntoView({behavior:"smooth"})},className:"bg-white text-[#4a6b6d] hover:bg-white/90 shadow-xl transition-all hover:scale-105",children:["Get Agent OS with Your Membership",s.jsx(cd,{className:"ml-2 w-5 h-5"})]})})]})]}),s.jsx("section",{id:"brokerage",className:"py-20 bg-[#4a6b6d]/5",children:s.jsx("div",{className:"container mx-auto px-4",children:s.jsx("div",{className:"max-w-6xl mx-auto",children:s.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-12 items-center",children:[s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-2 rounded-full bg-[#4a6b6d]/10 text-[#4a6b6d] text-sm font-medium",children:[s.jsx(yc,{className:"w-4 h-4"}),"For Brokerages"]}),s.jsxs("h2",{className:"font-serif text-3xl md:text-4xl",children:["Empower Your"," ",s.jsx("span",{className:"italic text-[#4a6b6d]",children:"Entire Team"})]}),s.jsx("p",{className:"text-lg text-muted-foreground",children:"Give every agent on your team access to world-class training and resources. Track performance, streamline onboarding, and watch your brokerage thrive."}),s.jsx("ul",{className:"space-y-4",children:["Dedicated brokerage manager dashboard","Invite and manage agents with one click","Exclusive brokerage-only resources","Team analytics and performance tracking","Simplified agent onboarding","Share resources across your team"].map((O,R)=>s.jsxs("li",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"w-6 h-6 rounded-full bg-[#4a6b6d]/10 flex items-center justify-center flex-shrink-0",children:s.jsx(ru,{className:"w-4 h-4 text-[#4a6b6d]"})}),s.jsx("span",{className:"text-foreground",children:O})]},R))}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 mt-4",children:[s.jsxs(de,{size:"lg",onClick:()=>{var O;return(O=document.getElementById("pricing"))==null?void 0:O.scrollIntoView({behavior:"smooth"})},className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:["See Brokerage Plans",s.jsx(wd,{className:"ml-2 w-5 h-5"})]}),s.jsxs(de,{size:"lg",variant:"outline",onClick:()=>A(!0),className:"border-[#4a6b6d] text-[#4a6b6d] hover:bg-[#4a6b6d]/10",children:[s.jsx(ko,{className:"mr-2 w-5 h-5"}),"Schedule Info Session"]})]})]}),s.jsx("div",{className:"relative",children:s.jsx("div",{className:"aspect-square rounded-3xl bg-gradient-to-br from-[#4a6b6d]/20 to-[#4a6b6d]/5 p-8 flex items-center justify-center border border-[#4a6b6d]/20",children:s.jsxs("div",{className:"text-center space-y-4",children:[s.jsx(_i,{className:"w-24 h-24 text-[#4a6b6d] mx-auto"}),s.jsx("p",{className:"text-2xl font-serif",children:"Scale Your Team"}),s.jsx("p",{className:"text-muted-foreground",children:"From 5 agents to 500"})]})})})]})})})}),s.jsx("section",{className:"py-20 bg-background",children:s.jsxs("div",{className:"container mx-auto px-4",children:[s.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-16",children:[s.jsxs("h2",{className:"font-serif text-3xl md:text-4xl mb-6",children:["Agents Love ",s.jsx("span",{className:"italic text-[#4a6b6d]",children:"LevelUp"})]}),s.jsx("p",{className:"text-lg text-muted-foreground",children:"See what top producers are saying about the platform."})]}),s.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-8 max-w-6xl mx-auto",children:BRe.map((O,R)=>s.jsx(at,{className:"bg-muted/30 border-0",children:s.jsxs(ct,{className:"pt-8",children:[s.jsx("div",{className:"flex gap-1 mb-4",children:[1,2,3,4,5].map(z=>s.jsx(mh,{className:"w-5 h-5 fill-yellow-400 text-yellow-400"},z))}),s.jsxs("p",{className:"text-lg mb-6 italic text-muted-foreground",children:['"',O.quote,'"']}),s.jsxs("div",{children:[s.jsx("p",{className:"font-semibold",children:O.name}),s.jsx("p",{className:"text-sm text-muted-foreground",children:O.role})]})]})},R))})]})}),s.jsx("section",{id:"pricing",className:"py-20 bg-muted/30",children:s.jsxs("div",{className:"container mx-auto px-4",children:[s.jsxs("div",{className:"text-center mb-16",children:[s.jsxs("h2",{className:"font-serif text-3xl md:text-4xl mb-6",children:["Simple, Transparent ",s.jsx("span",{className:"italic text-[#4a6b6d]",children:"Pricing"})]}),s.jsx("p",{className:"text-lg text-muted-foreground max-w-2xl mx-auto",children:"Choose the plan that fits your needs. All plans include everything you need to succeed."})]}),s.jsxs("div",{className:"max-w-md mx-auto mb-16 p-8 rounded-2xl bg-background border shadow-lg",children:[s.jsx("h3",{className:"text-xl font-serif mb-6 text-center",children:"Enter your details to get started"}),s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsxs(mt,{htmlFor:"signup-name",children:["Full Name ",s.jsx("span",{className:"text-red-500",children:"*"})]}),s.jsx(Et,{id:"signup-name",type:"text",placeholder:"John Smith",value:m,onChange:O=>g(O.target.value),className:"mt-1",required:!0})]}),s.jsxs("div",{children:[s.jsxs(mt,{htmlFor:"signup-email",children:["Email Address ",s.jsx("span",{className:"text-red-500",children:"*"})]}),s.jsx(Et,{id:"signup-email",type:"email",placeholder:"you@example.com",value:c,onChange:O=>a(O.target.value),className:"mt-1",required:!0})]}),s.jsxs("div",{children:[s.jsxs(mt,{htmlFor:"coupon-code",children:["Discount Code ",s.jsx("span",{className:"text-muted-foreground",children:"(Optional)"})]}),s.jsx(Et,{id:"coupon-code",type:"text",placeholder:"Enter discount code",value:_,onChange:O=>j(O.target.value),className:"mt-1"})]})]})]}),s.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-8 max-w-6xl mx-auto",children:[s.jsxs(at,{className:"relative flex flex-col border hover:border-[#4a6b6d]/50 transition-all hover:shadow-xl bg-background",children:[s.jsxs(xr,{className:"pb-4",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[s.jsx("div",{className:"w-10 h-10 rounded-xl bg-[#4a6b6d]/10 flex items-center justify-center",children:s.jsx(bf,{className:"w-5 h-5 text-[#4a6b6d]"})}),s.jsx(wr,{className:"text-xl font-serif",children:zl.individual_agent.name})]}),s.jsxs("div",{className:"flex items-baseline gap-1 mt-4",children:[s.jsx("span",{className:"text-5xl font-bold",children:zl.individual_agent.price}),s.jsx("span",{className:"text-muted-foreground text-lg",children:zl.individual_agent.period})]}),s.jsx(us,{className:"text-base mt-2",children:zl.individual_agent.description}),s.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-2 rounded-full bg-green-500/10 text-green-600 text-sm font-medium mt-4",children:[s.jsx(No,{className:"w-4 h-4"}),zl.individual_agent.trial]})]}),s.jsx(ct,{className:"flex-1 pt-0",children:s.jsx("ul",{className:"space-y-3",children:zl.individual_agent.features.map((O,R)=>s.jsxs("li",{className:"flex items-center gap-3",children:[s.jsx(ru,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),s.jsx("span",{children:O})]},R))})}),s.jsxs(o2,{className:"flex flex-col gap-3 pt-4",children:[s.jsx(de,{className:"w-full py-6 text-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:()=>I("individual_agent"),disabled:N,children:N&&i==="individual_agent"?"Loading...":"Start Free Trial"}),s.jsx(de,{variant:"ghost",className:"w-full text-sm text-muted-foreground",onClick:()=>I("individual_agent",!0),disabled:N,children:N&&i==="individual_agent_direct"?"Loading...":"Skip trial, subscribe now"})]})]}),s.jsxs(at,{className:"relative flex flex-col border-2 border-[#4a6b6d] shadow-2xl scale-105 bg-background",children:[s.jsx("div",{className:"absolute -top-4 left-1/2 -translate-x-1/2 px-6 py-2 bg-[#4a6b6d] text-white text-sm font-semibold rounded-full shadow-lg",children:"Most Popular"}),s.jsxs(xr,{className:"pb-4 pt-8",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[s.jsx("div",{className:"w-10 h-10 rounded-xl bg-[#4a6b6d]/20 flex items-center justify-center",children:s.jsx(yc,{className:"w-5 h-5 text-[#4a6b6d]"})}),s.jsxs("div",{children:[s.jsx(wr,{className:"text-xl font-serif",children:zl.brokerage_under_25.name}),s.jsx("span",{className:"text-sm text-muted-foreground",children:zl.brokerage_under_25.subtitle})]})]}),s.jsxs("div",{className:"flex items-baseline gap-1 mt-4",children:[s.jsx("span",{className:"text-5xl font-bold",children:zl.brokerage_under_25.price}),s.jsx("span",{className:"text-muted-foreground text-lg",children:zl.brokerage_under_25.period})]}),s.jsx(us,{className:"text-base mt-2",children:zl.brokerage_under_25.description})]}),s.jsx(ct,{className:"flex-1 pt-0",children:s.jsx("ul",{className:"space-y-3",children:zl.brokerage_under_25.features.map((O,R)=>s.jsxs("li",{className:"flex items-center gap-3",children:[s.jsx(ru,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),s.jsx("span",{children:O})]},R))})}),s.jsx(o2,{className:"pt-4",children:s.jsx(de,{className:"w-full py-6 text-lg shadow-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:()=>I("brokerage_under_25"),disabled:N,children:N&&i==="brokerage_under_25"?"Loading...":"Get Started"})})]}),s.jsxs(at,{className:"relative flex flex-col border hover:border-[#4a6b6d]/50 transition-all hover:shadow-xl bg-background",children:[s.jsxs(xr,{className:"pb-4",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[s.jsx("div",{className:"w-10 h-10 rounded-xl bg-[#4a6b6d]/10 flex items-center justify-center",children:s.jsx(yc,{className:"w-5 h-5 text-[#4a6b6d]"})}),s.jsxs("div",{children:[s.jsx(wr,{className:"text-xl font-serif",children:zl.brokerage_over_25.name}),s.jsx("span",{className:"text-sm text-muted-foreground",children:zl.brokerage_over_25.subtitle})]})]}),s.jsxs("div",{className:"flex items-baseline gap-1 mt-4",children:[s.jsx("span",{className:"text-5xl font-bold",children:zl.brokerage_over_25.price}),s.jsx("span",{className:"text-muted-foreground text-lg",children:zl.brokerage_over_25.period})]}),s.jsx(us,{className:"text-base mt-2",children:zl.brokerage_over_25.description})]}),s.jsx(ct,{className:"flex-1 pt-0",children:s.jsx("ul",{className:"space-y-3",children:zl.brokerage_over_25.features.map((O,R)=>s.jsxs("li",{className:"flex items-center gap-3",children:[s.jsx(ru,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),s.jsx("span",{children:O})]},R))})}),s.jsx(o2,{className:"pt-4",children:s.jsx(de,{className:"w-full py-6 text-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:()=>I("brokerage_over_25"),disabled:N,children:N&&i==="brokerage_over_25"?"Loading...":"Get Started"})})]})]})]})}),s.jsx("section",{className:"py-20 bg-[#4a6b6d]",children:s.jsx("div",{className:"container mx-auto px-4",children:s.jsxs("div",{className:"max-w-4xl mx-auto text-center space-y-8",children:[s.jsx("h2",{className:"font-serif text-3xl md:text-4xl text-white",children:"Ready to Level Up?"}),s.jsx("p",{className:"text-lg text-white/80 max-w-2xl mx-auto",children:"Join thousands of agents who are closing more deals, saving time, and growing their business with LevelUp."}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center",children:[s.jsxs(de,{size:"lg",onClick:()=>{var O;return(O=document.getElementById("pricing"))==null?void 0:O.scrollIntoView({behavior:"smooth"})},className:"px-10 py-7 text-lg font-semibold bg-white text-[#4a6b6d] hover:bg-white/90 shadow-2xl transition-all hover:scale-105",children:["Start Your Free Trial",s.jsx(cd,{className:"ml-2 w-5 h-5"})]}),s.jsx(de,{size:"lg",onClick:()=>r("/auth"),className:"px-10 py-7 text-lg font-semibold border-2 border-white text-white bg-transparent hover:bg-white hover:text-[#4a6b6d]",children:"Sign In"})]})]})})}),s.jsx("footer",{className:"py-12 bg-[#3d5a5c] text-white/80",children:s.jsx("div",{className:"container mx-auto px-4",children:s.jsxs("div",{className:"flex flex-col md:flex-row items-center justify-between gap-4",children:[s.jsx("img",{src:kI,alt:"LevelUp",className:"h-8"}),s.jsxs("p",{className:"text-sm",children:["© ",new Date().getFullYear()," LevelUp. All rights reserved."]}),s.jsx("div",{className:"flex items-center gap-6",children:s.jsx("a",{href:"mailto:support@relevelup.com",className:"text-white/60 hover:text-white transition-colors text-sm",children:"Contact Support"})})]})})}),s.jsx(LRe,{open:P,onOpenChange:A})]})};var ha;(function(t){t.assertEqual=i=>{};function e(i){}t.assertIs=e;function r(i){throw new Error}t.assertNever=r,t.arrayToEnum=i=>{const o={};for(const c of i)o[c]=c;return o},t.getValidEnumValues=i=>{const o=t.objectKeys(i).filter(a=>typeof i[i[a]]!="number"),c={};for(const a of o)c[a]=i[a];return t.objectValues(c)},t.objectValues=i=>t.objectKeys(i).map(function(o){return i[o]}),t.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{const o=[];for(const c in i)Object.prototype.hasOwnProperty.call(i,c)&&o.push(c);return o},t.find=(i,o)=>{for(const c of i)if(o(c))return c},t.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function n(i,o=" | "){return i.map(c=>typeof c=="string"?`'${c}'`:c).join(o)}t.joinValues=n,t.jsonStringifyReplacer=(i,o)=>typeof o=="bigint"?o.toString():o})(ha||(ha={}));var yX;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(yX||(yX={}));const es=ha.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),sy=t=>{switch(typeof t){case"undefined":return es.undefined;case"string":return es.string;case"number":return Number.isNaN(t)?es.nan:es.number;case"boolean":return es.boolean;case"function":return es.function;case"bigint":return es.bigint;case"symbol":return es.symbol;case"object":return Array.isArray(t)?es.array:t===null?es.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?es.promise:typeof Map<"u"&&t instanceof Map?es.map:typeof Set<"u"&&t instanceof Set?es.set:typeof Date<"u"&&t instanceof Date?es.date:es.object;default:return es.unknown}},dn=ha.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class Sp extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){const r=e||function(o){return o.message},n={_errors:[]},i=o=>{for(const c of o.issues)if(c.code==="invalid_union")c.unionErrors.map(i);else if(c.code==="invalid_return_type")i(c.returnTypeError);else if(c.code==="invalid_arguments")i(c.argumentsError);else if(c.path.length===0)n._errors.push(r(c));else{let a=n,m=0;for(;mr.message){const r={},n=[];for(const i of this.issues)if(i.path.length>0){const o=i.path[0];r[o]=r[o]||[],r[o].push(e(i))}else n.push(e(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}}Sp.create=t=>new Sp(t);const y$=(t,e)=>{let r;switch(t.code){case dn.invalid_type:t.received===es.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case dn.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ha.jsonStringifyReplacer)}`;break;case dn.unrecognized_keys:r=`Unrecognized key(s) in object: ${ha.joinValues(t.keys,", ")}`;break;case dn.invalid_union:r="Invalid input";break;case dn.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ha.joinValues(t.options)}`;break;case dn.invalid_enum_value:r=`Invalid enum value. Expected ${ha.joinValues(t.options)}, received '${t.received}'`;break;case dn.invalid_arguments:r="Invalid function arguments";break;case dn.invalid_return_type:r="Invalid function return type";break;case dn.invalid_date:r="Invalid date";break;case dn.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:ha.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case dn.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case dn.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case dn.custom:r="Invalid input";break;case dn.invalid_intersection_types:r="Intersection results could not be merged";break;case dn.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case dn.not_finite:r="Number must be finite";break;default:r=e.defaultError,ha.assertNever(t)}return{message:r}};let URe=y$;function VRe(){return URe}const qRe=t=>{const{data:e,path:r,errorMaps:n,issueData:i}=t,o=[...r,...i.path||[]],c={...i,path:o};if(i.message!==void 0)return{...i,path:o,message:i.message};let a="";const m=n.filter(g=>!!g).slice().reverse();for(const g of m)a=g(c,{data:e,defaultError:a}).message;return{...i,path:o,message:a}};function Rn(t,e){const r=VRe(),n=qRe({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===y$?void 0:y$].filter(i=>!!i)});t.common.issues.push(n)}class Sd{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){const n=[];for(const i of r){if(i.status==="aborted")return hi;i.status==="dirty"&&e.dirty(),n.push(i.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){const n=[];for(const i of r){const o=await i.key,c=await i.value;n.push({key:o,value:c})}return Sd.mergeObjectSync(e,n)}static mergeObjectSync(e,r){const n={};for(const i of r){const{key:o,value:c}=i;if(o.status==="aborted"||c.status==="aborted")return hi;o.status==="dirty"&&e.dirty(),c.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof c.value<"u"||i.alwaysSet)&&(n[o.value]=c.value)}return{status:e.value,value:n}}}const hi=Object.freeze({status:"aborted"}),zC=t=>({status:"dirty",value:t}),xh=t=>({status:"valid",value:t}),xX=t=>t.status==="aborted",vX=t=>t.status==="dirty",B1=t=>t.status==="valid",AM=t=>typeof Promise<"u"&&t instanceof Promise;var cs;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(cs||(cs={}));class lx{constructor(e,r,n,i){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const _X=(t,e)=>{if(B1(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const r=new Sp(t.common.issues);return this._error=r,this._error}}};function Bi(t){if(!t)return{};const{errorMap:e,invalid_type_error:r,required_error:n,description:i}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(c,a)=>{const{message:m}=t;return c.code==="invalid_enum_value"?{message:m??a.defaultError}:typeof a.data>"u"?{message:m??n??a.defaultError}:c.code!=="invalid_type"?{message:a.defaultError}:{message:m??r??a.defaultError}},description:i}}class la{get description(){return this._def.description}_getType(e){return sy(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:sy(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Sd,ctx:{common:e.parent.common,data:e.data,parsedType:sy(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const r=this._parse(e);if(AM(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){const r=this._parse(e);return Promise.resolve(r)}parse(e,r){const n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){const n={common:{issues:[],async:(r==null?void 0:r.async)??!1,contextualErrorMap:r==null?void 0:r.errorMap},path:(r==null?void 0:r.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:sy(e)},i=this._parseSync({data:e,path:n.path,parent:n});return _X(n,i)}"~validate"(e){var n,i;const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:sy(e)};if(!this["~standard"].async)try{const o=this._parseSync({data:e,path:[],parent:r});return B1(o)?{value:o.value}:{issues:r.common.issues}}catch(o){(i=(n=o==null?void 0:o.message)==null?void 0:n.toLowerCase())!=null&&i.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(o=>B1(o)?{value:o.value}:{issues:r.common.issues})}async parseAsync(e,r){const n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){const n={common:{issues:[],contextualErrorMap:r==null?void 0:r.errorMap,async:!0},path:(r==null?void 0:r.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:sy(e)},i=this._parse({data:e,path:n.path,parent:n}),o=await(AM(i)?i:Promise.resolve(i));return _X(n,o)}refine(e,r){const n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,o)=>{const c=e(i),a=()=>o.addIssue({code:dn.custom,...n(i)});return typeof Promise<"u"&&c instanceof Promise?c.then(m=>m?!0:(a(),!1)):c?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,i)=>e(n)?!0:(i.addIssue(typeof r=="function"?r(n,i):r),!1))}_refinement(e){return new V1({schema:this,typeName:pi.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return Gy.create(this,this._def)}nullable(){return q1.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return yp.create(this)}promise(){return OM.create(this,this._def)}or(e){return IM.create([this,e],this._def)}and(e){return MM.create(this,e,this._def)}transform(e){return new V1({...Bi(this._def),schema:this,typeName:pi.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const r=typeof e=="function"?e:()=>e;return new _$({...Bi(this._def),innerType:this,defaultValue:r,typeName:pi.ZodDefault})}brand(){return new fDe({typeName:pi.ZodBranded,type:this,...Bi(this._def)})}catch(e){const r=typeof e=="function"?e:()=>e;return new b$({...Bi(this._def),innerType:this,catchValue:r,typeName:pi.ZodCatch})}describe(e){const r=this.constructor;return new r({...this._def,description:e})}pipe(e){return I8.create(this,e)}readonly(){return w$.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const HRe=/^c[^\s-]{8,}$/i,WRe=/^[0-9a-z]+$/,GRe=/^[0-9A-HJKMNP-TV-Z]{26}$/i,KRe=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,ZRe=/^[a-z0-9_-]{21}$/i,YRe=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,XRe=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,QRe=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,JRe="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let oz;const eDe=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,tDe=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,rDe=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,nDe=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,sDe=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,iDe=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Nue="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",aDe=new RegExp(`^${Nue}$`);function Cue(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);const r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function oDe(t){return new RegExp(`^${Cue(t)}$`)}function lDe(t){let e=`${Nue}T${Cue(t)}`;const r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function cDe(t,e){return!!((e==="v4"||!e)&&eDe.test(t)||(e==="v6"||!e)&&rDe.test(t))}function uDe(t,e){if(!YRe.test(t))return!1;try{const[r]=t.split(".");if(!r)return!1;const n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(n));return!(typeof i!="object"||i===null||"typ"in i&&(i==null?void 0:i.typ)!=="JWT"||!i.alg||e&&i.alg!==e)}catch{return!1}}function dDe(t,e){return!!((e==="v4"||!e)&&tDe.test(t)||(e==="v6"||!e)&&nDe.test(t))}class Py extends la{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==es.string){const o=this._getOrReturnCtx(e);return Rn(o,{code:dn.invalid_type,expected:es.string,received:o.parsedType}),hi}const n=new Sd;let i;for(const o of this._def.checks)if(o.kind==="min")e.data.lengtho.value&&(i=this._getOrReturnCtx(e,i),Rn(i,{code:dn.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){const c=e.data.length>o.value,a=e.data.lengthe.test(i),{validation:r,code:dn.invalid_string,...cs.errToObj(n)})}_addCheck(e){return new Py({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...cs.errToObj(e)})}url(e){return this._addCheck({kind:"url",...cs.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...cs.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...cs.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...cs.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...cs.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...cs.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...cs.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...cs.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...cs.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...cs.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...cs.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...cs.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(e==null?void 0:e.offset)??!1,local:(e==null?void 0:e.local)??!1,...cs.errToObj(e==null?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...cs.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...cs.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...cs.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r==null?void 0:r.position,...cs.errToObj(r==null?void 0:r.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...cs.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...cs.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...cs.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...cs.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...cs.errToObj(r)})}nonempty(e){return this.min(1,cs.errToObj(e))}trim(){return new Py({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Py({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Py({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.valuenew Py({checks:[],typeName:pi.ZodString,coerce:(t==null?void 0:t.coerce)??!1,...Bi(t)});function hDe(t,e){const r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=r>n?r:n,o=Number.parseInt(t.toFixed(i).replace(".","")),c=Number.parseInt(e.toFixed(i).replace(".",""));return o%c/10**i}class $1 extends la{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==es.number){const o=this._getOrReturnCtx(e);return Rn(o,{code:dn.invalid_type,expected:es.number,received:o.parsedType}),hi}let n;const i=new Sd;for(const o of this._def.checks)o.kind==="int"?ha.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),Rn(n,{code:dn.invalid_type,expected:"integer",received:"float",message:o.message}),i.dirty()):o.kind==="min"?(o.inclusive?e.datao.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),Rn(n,{code:dn.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?hDe(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),Rn(n,{code:dn.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),Rn(n,{code:dn.not_finite,message:o.message}),i.dirty()):ha.assertNever(o);return{status:i.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,cs.toString(r))}gt(e,r){return this.setLimit("min",e,!1,cs.toString(r))}lte(e,r){return this.setLimit("max",e,!0,cs.toString(r))}lt(e,r){return this.setLimit("max",e,!1,cs.toString(r))}setLimit(e,r,n,i){return new $1({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:cs.toString(i)}]})}_addCheck(e){return new $1({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:cs.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:cs.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:cs.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:cs.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:cs.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:cs.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:cs.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:cs.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:cs.toString(e)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.valuee.kind==="int"||e.kind==="multipleOf"&&ha.isInteger(e.value))}get isFinite(){let e=null,r=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.valuenew $1({checks:[],typeName:pi.ZodNumber,coerce:(t==null?void 0:t.coerce)||!1,...Bi(t)});class ik extends la{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==es.bigint)return this._getInvalidInput(e);let n;const i=new Sd;for(const o of this._def.checks)o.kind==="min"?(o.inclusive?e.datao.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),Rn(n,{code:dn.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),Rn(n,{code:dn.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):ha.assertNever(o);return{status:i.value,value:e.data}}_getInvalidInput(e){const r=this._getOrReturnCtx(e);return Rn(r,{code:dn.invalid_type,expected:es.bigint,received:r.parsedType}),hi}gte(e,r){return this.setLimit("min",e,!0,cs.toString(r))}gt(e,r){return this.setLimit("min",e,!1,cs.toString(r))}lte(e,r){return this.setLimit("max",e,!0,cs.toString(r))}lt(e,r){return this.setLimit("max",e,!1,cs.toString(r))}setLimit(e,r,n,i){return new ik({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:cs.toString(i)}]})}_addCheck(e){return new ik({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:cs.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:cs.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:cs.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:cs.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:cs.toString(r)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.valuenew ik({checks:[],typeName:pi.ZodBigInt,coerce:(t==null?void 0:t.coerce)??!1,...Bi(t)});class x$ extends la{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==es.boolean){const n=this._getOrReturnCtx(e);return Rn(n,{code:dn.invalid_type,expected:es.boolean,received:n.parsedType}),hi}return xh(e.data)}}x$.create=t=>new x$({typeName:pi.ZodBoolean,coerce:(t==null?void 0:t.coerce)||!1,...Bi(t)});class PM extends la{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==es.date){const o=this._getOrReturnCtx(e);return Rn(o,{code:dn.invalid_type,expected:es.date,received:o.parsedType}),hi}if(Number.isNaN(e.data.getTime())){const o=this._getOrReturnCtx(e);return Rn(o,{code:dn.invalid_date}),hi}const n=new Sd;let i;for(const o of this._def.checks)o.kind==="min"?e.data.getTime()o.value&&(i=this._getOrReturnCtx(e,i),Rn(i,{code:dn.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):ha.assertNever(o);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new PM({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:cs.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:cs.toString(r)})}get minDate(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.valuenew PM({checks:[],coerce:(t==null?void 0:t.coerce)||!1,typeName:pi.ZodDate,...Bi(t)});class bX extends la{_parse(e){if(this._getType(e)!==es.symbol){const n=this._getOrReturnCtx(e);return Rn(n,{code:dn.invalid_type,expected:es.symbol,received:n.parsedType}),hi}return xh(e.data)}}bX.create=t=>new bX({typeName:pi.ZodSymbol,...Bi(t)});class wX extends la{_parse(e){if(this._getType(e)!==es.undefined){const n=this._getOrReturnCtx(e);return Rn(n,{code:dn.invalid_type,expected:es.undefined,received:n.parsedType}),hi}return xh(e.data)}}wX.create=t=>new wX({typeName:pi.ZodUndefined,...Bi(t)});class jX extends la{_parse(e){if(this._getType(e)!==es.null){const n=this._getOrReturnCtx(e);return Rn(n,{code:dn.invalid_type,expected:es.null,received:n.parsedType}),hi}return xh(e.data)}}jX.create=t=>new jX({typeName:pi.ZodNull,...Bi(t)});class SX extends la{constructor(){super(...arguments),this._any=!0}_parse(e){return xh(e.data)}}SX.create=t=>new SX({typeName:pi.ZodAny,...Bi(t)});class NX extends la{constructor(){super(...arguments),this._unknown=!0}_parse(e){return xh(e.data)}}NX.create=t=>new NX({typeName:pi.ZodUnknown,...Bi(t)});class cx extends la{_parse(e){const r=this._getOrReturnCtx(e);return Rn(r,{code:dn.invalid_type,expected:es.never,received:r.parsedType}),hi}}cx.create=t=>new cx({typeName:pi.ZodNever,...Bi(t)});class CX extends la{_parse(e){if(this._getType(e)!==es.undefined){const n=this._getOrReturnCtx(e);return Rn(n,{code:dn.invalid_type,expected:es.void,received:n.parsedType}),hi}return xh(e.data)}}CX.create=t=>new CX({typeName:pi.ZodVoid,...Bi(t)});class yp extends la{_parse(e){const{ctx:r,status:n}=this._processInputParams(e),i=this._def;if(r.parsedType!==es.array)return Rn(r,{code:dn.invalid_type,expected:es.array,received:r.parsedType}),hi;if(i.exactLength!==null){const c=r.data.length>i.exactLength.value,a=r.data.lengthi.maxLength.value&&(Rn(r,{code:dn.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((c,a)=>i.type._parseAsync(new lx(r,c,r.path,a)))).then(c=>Sd.mergeArray(n,c));const o=[...r.data].map((c,a)=>i.type._parseSync(new lx(r,c,r.path,a)));return Sd.mergeArray(n,o)}get element(){return this._def.type}min(e,r){return new yp({...this._def,minLength:{value:e,message:cs.toString(r)}})}max(e,r){return new yp({...this._def,maxLength:{value:e,message:cs.toString(r)}})}length(e,r){return new yp({...this._def,exactLength:{value:e,message:cs.toString(r)}})}nonempty(e){return this.min(1,e)}}yp.create=(t,e)=>new yp({type:t,minLength:null,maxLength:null,exactLength:null,typeName:pi.ZodArray,...Bi(e)});function bw(t){if(t instanceof hl){const e={};for(const r in t.shape){const n=t.shape[r];e[r]=Gy.create(bw(n))}return new hl({...t._def,shape:()=>e})}else return t instanceof yp?new yp({...t._def,type:bw(t.element)}):t instanceof Gy?Gy.create(bw(t.unwrap())):t instanceof q1?q1.create(bw(t.unwrap())):t instanceof D_?D_.create(t.items.map(e=>bw(e))):t}class hl extends la{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),r=ha.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==es.object){const g=this._getOrReturnCtx(e);return Rn(g,{code:dn.invalid_type,expected:es.object,received:g.parsedType}),hi}const{status:n,ctx:i}=this._processInputParams(e),{shape:o,keys:c}=this._getCached(),a=[];if(!(this._def.catchall instanceof cx&&this._def.unknownKeys==="strip"))for(const g in i.data)c.includes(g)||a.push(g);const m=[];for(const g of c){const _=o[g],j=i.data[g];m.push({key:{status:"valid",value:g},value:_._parse(new lx(i,j,i.path,g)),alwaysSet:g in i.data})}if(this._def.catchall instanceof cx){const g=this._def.unknownKeys;if(g==="passthrough")for(const _ of a)m.push({key:{status:"valid",value:_},value:{status:"valid",value:i.data[_]}});else if(g==="strict")a.length>0&&(Rn(i,{code:dn.unrecognized_keys,keys:a}),n.dirty());else if(g!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const g=this._def.catchall;for(const _ of a){const j=i.data[_];m.push({key:{status:"valid",value:_},value:g._parse(new lx(i,j,i.path,_)),alwaysSet:_ in i.data})}}return i.common.async?Promise.resolve().then(async()=>{const g=[];for(const _ of m){const j=await _.key,N=await _.value;g.push({key:j,value:N,alwaysSet:_.alwaysSet})}return g}).then(g=>Sd.mergeObjectSync(n,g)):Sd.mergeObjectSync(n,m)}get shape(){return this._def.shape()}strict(e){return cs.errToObj,new hl({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{var o,c;const i=((c=(o=this._def).errorMap)==null?void 0:c.call(o,r,n).message)??n.defaultError;return r.code==="unrecognized_keys"?{message:cs.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new hl({...this._def,unknownKeys:"strip"})}passthrough(){return new hl({...this._def,unknownKeys:"passthrough"})}extend(e){return new hl({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new hl({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:pi.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new hl({...this._def,catchall:e})}pick(e){const r={};for(const n of ha.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new hl({...this._def,shape:()=>r})}omit(e){const r={};for(const n of ha.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new hl({...this._def,shape:()=>r})}deepPartial(){return bw(this)}partial(e){const r={};for(const n of ha.objectKeys(this.shape)){const i=this.shape[n];e&&!e[n]?r[n]=i:r[n]=i.optional()}return new hl({...this._def,shape:()=>r})}required(e){const r={};for(const n of ha.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof Gy;)o=o._def.innerType;r[n]=o}return new hl({...this._def,shape:()=>r})}keyof(){return kue(ha.objectKeys(this.shape))}}hl.create=(t,e)=>new hl({shape:()=>t,unknownKeys:"strip",catchall:cx.create(),typeName:pi.ZodObject,...Bi(e)});hl.strictCreate=(t,e)=>new hl({shape:()=>t,unknownKeys:"strict",catchall:cx.create(),typeName:pi.ZodObject,...Bi(e)});hl.lazycreate=(t,e)=>new hl({shape:t,unknownKeys:"strip",catchall:cx.create(),typeName:pi.ZodObject,...Bi(e)});class IM extends la{_parse(e){const{ctx:r}=this._processInputParams(e),n=this._def.options;function i(o){for(const a of o)if(a.result.status==="valid")return a.result;for(const a of o)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;const c=o.map(a=>new Sp(a.ctx.common.issues));return Rn(r,{code:dn.invalid_union,unionErrors:c}),hi}if(r.common.async)return Promise.all(n.map(async o=>{const c={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:c}),ctx:c}})).then(i);{let o;const c=[];for(const m of n){const g={...r,common:{...r.common,issues:[]},parent:null},_=m._parseSync({data:r.data,path:r.path,parent:g});if(_.status==="valid")return _;_.status==="dirty"&&!o&&(o={result:_,ctx:g}),g.common.issues.length&&c.push(g.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;const a=c.map(m=>new Sp(m));return Rn(r,{code:dn.invalid_union,unionErrors:a}),hi}}get options(){return this._def.options}}IM.create=(t,e)=>new IM({options:t,typeName:pi.ZodUnion,...Bi(e)});function v$(t,e){const r=sy(t),n=sy(e);if(t===e)return{valid:!0,data:t};if(r===es.object&&n===es.object){const i=ha.objectKeys(e),o=ha.objectKeys(t).filter(a=>i.indexOf(a)!==-1),c={...t,...e};for(const a of o){const m=v$(t[a],e[a]);if(!m.valid)return{valid:!1};c[a]=m.data}return{valid:!0,data:c}}else if(r===es.array&&n===es.array){if(t.length!==e.length)return{valid:!1};const i=[];for(let o=0;o{if(xX(o)||xX(c))return hi;const a=v$(o.value,c.value);return a.valid?((vX(o)||vX(c))&&r.dirty(),{status:r.value,value:a.data}):(Rn(n,{code:dn.invalid_intersection_types}),hi)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([o,c])=>i(o,c)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}MM.create=(t,e,r)=>new MM({left:t,right:e,typeName:pi.ZodIntersection,...Bi(r)});class D_ extends la{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==es.array)return Rn(n,{code:dn.invalid_type,expected:es.array,received:n.parsedType}),hi;if(n.data.lengththis._def.items.length&&(Rn(n,{code:dn.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const o=[...n.data].map((c,a)=>{const m=this._def.items[a]||this._def.rest;return m?m._parse(new lx(n,c,n.path,a)):null}).filter(c=>!!c);return n.common.async?Promise.all(o).then(c=>Sd.mergeArray(r,c)):Sd.mergeArray(r,o)}get items(){return this._def.items}rest(e){return new D_({...this._def,rest:e})}}D_.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new D_({items:t,typeName:pi.ZodTuple,rest:null,...Bi(e)})};class kX extends la{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==es.map)return Rn(n,{code:dn.invalid_type,expected:es.map,received:n.parsedType}),hi;const i=this._def.keyType,o=this._def.valueType,c=[...n.data.entries()].map(([a,m],g)=>({key:i._parse(new lx(n,a,n.path,[g,"key"])),value:o._parse(new lx(n,m,n.path,[g,"value"]))}));if(n.common.async){const a=new Map;return Promise.resolve().then(async()=>{for(const m of c){const g=await m.key,_=await m.value;if(g.status==="aborted"||_.status==="aborted")return hi;(g.status==="dirty"||_.status==="dirty")&&r.dirty(),a.set(g.value,_.value)}return{status:r.value,value:a}})}else{const a=new Map;for(const m of c){const g=m.key,_=m.value;if(g.status==="aborted"||_.status==="aborted")return hi;(g.status==="dirty"||_.status==="dirty")&&r.dirty(),a.set(g.value,_.value)}return{status:r.value,value:a}}}}kX.create=(t,e,r)=>new kX({valueType:e,keyType:t,typeName:pi.ZodMap,...Bi(r)});class ak extends la{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==es.set)return Rn(n,{code:dn.invalid_type,expected:es.set,received:n.parsedType}),hi;const i=this._def;i.minSize!==null&&n.data.sizei.maxSize.value&&(Rn(n,{code:dn.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());const o=this._def.valueType;function c(m){const g=new Set;for(const _ of m){if(_.status==="aborted")return hi;_.status==="dirty"&&r.dirty(),g.add(_.value)}return{status:r.value,value:g}}const a=[...n.data.values()].map((m,g)=>o._parse(new lx(n,m,n.path,g)));return n.common.async?Promise.all(a).then(m=>c(m)):c(a)}min(e,r){return new ak({...this._def,minSize:{value:e,message:cs.toString(r)}})}max(e,r){return new ak({...this._def,maxSize:{value:e,message:cs.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}}ak.create=(t,e)=>new ak({valueType:t,minSize:null,maxSize:null,typeName:pi.ZodSet,...Bi(e)});class TX extends la{get schema(){return this._def.getter()}_parse(e){const{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}}TX.create=(t,e)=>new TX({getter:t,typeName:pi.ZodLazy,...Bi(e)});class EX extends la{_parse(e){if(e.data!==this._def.value){const r=this._getOrReturnCtx(e);return Rn(r,{received:r.data,code:dn.invalid_literal,expected:this._def.value}),hi}return{status:"valid",value:e.data}}get value(){return this._def.value}}EX.create=(t,e)=>new EX({value:t,typeName:pi.ZodLiteral,...Bi(e)});function kue(t,e){return new U1({values:t,typeName:pi.ZodEnum,...Bi(e)})}class U1 extends la{_parse(e){if(typeof e.data!="string"){const r=this._getOrReturnCtx(e),n=this._def.values;return Rn(r,{expected:ha.joinValues(n),received:r.parsedType,code:dn.invalid_type}),hi}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const r=this._getOrReturnCtx(e),n=this._def.values;return Rn(r,{received:r.data,code:dn.invalid_enum_value,options:n}),hi}return xh(e.data)}get options(){return this._def.values}get enum(){const e={};for(const r of this._def.values)e[r]=r;return e}get Values(){const e={};for(const r of this._def.values)e[r]=r;return e}get Enum(){const e={};for(const r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return U1.create(e,{...this._def,...r})}exclude(e,r=this._def){return U1.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}}U1.create=kue;class AX extends la{_parse(e){const r=ha.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==es.string&&n.parsedType!==es.number){const i=ha.objectValues(r);return Rn(n,{expected:ha.joinValues(i),received:n.parsedType,code:dn.invalid_type}),hi}if(this._cache||(this._cache=new Set(ha.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const i=ha.objectValues(r);return Rn(n,{received:n.data,code:dn.invalid_enum_value,options:i}),hi}return xh(e.data)}get enum(){return this._def.values}}AX.create=(t,e)=>new AX({values:t,typeName:pi.ZodNativeEnum,...Bi(e)});class OM extends la{unwrap(){return this._def.type}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==es.promise&&r.common.async===!1)return Rn(r,{code:dn.invalid_type,expected:es.promise,received:r.parsedType}),hi;const n=r.parsedType===es.promise?r.data:Promise.resolve(r.data);return xh(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}}OM.create=(t,e)=>new OM({type:t,typeName:pi.ZodPromise,...Bi(e)});class V1 extends la{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===pi.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:r,ctx:n}=this._processInputParams(e),i=this._def.effect||null,o={addIssue:c=>{Rn(n,c),c.fatal?r.abort():r.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),i.type==="preprocess"){const c=i.transform(n.data,o);if(n.common.async)return Promise.resolve(c).then(async a=>{if(r.value==="aborted")return hi;const m=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return m.status==="aborted"?hi:m.status==="dirty"||r.value==="dirty"?zC(m.value):m});{if(r.value==="aborted")return hi;const a=this._def.schema._parseSync({data:c,path:n.path,parent:n});return a.status==="aborted"?hi:a.status==="dirty"||r.value==="dirty"?zC(a.value):a}}if(i.type==="refinement"){const c=a=>{const m=i.refinement(a,o);if(n.common.async)return Promise.resolve(m);if(m instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){const a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?hi:(a.status==="dirty"&&r.dirty(),c(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?hi:(a.status==="dirty"&&r.dirty(),c(a.value).then(()=>({status:r.value,value:a.value}))))}if(i.type==="transform")if(n.common.async===!1){const c=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!B1(c))return hi;const a=i.transform(c.value,o);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(c=>B1(c)?Promise.resolve(i.transform(c.value,o)).then(a=>({status:r.value,value:a})):hi);ha.assertNever(i)}}V1.create=(t,e,r)=>new V1({schema:t,typeName:pi.ZodEffects,effect:e,...Bi(r)});V1.createWithPreprocess=(t,e,r)=>new V1({schema:e,effect:{type:"preprocess",transform:t},typeName:pi.ZodEffects,...Bi(r)});class Gy extends la{_parse(e){return this._getType(e)===es.undefined?xh(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Gy.create=(t,e)=>new Gy({innerType:t,typeName:pi.ZodOptional,...Bi(e)});class q1 extends la{_parse(e){return this._getType(e)===es.null?xh(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}q1.create=(t,e)=>new q1({innerType:t,typeName:pi.ZodNullable,...Bi(e)});class _$ extends la{_parse(e){const{ctx:r}=this._processInputParams(e);let n=r.data;return r.parsedType===es.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}}_$.create=(t,e)=>new _$({innerType:t,typeName:pi.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Bi(e)});class b$ extends la{_parse(e){const{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return AM(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Sp(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Sp(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}b$.create=(t,e)=>new b$({innerType:t,typeName:pi.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Bi(e)});class PX extends la{_parse(e){if(this._getType(e)!==es.nan){const n=this._getOrReturnCtx(e);return Rn(n,{code:dn.invalid_type,expected:es.nan,received:n.parsedType}),hi}return{status:"valid",value:e.data}}}PX.create=t=>new PX({typeName:pi.ZodNaN,...Bi(t)});class fDe extends la{_parse(e){const{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}}class I8 extends la{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?hi:o.status==="dirty"?(r.dirty(),zC(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{const i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?hi:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(e,r){return new I8({in:e,out:r,typeName:pi.ZodPipeline})}}class w$ extends la{_parse(e){const r=this._def.innerType._parse(e),n=i=>(B1(i)&&(i.value=Object.freeze(i.value)),i);return AM(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}}w$.create=(t,e)=>new w$({innerType:t,typeName:pi.ZodReadonly,...Bi(e)});var pi;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(pi||(pi={}));const id=Py.create,l2=$1.create,pDe=x$.create;cx.create;yp.create;const wD=hl.create;IM.create;MM.create;D_.create;const Tue=U1.create;OM.create;Gy.create;q1.create;const mDe=wD({email:id().email("Invalid email address"),password:id().min(6,"Password must be at least 6 characters")}),gDe=()=>{const{signIn:t,user:e}=rn(),r=Bs(),[n,i]=D.useState(!1),[o,c]=D.useState({}),[a,m]=D.useState(""),[g,_]=D.useState(!1),[j,N]=D.useState(!1);D.useEffect(()=>{e&&r("/dashboard")},[e,r]);const C=async A=>{A.preventDefault(),c({}),i(!0);const I=new FormData(A.currentTarget),O=I.get("email"),R=I.get("password");try{mDe.parse({email:O,password:R}),await t(O,R)}catch(z){if(z instanceof Sp){const W={};z.errors.forEach(V=>{V.path[0]&&(W[V.path[0]]=V.message)}),c(W)}}finally{i(!1)}},P=async()=>{if(!a){Dt.error("Please enter your email address");return}_(!0);try{const{error:A}=await ae.functions.invoke("send-password-reset",{body:{email:a,redirectTo:`${window.location.origin}/profile?reset=true`}});if(A)throw A;Dt.success("Password reset email sent! Check your inbox."),N(!1),m("")}catch(A){Dt.error(A.message||"Failed to send reset email")}finally{_(!1)}};return s.jsxs("div",{className:"min-h-screen relative overflow-hidden",children:[s.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-[#4a6b6d] via-[#3d5a5c] to-[#2a4347]",children:s.jsxs("div",{className:"absolute inset-0 opacity-30",children:[s.jsx("div",{className:"absolute top-0 left-0 w-96 h-96 bg-white/10 rounded-full blur-3xl animate-pulse"}),s.jsx("div",{className:"absolute bottom-0 right-0 w-96 h-96 bg-white/5 rounded-full blur-3xl animate-pulse",style:{animationDelay:"1s"}}),s.jsx("div",{className:"absolute top-1/2 left-1/2 w-64 h-64 bg-white/5 rounded-full blur-3xl animate-pulse",style:{animationDelay:"2s"}})]})}),s.jsxs("div",{className:"relative z-10 flex flex-col min-h-screen",children:[s.jsx("header",{className:"p-6",children:s.jsxs(jd,{to:"/",className:"inline-flex items-center gap-2 text-sm text-white/80 hover:text-white transition-colors",children:[s.jsx(Ka,{className:"h-4 w-4"}),"Back to Home"]})}),s.jsx("div",{className:"flex-1 flex items-center justify-center p-4",children:s.jsxs("div",{className:"w-full max-w-md",children:[s.jsx("div",{className:"flex justify-center mb-8",children:s.jsx("div",{className:"bg-white rounded-xl p-4 shadow-2xl",children:s.jsx("img",{src:kI,alt:"LevelUp",className:"h-12 w-auto"})})}),s.jsxs(at,{className:"border-0 shadow-2xl bg-white/95 backdrop-blur-sm",children:[s.jsxs(xr,{className:"space-y-1 text-center pb-4",children:[s.jsx(wr,{className:"text-3xl font-bold text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Welcome Back"}),s.jsx(us,{className:"text-gray-600",children:"Sign in to access your dashboard"})]}),s.jsx(ct,{children:s.jsxs("form",{onSubmit:C,className:"space-y-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"signin-email",className:"text-gray-700",children:"Email"}),s.jsx(Et,{id:"signin-email",name:"email",type:"email",placeholder:"your@email.com",required:!0,className:"border-gray-300 focus:border-[#4a6b6d] focus:ring-[#4a6b6d]"}),o.email&&s.jsx("p",{className:"text-sm text-red-600",children:o.email})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"signin-password",className:"text-gray-700",children:"Password"}),s.jsx(Et,{id:"signin-password",name:"password",type:"password",required:!0,className:"border-gray-300 focus:border-[#4a6b6d] focus:ring-[#4a6b6d]"}),o.password&&s.jsx("p",{className:"text-sm text-red-600",children:o.password})]}),s.jsx(de,{type:"submit",className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white font-semibold py-6 text-lg transition-all duration-200 shadow-lg hover:shadow-xl",disabled:n,children:n?"Signing in...":"Sign In"}),s.jsxs(mn,{open:j,onOpenChange:N,children:[s.jsx(Do,{asChild:!0,children:s.jsx(de,{variant:"link",className:"w-full text-sm text-[#4a6b6d] hover:text-[#3d5a5c]",children:"Forgot password?"})}),s.jsxs(pn,{className:"bg-white",children:[s.jsxs(xn,{children:[s.jsx(gn,{className:"text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Reset Password"}),s.jsx(fi,{className:"text-gray-600",children:"Enter your email address and we'll send you a link to reset your password."})]}),s.jsxs("div",{className:"space-y-4 pt-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"reset-email",className:"text-gray-700",children:"Email"}),s.jsx(Et,{id:"reset-email",type:"email",placeholder:"your@email.com",value:a,onChange:A=>m(A.target.value),className:"border-gray-300 focus:border-[#4a6b6d] focus:ring-[#4a6b6d]"})]}),s.jsx(de,{onClick:P,className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white",disabled:g,children:g?"Sending...":"Send Reset Link"})]})]})]})]})})]}),s.jsxs("p",{className:"text-center text-white/70 text-sm mt-6",children:["Don't have an account?"," ",s.jsx(jd,{to:"/",className:"text-white hover:underline font-medium",children:"View Plans"})]})]})})]})]})},yDe=()=>{const[t]=n0(),e=t.get("tier"),r=e==null?void 0:e.includes("brokerage");return s.jsx("div",{className:"min-h-screen bg-gradient-to-br from-background via-primary/5 to-secondary/10 flex items-center justify-center p-4",children:s.jsxs(at,{className:"max-w-lg w-full",children:[s.jsxs(xr,{className:"text-center",children:[s.jsx("div",{className:"mx-auto w-16 h-16 rounded-full bg-green-500/10 flex items-center justify-center mb-4",children:s.jsx(gc,{className:"w-10 h-10 text-green-500"})}),s.jsx(wr,{className:"text-2xl",children:"Welcome to LevelUp!"}),s.jsx(us,{className:"text-lg",children:"Your subscription has been activated successfully."})]}),s.jsxs(ct,{className:"space-y-6",children:[s.jsxs("div",{className:"p-4 rounded-lg bg-primary/10 border border-primary/20 space-y-2",children:[s.jsxs("div",{className:"flex items-center gap-2 text-primary",children:[s.jsx(Fo,{className:"w-5 h-5"}),s.jsx("span",{className:"font-semibold",children:"Check your email to sign in"})]}),s.jsx("p",{className:"text-sm text-muted-foreground",children:"We've sent you an email with a secure link to access your account. Click the link in your email to get started."})]}),r?s.jsxs("div",{className:"space-y-3",children:[s.jsx("h3",{className:"font-semibold",children:"What's next?"}),s.jsxs("ul",{className:"space-y-2 text-sm text-muted-foreground",children:[s.jsxs("li",{className:"flex items-start gap-2",children:[s.jsx("span",{className:"font-bold text-primary",children:"1."}),"Click the link in your email to sign in"]}),s.jsxs("li",{className:"flex items-start gap-2",children:[s.jsx("span",{className:"font-bold text-primary",children:"2."}),"Create and name your brokerage"]}),s.jsxs("li",{className:"flex items-start gap-2",children:[s.jsx("span",{className:"font-bold text-primary",children:"3."}),"Set your password and complete your profile"]}),s.jsxs("li",{className:"flex items-start gap-2",children:[s.jsx("span",{className:"font-bold text-primary",children:"4."}),"Start inviting agents to join your team"]})]})]}):s.jsxs("div",{className:"space-y-3",children:[s.jsx("h3",{className:"font-semibold",children:"What's next?"}),s.jsxs("ul",{className:"space-y-2 text-sm text-muted-foreground",children:[s.jsxs("li",{className:"flex items-start gap-2",children:[s.jsx("span",{className:"font-bold text-primary",children:"1."}),"Click the link in your email to sign in"]}),s.jsxs("li",{className:"flex items-start gap-2",children:[s.jsx("span",{className:"font-bold text-primary",children:"2."}),"Set your password and complete your profile"]}),s.jsxs("li",{className:"flex items-start gap-2",children:[s.jsx("span",{className:"font-bold text-primary",children:"3."}),"Start exploring templates, training videos, and more!"]})]}),s.jsx("p",{className:"text-sm text-green-600 font-medium mt-4",children:"🎉 Your 7-day free trial has started!"})]}),s.jsx("div",{className:"p-3 rounded-lg bg-muted/50 text-center",children:s.jsx("p",{className:"text-sm text-muted-foreground",children:"Didn't receive the email? Check your spam folder or contact support."})})]})]})})},xDe=()=>{const{user:t,loading:e,isBrokerageManager:r,brokerageId:n}=rn(),i=Bs(),[o,c]=D.useState(""),[a,m]=D.useState(!1),[g,_]=D.useState(!1);D.useEffect(()=>{!e&&!t&&i("/auth")},[t,e,i]),D.useEffect(()=>{!e&&t&&n&&i("/profile?setup=true")},[t,e,n,i]);const j=async()=>{if(!o.trim()){Dt.error("Please enter a brokerage name");return}const{data:N}=await ae.auth.getSession(),C=N.session;if(!t||!C){Dt.error("Please sign in again to create your brokerage."),i("/auth");return}m(!0);try{console.log("[SetupBrokerage] Creating brokerage…",{hasUser:!!t,hasSession:!!C,userId:t==null?void 0:t.id});const{data:P,error:A}=await ae.functions.invoke("create-brokerage",{body:{name:o.trim()}});if(console.log("[SetupBrokerage] create-brokerage response",{data:P,error:A}),A)throw A;if(!(P!=null&&P.ok))throw new Error((P==null?void 0:P.error)||"Failed to create brokerage");m(!1),_(!0),Dt.success("Brokerage created! Setting up your account..."),setTimeout(()=>{i("/profile?setup=true")},2e3)}catch(P){console.error("Error creating brokerage:",P),Dt.error(P.message||"Failed to create brokerage"),m(!1)}};return e?s.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):g?s.jsx("div",{className:"min-h-screen bg-gradient-to-br from-background via-primary/5 to-secondary/10 flex items-center justify-center p-4",children:s.jsxs(at,{className:"max-w-lg w-full",children:[s.jsxs(xr,{className:"text-center",children:[s.jsx("div",{className:"mx-auto w-16 h-16 rounded-full bg-primary/10 flex items-center justify-center mb-4",children:s.jsx(Ps,{className:"w-10 h-10 text-primary animate-spin"})}),s.jsx(wr,{className:"text-2xl",children:"Setting Up Your Brokerage"}),s.jsx(us,{className:"text-lg",children:"We're assigning you as the brokerage manager and preparing your dashboard..."})]}),s.jsxs(ct,{className:"space-y-4",children:[s.jsxs("div",{className:"flex items-center justify-center gap-2 text-muted-foreground",children:[s.jsx(gc,{className:"w-5 h-5 text-green-500"}),s.jsx("span",{children:"Brokerage created"})]}),s.jsxs("div",{className:"flex items-center justify-center gap-2 text-muted-foreground",children:[s.jsx(Ps,{className:"w-5 h-5 animate-spin text-primary"}),s.jsx("span",{children:"Assigning you as manager..."})]}),s.jsx("p",{className:"text-center text-sm text-muted-foreground mt-4",children:"You'll be redirected to complete your profile setup in a moment."})]})]})}):s.jsx("div",{className:"min-h-screen bg-gradient-to-br from-background via-primary/5 to-secondary/10 flex items-center justify-center p-4",children:s.jsxs(at,{className:"max-w-lg w-full",children:[s.jsxs(xr,{className:"text-center",children:[s.jsx("div",{className:"mx-auto w-16 h-16 rounded-full bg-primary/10 flex items-center justify-center mb-4",children:s.jsx(yc,{className:"w-10 h-10 text-primary"})}),s.jsx(wr,{className:"text-2xl",children:"Set Up Your Brokerage"}),s.jsx(us,{className:"text-lg",children:"Create your brokerage to start managing your team"})]}),s.jsxs(ct,{className:"space-y-6",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"brokerage-name",children:"Brokerage Name"}),s.jsx(Et,{id:"brokerage-name",placeholder:"Enter your brokerage name",value:o,onChange:N=>c(N.target.value),onKeyDown:N=>N.key==="Enter"&&j()}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"This is how your brokerage will appear to your agents"})]}),s.jsxs("div",{className:"p-4 rounded-lg bg-muted/50 space-y-3",children:[s.jsxs("h3",{className:"font-semibold flex items-center gap-2",children:[s.jsx(_i,{className:"w-4 h-4 text-primary"}),"What you can do as a Brokerage Manager:"]}),s.jsxs("ul",{className:"space-y-2 text-sm text-muted-foreground",children:[s.jsxs("li",{className:"flex items-center gap-2",children:[s.jsx(gc,{className:"w-4 h-4 text-green-500"}),"Invite agents to join your brokerage"]}),s.jsxs("li",{className:"flex items-center gap-2",children:[s.jsx(gc,{className:"w-4 h-4 text-green-500"}),"Access exclusive brokerage resources"]}),s.jsxs("li",{className:"flex items-center gap-2",children:[s.jsx(gc,{className:"w-4 h-4 text-green-500"}),"Track your team's activity and engagement"]}),s.jsxs("li",{className:"flex items-center gap-2",children:[s.jsx(gc,{className:"w-4 h-4 text-green-500"}),"Share resources with your agents"]})]})]}),s.jsxs(de,{onClick:j,className:"w-full",disabled:a||!o.trim(),children:[a?"Creating...":"Create Brokerage",s.jsx(cd,{className:"w-4 h-4 ml-2"})]})]})]})})},vDe=()=>{const t=Bs(),[e,r]=D.useState("verifying"),[n,i]=D.useState("");return D.useEffect(()=>{(async()=>{try{const{data:{session:c},error:a}=await ae.auth.getSession();if(a)throw a;if(c!=null&&c.user){console.log("User logged in successfully:",c.user.email),r("success");try{await ae.functions.invoke("trial-claim-hook",{body:{userId:c.user.id}})}catch(m){console.log("Trial claim hook (non-critical):",m)}setTimeout(()=>{t("/profile?setup=true")},1500)}else setTimeout(()=>{r("error"),i("Invalid claim link")},2e3)}catch(c){console.error("Claim error:",c),r("error"),i(c.message||"Failed to claim account")}})()},[t]),s.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background p-4",children:s.jsxs(at,{className:"w-full max-w-md",children:[s.jsxs(xr,{className:"space-y-1 text-center",children:[s.jsxs("div",{className:"mx-auto mb-4 flex h-16 w-16 items-center justify-center rounded-full bg-primary/10",children:[e==="verifying"&&s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"}),e==="success"&&s.jsx("svg",{className:"h-8 w-8 text-primary",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),e==="error"&&s.jsx("svg",{className:"h-8 w-8 text-destructive",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})]}),s.jsxs(wr,{className:"text-2xl",children:[e==="verifying"&&"Claiming Your Account...",e==="success"&&"Account Claimed!",e==="error"&&"Claim Failed"]}),s.jsxs(us,{children:[e==="verifying"&&"Please wait while we verify your account...",e==="success"&&"Redirecting you to complete your profile...",e==="error"&&n]})]}),e==="error"&&s.jsx(ct,{children:s.jsx("button",{onClick:()=>t("/auth"),className:"w-full rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90",children:"Go to Login"})})]})})},_De=()=>{const t=Bs(),[e]=n0(),[r,n]=D.useState(e.get("code")||""),[i,o]=D.useState(""),[c,a]=D.useState(""),[m,g]=D.useState(""),[_,j]=D.useState(!1),[N,C]=D.useState(!1),[P,A]=D.useState(!1),[I,O]=D.useState(!1),[R,z]=D.useState(null),[W,V]=D.useState(null),[K,Q]=D.useState(null);D.useEffect(()=>{const he=e.get("code");he&&(n(he),te(he))},[e]);const te=async he=>{A(!0);const{data:xe,error:pe}=await ae.from("invite_codes").select("id, code, max_uses, uses_count, expires_at, is_active, brokerage_id").eq("code",he.toUpperCase().trim()).single();if(pe||!xe){Dt.error("Invalid invite code"),A(!1);return}if(!xe.is_active){Dt.error("This invite code is no longer active"),A(!1);return}if(xe.max_uses&&xe.uses_count>=xe.max_uses){Dt.error("This invite code has reached its maximum uses"),A(!1);return}if(xe.expires_at&&new Date(xe.expires_at){he.preventDefault(),te(r)},ie=async he=>{var xe;if(he.preventDefault(),!m.trim()){Dt.error("Please enter your name");return}if(c.length<6){Dt.error("Password must be at least 6 characters");return}C(!0);try{const pe=`${window.location.origin}/`,{data:ve,error:ge}=await ae.auth.signUp({email:i.trim(),password:c,options:{emailRedirectTo:pe,data:{name:m.trim()}}});if(ge){ge.message.includes("already registered")?Dt.error("This email is already registered. Please sign in instead."):Dt.error(ge.message);return}ve.user&&(await ae.rpc("add_default_signup_tag",{user_id:ve.user.id}),W?await ae.functions.invoke("assign-brokerage",{body:{userId:ve.user.id,brokerageId:W}}):await ae.functions.invoke("assign-brokerage",{body:{userId:ve.user.id,grandfathered:!0}}),R&&await ae.from("invite_codes").update({uses_count:((xe=(await ae.from("invite_codes").select("uses_count").eq("id",R).single()).data)==null?void 0:xe.uses_count)+1}).eq("id",R),Dt.success("Account created! You can now access the dashboard."),t("/dashboard"))}catch(pe){console.error("Signup error:",pe),Dt.error("An unexpected error occurred")}finally{C(!1)}};return s.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:s.jsxs(at,{className:"w-full max-w-md",children:[s.jsxs(xr,{className:"text-center",children:[s.jsx(wr,{className:"text-2xl font-bold text-primary",children:K?`Join ${K}`:"Join LevelUp"}),s.jsx(us,{children:I?K?`Create your account to join ${K}`:"Create your account to get started":"Enter your invite code to continue"})]}),s.jsx(ct,{children:I?s.jsxs("form",{onSubmit:ie,className:"space-y-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"name",children:"Full Name"}),s.jsx(Et,{id:"name",type:"text",placeholder:"John Doe",value:m,onChange:he=>g(he.target.value),required:!0})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"email",children:"Email"}),s.jsx(Et,{id:"email",type:"email",placeholder:"you@example.com",value:i,onChange:he=>o(he.target.value),required:!0})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"password",children:"Password"}),s.jsxs("div",{className:"relative",children:[s.jsx(Et,{id:"password",type:_?"text":"password",placeholder:"••••••••",value:c,onChange:he=>a(he.target.value),required:!0,minLength:6}),s.jsx("button",{type:"button",className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",onClick:()=>j(!_),children:_?s.jsx(Z6,{className:"h-4 w-4"}):s.jsx(Rc,{className:"h-4 w-4"})})]})]}),s.jsx(de,{type:"submit",className:"w-full",disabled:N,children:N?s.jsxs(s.Fragment,{children:[s.jsx(Ps,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating Account..."]}):"Create Account"})]}):s.jsxs("form",{onSubmit:X,className:"space-y-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"inviteCode",children:"Invite Code"}),s.jsx(Et,{id:"inviteCode",type:"text",placeholder:"Enter your invite code",value:r,onChange:he=>n(he.target.value),required:!0,autoFocus:!0})]}),s.jsx(de,{type:"submit",className:"w-full",disabled:P,children:P?s.jsxs(s.Fragment,{children:[s.jsx(Ps,{className:"mr-2 h-4 w-4 animate-spin"}),"Verifying..."]}):"Verify Code"})]})})]})})};var Eue={exports:{}},Aue={};/** * @license React * use-sync-external-store-shim.production.js * * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var H1=D;function bDe(t,e){return t===e&&(t!==0||1/t===1/e)||t!==t&&e!==e}var wDe=typeof Object.is=="function"?Object.is:bDe,jDe=H1.useState,SDe=H1.useEffect,NDe=H1.useLayoutEffect,CDe=H1.useDebugValue;function kDe(t,e){var r=e(),n=jDe({inst:{value:r,getSnapshot:e}}),i=n[0].inst,o=n[1];return NDe(function(){i.value=r,i.getSnapshot=e,lz(i)&&o({inst:i})},[t,r,e]),SDe(function(){return lz(i)&&o({inst:i}),t(function(){lz(i)&&o({inst:i})})},[t]),CDe(r),r}function lz(t){var e=t.getSnapshot;t=t.value;try{var r=e();return!wDe(t,r)}catch{return!0}}function TDe(t,e){return e()}var EDe=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?TDe:kDe;Aue.useSyncExternalStore=H1.useSyncExternalStore!==void 0?H1.useSyncExternalStore:EDe;Eue.exports=Aue;var ADe=Eue.exports;function PDe(){return ADe.useSyncExternalStore(IDe,()=>!0,()=>!1)}function IDe(){return()=>{}}var M8="Avatar",[MDe]=Yo(M8),[ODe,Pue]=MDe(M8),Iue=D.forwardRef((t,e)=>{const{__scopeAvatar:r,...n}=t,[i,o]=D.useState("idle");return s.jsx(ODe,{scope:r,imageLoadingStatus:i,onImageLoadingStatusChange:o,children:s.jsx(yn.span,{...n,ref:e})})});Iue.displayName=M8;var Mue="AvatarImage",Oue=D.forwardRef((t,e)=>{const{__scopeAvatar:r,src:n,onLoadingStatusChange:i=()=>{},...o}=t,c=Pue(Mue,r),a=RDe(n,o),m=Oo(g=>{i(g),c.onImageLoadingStatusChange(g)});return Lo(()=>{a!=="idle"&&m(a)},[a,m]),a==="loaded"?s.jsx(yn.img,{...o,ref:e,src:n}):null});Oue.displayName=Mue;var Rue="AvatarFallback",Due=D.forwardRef((t,e)=>{const{__scopeAvatar:r,delayMs:n,...i}=t,o=Pue(Rue,r),[c,a]=D.useState(n===void 0);return D.useEffect(()=>{if(n!==void 0){const m=window.setTimeout(()=>a(!0),n);return()=>window.clearTimeout(m)}},[n]),c&&o.imageLoadingStatus!=="loaded"?s.jsx(yn.span,{...i,ref:e}):null});Due.displayName=Rue;function IX(t,e){return t?e?(t.src!==e&&(t.src=e),t.complete&&t.naturalWidth>0?"loaded":"loading"):"error":"idle"}function RDe(t,{referrerPolicy:e,crossOrigin:r}){const n=PDe(),i=D.useRef(null),o=n?(i.current||(i.current=new window.Image),i.current):null,[c,a]=D.useState(()=>IX(o,t));return Lo(()=>{a(IX(o,t))},[o,t]),Lo(()=>{const m=j=>()=>{a(j)};if(!o)return;const g=m("loaded"),_=m("error");return o.addEventListener("load",g),o.addEventListener("error",_),e&&(o.referrerPolicy=e),typeof r=="string"&&(o.crossOrigin=r),()=>{o.removeEventListener("load",g),o.removeEventListener("error",_)}},[o,r,e]),c}var Lue=Iue,Fue=Oue,zue=Due;const ql=D.forwardRef(({className:t,...e},r)=>s.jsx(Lue,{ref:r,className:ar("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",t),...e}));ql.displayName=Lue.displayName;const Iy=D.forwardRef(({className:t,...e},r)=>s.jsx(Fue,{ref:r,className:ar("aspect-square h-full w-full",t),...e}));Iy.displayName=Fue.displayName;const Hl=D.forwardRef(({className:t,...e},r)=>s.jsx(zue,{ref:r,className:ar("flex h-full w-full items-center justify-center rounded-full bg-muted",t),...e}));Hl.displayName=zue.displayName;function DDe(){const{shareToken:t}=mu(),[e,r]=D.useState(null),[n,i]=D.useState(null),[o,c]=D.useState(null),[a,m]=D.useState(!0),[g,_]=D.useState(null),[j,N]=D.useState(!1);D.useEffect(()=>{(async()=>{if(!t){_("Invalid share link"),m(!1);return}const{data:z,error:W}=await ae.from("agent_videos").select("id, title, playback_url, thumbnail_url, preview_url, duration_seconds, share_token, owner_user_id").eq("share_token",t).eq("is_deleted",!1).single();if(W||!z){_("Video not found or has been removed"),m(!1);return}if(r(z),z.owner_user_id){const{data:V}=await ae.from("profiles").select("id, name, email, phone").eq("id",z.owner_user_id).single();if(V){i(V);try{const{data:K}=await ae.storage.from("avatars").list(`${z.owner_user_id}`);if(K&&K.length>0){const{data:Q}=ae.storage.from("avatars").getPublicUrl(`${z.owner_user_id}/${K[0].name}`);c(Q.publicUrl)}}catch{}}}m(!1)})()},[t]);const C=R=>{if(!R)return"0:00";const z=Math.floor(R/60),W=R%60;return`${z}:${W.toString().padStart(2,"0")}`},P=R=>R.includes("iframe.mediadelivery.net/play/")?R.replace("/play/","/embed/")+"?autoplay=true&responsive=true":R,A=R=>{if(!R)return"?";const z=R.split(" ");return z.length>=2?`${z[0][0]}${z[1][0]}`.toUpperCase():R.substring(0,2).toUpperCase()},O=`https://dashboard.relevelup.com/share/video/${t}`;return a?s.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center",children:s.jsx(Ps,{className:"h-8 w-8 animate-spin text-primary"})}):g||!e?s.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center p-4",children:s.jsx(at,{className:"max-w-md w-full",children:s.jsxs(ct,{className:"py-12 text-center",children:[s.jsx(Ia,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),s.jsx("h2",{className:"text-xl font-semibold mb-2",children:"Video Not Found"}),s.jsx("p",{className:"text-muted-foreground",children:g||"This video is no longer available."})]})})}):s.jsxs(s.Fragment,{children:[s.jsxs(tIe,{children:[s.jsx("title",{children:"Watch this video"}),s.jsx("meta",{name:"description",content:"Check out this personalized video message!"}),s.jsx("meta",{property:"og:title",content:e.title||"Video Message"}),s.jsx("meta",{property:"og:description",content:"Check out this personalized video message!"}),s.jsx("meta",{property:"og:type",content:"video.other"}),s.jsx("meta",{property:"og:url",content:O}),e.preview_url&&s.jsx("meta",{property:"og:image",content:e.preview_url}),!e.preview_url&&e.thumbnail_url&&s.jsx("meta",{property:"og:image",content:e.thumbnail_url}),e.playback_url&&s.jsxs(s.Fragment,{children:[s.jsx("meta",{property:"og:video",content:e.playback_url}),s.jsx("meta",{property:"og:video:type",content:"text/html"}),s.jsx("meta",{property:"og:video:width",content:"1280"}),s.jsx("meta",{property:"og:video:height",content:"720"})]}),s.jsx("meta",{name:"twitter:card",content:"player"}),s.jsx("meta",{name:"twitter:title",content:e.title||"Video Message"}),s.jsx("meta",{name:"twitter:description",content:"Check out this personalized video message!"}),e.preview_url&&s.jsx("meta",{name:"twitter:image",content:e.preview_url}),e.playback_url&&s.jsxs(s.Fragment,{children:[s.jsx("meta",{name:"twitter:player",content:e.playback_url}),s.jsx("meta",{name:"twitter:player:width",content:"1280"}),s.jsx("meta",{name:"twitter:player:height",content:"720"})]})]}),s.jsx("div",{className:"min-h-screen bg-gradient-to-b from-background to-muted/30 flex items-center justify-center p-4",children:s.jsxs("div",{className:"max-w-2xl w-full space-y-6",children:[n&&s.jsxs("div",{className:"flex items-center gap-4 p-4 bg-card rounded-lg border shadow-sm",children:[s.jsxs(ql,{className:"h-14 w-14 border-2 border-primary/20",children:[s.jsx(Iy,{src:o||void 0,alt:n.name||"Agent"}),s.jsx(Hl,{className:"bg-primary/10 text-primary font-semibold",children:A(n.name)})]}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("p",{className:"text-sm text-muted-foreground",children:"A personal video from"}),s.jsx("h2",{className:"text-lg font-semibold truncate",children:n.name||"Your Agent"}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Your Real Estate Professional"})]}),s.jsxs("div",{className:"flex gap-2 shrink-0",children:[n.phone&&s.jsx(de,{variant:"outline",size:"icon",asChild:!0,className:"h-10 w-10",children:s.jsx("a",{href:`tel:${n.phone}`,"aria-label":"Call agent",children:s.jsx(Yl,{className:"h-4 w-4"})})}),n.email&&s.jsx(de,{variant:"outline",size:"icon",asChild:!0,className:"h-10 w-10",children:s.jsx("a",{href:`mailto:${n.email}`,"aria-label":"Email agent",children:s.jsx(Fo,{className:"h-4 w-4"})})})]})]}),s.jsx(at,{className:"overflow-hidden",children:j&&e.playback_url?s.jsx("div",{className:"relative w-full",style:{paddingBottom:"56.25%"},children:s.jsx("iframe",{src:P(e.playback_url),title:e.title||"Video message",className:"absolute top-0 left-0 w-full h-full",style:{border:0},allow:"accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture",allowFullScreen:!0})}):s.jsxs("div",{className:"relative aspect-video bg-muted cursor-pointer group",onClick:()=>N(!0),children:[e.preview_url||e.thumbnail_url?s.jsx("img",{src:e.preview_url||e.thumbnail_url||"",alt:e.title?`${e.title} video preview`:"Video message preview",className:"w-full h-full object-cover",onError:R=>{var W;R.currentTarget.style.display="none";const z=(W=R.currentTarget.parentElement)==null?void 0:W.querySelector(".video-fallback");z&&(z.style.display="flex")}}):null,s.jsx("div",{className:"video-fallback w-full h-full items-center justify-center bg-gradient-to-br from-primary/20 to-primary/5",style:{display:e.preview_url||e.thumbnail_url?"none":"flex"},children:s.jsx(Ia,{className:"h-16 w-16 text-primary/50"})}),s.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/30 group-hover:bg-black/40 transition-colors",children:s.jsx("div",{className:"w-20 h-20 rounded-full bg-white/90 flex items-center justify-center shadow-lg transform group-hover:scale-105 transition-transform",children:s.jsx(Sf,{className:"h-10 w-10 text-primary ml-1"})})}),e.duration_seconds&&s.jsx("div",{className:"absolute bottom-3 right-3 bg-black/70 text-white text-sm px-2 py-1 rounded",children:C(e.duration_seconds)})]})}),s.jsxs("div",{className:"text-center",children:[s.jsx("h1",{className:"text-2xl font-bold",children:e.title||"Video Message"}),s.jsx("p",{className:"text-muted-foreground mt-2",children:j?"Enjoy the video!":"Click to play the video"})]}),!j&&s.jsx("div",{className:"flex justify-center",children:s.jsxs(de,{size:"lg",onClick:()=>N(!0),className:"gap-2",children:[s.jsx(Sf,{className:"h-5 w-5"}),"Watch Video"]})})]})})]})}function LDe(){const{token:t}=mu();return D.useEffect(()=>{if(!t)return;const e=`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/video-og-image?token=${t}`;window.location.replace(e)},[t]),s.jsx("main",{className:"min-h-screen bg-background flex items-center justify-center",children:s.jsxs("div",{className:"flex items-center gap-3 text-muted-foreground",children:[s.jsx(Ps,{className:"h-5 w-5 animate-spin"}),s.jsx("span",{children:"Loading video preview…"})]})})}const Bue=t=>{const[e,r]=D.useState(null),[n,i]=D.useState(!0);return D.useEffect(()=>{if(!t){i(!1);return}(async()=>{try{const{data:a}=await ae.storage.from("avatars").list(`${t}`);if(a&&a.length>0){const{data:m}=ae.storage.from("avatars").getPublicUrl(`${t}/${a[0].name}`);r(`${m.publicUrl}?t=${Date.now()}`)}else r(null)}catch(a){console.error("Error fetching avatar:",a),r(null)}finally{i(!1)}})()},[t]),{avatarUrl:e,loading:n,refreshAvatar:async()=>{if(t)try{const{data:c}=await ae.storage.from("avatars").list(`${t}`);if(c&&c.length>0){const{data:a}=ae.storage.from("avatars").getPublicUrl(`${t}/${c[0].name}`);r(`${a.publicUrl}?t=${Date.now()}`)}}catch(c){console.error("Error refreshing avatar:",c)}}}},MX=async t=>{const e=new Map;return await Promise.all(t.map(async r=>{try{const{data:n}=await ae.storage.from("avatars").list(`${r}`);if(n&&n.length>0){const{data:i}=ae.storage.from("avatars").getPublicUrl(`${r}/${n[0].name}`);e.set(r,i.publicUrl)}}catch{}})),e},FDe=t=>{const[e,r]=D.useState({isTrial:!1,isExpired:!1,expiresAt:null,daysLeft:null,loading:!0});return D.useEffect(()=>{if(!t){r(i=>({...i,loading:!1}));return}(async()=>{try{const{data:i,error:o}=await ae.from("profiles").select("is_trial, trial_expires_at, subscription_status, subscription_end_date").eq("id",t).single();if(o){console.error("Error fetching trial status:",o),r(m=>({...m,loading:!1}));return}const c=(i==null?void 0:i.subscription_status)==="trialing"&&(i==null?void 0:i.subscription_end_date),a=(i==null?void 0:i.is_trial)&&(i==null?void 0:i.trial_expires_at);if(c){const m=new Date().getTime(),g=new Date(i.subscription_end_date).getTime(),_=Math.ceil((g-m)/(1e3*60*60*24)),j=_<=0;r({isTrial:!0,isExpired:j,expiresAt:i.subscription_end_date,daysLeft:j?0:_,loading:!1})}else if(a){const m=new Date().getTime(),g=new Date(i.trial_expires_at).getTime(),_=Math.ceil((g-m)/(1e3*60*60*24)),j=_<=0;r({isTrial:!0,isExpired:j,expiresAt:i.trial_expires_at,daysLeft:j?0:_,loading:!1})}else r({isTrial:!1,isExpired:!1,expiresAt:null,daysLeft:null,loading:!1})}catch(i){console.error("Error in useTrialStatus:",i),r(o=>({...o,loading:!1}))}})()},[t]),e},$ue=()=>{const{data:t,isLoading:e}=Sr({queryKey:["feature-flags"],queryFn:async()=>{const{data:n,error:i}=await ae.from("feature_flags").select("*");if(i)throw i;return n}}),r=n=>{if(!t)return!1;const i=t.find(o=>o.key===n);return(i==null?void 0:i.enabled)??!1};return{flags:t,isLoading:e,isFeatureEnabled:r,isAgentOSEnabled:r("agent_os_enabled"),isInnerCircleEnabled:r("innercircle_enabled")}},Uue=vD,Vue=P8,zDe=_D,que=D.forwardRef(({className:t,...e},r)=>s.jsx(Bj,{className:ar("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",t),...e,ref:r}));que.displayName=Bj.displayName;const BDe=Ej("fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),O8=D.forwardRef(({side:t="right",className:e,children:r,...n},i)=>s.jsxs(zDe,{children:[s.jsx(que,{}),s.jsxs($j,{ref:i,className:ar(BDe({side:t}),e),...n,children:[r,s.jsxs(bD,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity data-[state=open]:bg-secondary hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none",children:[s.jsx(Ni,{className:"h-4 w-4"}),s.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));O8.displayName=$j.displayName;const Hue=({className:t,...e})=>s.jsx("div",{className:ar("flex flex-col space-y-2 text-center sm:text-left",t),...e});Hue.displayName="SheetHeader";const Wue=D.forwardRef(({className:t,...e},r)=>s.jsx(NT,{ref:r,className:ar("text-lg font-semibold text-foreground",t),...e}));Wue.displayName=NT.displayName;const $De=D.forwardRef(({className:t,...e},r)=>s.jsx(CT,{ref:r,className:ar("text-sm text-muted-foreground",t),...e}));$De.displayName=CT.displayName;var UDe=D.createContext(void 0);function i0(t){const e=D.useContext(UDe);return t||e||"ltr"}var cz="rovingFocusGroup.onEntryFocus",VDe={bubbles:!1,cancelable:!0},kT="RovingFocusGroup",[j$,Gue,qDe]=hT(kT),[HDe,Uj]=Yo(kT,[qDe]),[WDe,GDe]=HDe(kT),Kue=D.forwardRef((t,e)=>s.jsx(j$.Provider,{scope:t.__scopeRovingFocusGroup,children:s.jsx(j$.Slot,{scope:t.__scopeRovingFocusGroup,children:s.jsx(KDe,{...t,ref:e})})}));Kue.displayName=kT;var KDe=D.forwardRef((t,e)=>{const{__scopeRovingFocusGroup:r,orientation:n,loop:i=!1,dir:o,currentTabStopId:c,defaultCurrentTabStopId:a,onCurrentTabStopIdChange:m,onEntryFocus:g,preventScrollOnEntryFocus:_=!1,...j}=t,N=D.useRef(null),C=vs(e,N),P=i0(o),[A,I]=Uu({prop:c,defaultProp:a??null,onChange:m,caller:kT}),[O,R]=D.useState(!1),z=Oo(g),W=Gue(r),V=D.useRef(!1),[K,Q]=D.useState(0);return D.useEffect(()=>{const te=N.current;if(te)return te.addEventListener(cz,z),()=>te.removeEventListener(cz,z)},[z]),s.jsx(WDe,{scope:r,orientation:n,dir:P,loop:i,currentTabStopId:A,onItemFocus:D.useCallback(te=>I(te),[I]),onItemShiftTab:D.useCallback(()=>R(!0),[]),onFocusableItemAdd:D.useCallback(()=>Q(te=>te+1),[]),onFocusableItemRemove:D.useCallback(()=>Q(te=>te-1),[]),children:s.jsx(yn.div,{tabIndex:O||K===0?-1:0,"data-orientation":n,...j,ref:C,style:{outline:"none",...t.style},onMouseDown:Yr(t.onMouseDown,()=>{V.current=!0}),onFocus:Yr(t.onFocus,te=>{const X=!V.current;if(te.target===te.currentTarget&&X&&!O){const ie=new CustomEvent(cz,VDe);if(te.currentTarget.dispatchEvent(ie),!ie.defaultPrevented){const he=W().filter(ke=>ke.focusable),xe=he.find(ke=>ke.active),pe=he.find(ke=>ke.id===A),ge=[xe,pe,...he].filter(Boolean).map(ke=>ke.ref.current);Xue(ge,_)}}V.current=!1}),onBlur:Yr(t.onBlur,()=>R(!1))})})}),Zue="RovingFocusGroupItem",Yue=D.forwardRef((t,e)=>{const{__scopeRovingFocusGroup:r,focusable:n=!0,active:i=!1,tabStopId:o,children:c,...a}=t,m=Al(),g=o||m,_=GDe(Zue,r),j=_.currentTabStopId===g,N=Gue(r),{onFocusableItemAdd:C,onFocusableItemRemove:P,currentTabStopId:A}=_;return D.useEffect(()=>{if(n)return C(),()=>P()},[n,C,P]),s.jsx(j$.ItemSlot,{scope:r,id:g,focusable:n,active:i,children:s.jsx(yn.span,{tabIndex:j?0:-1,"data-orientation":_.orientation,...a,ref:e,onMouseDown:Yr(t.onMouseDown,I=>{n?_.onItemFocus(g):I.preventDefault()}),onFocus:Yr(t.onFocus,()=>_.onItemFocus(g)),onKeyDown:Yr(t.onKeyDown,I=>{if(I.key==="Tab"&&I.shiftKey){_.onItemShiftTab();return}if(I.target!==I.currentTarget)return;const O=XDe(I,_.orientation,_.dir);if(O!==void 0){if(I.metaKey||I.ctrlKey||I.altKey||I.shiftKey)return;I.preventDefault();let z=N().filter(W=>W.focusable).map(W=>W.ref.current);if(O==="last")z.reverse();else if(O==="prev"||O==="next"){O==="prev"&&z.reverse();const W=z.indexOf(I.currentTarget);z=_.loop?QDe(z,W+1):z.slice(W+1)}setTimeout(()=>Xue(z))}}),children:typeof c=="function"?c({isCurrentTabStop:j,hasTabStop:A!=null}):c})})});Yue.displayName=Zue;var ZDe={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function YDe(t,e){return e!=="rtl"?t:t==="ArrowLeft"?"ArrowRight":t==="ArrowRight"?"ArrowLeft":t}function XDe(t,e,r){const n=YDe(t.key,r);if(!(e==="vertical"&&["ArrowLeft","ArrowRight"].includes(n))&&!(e==="horizontal"&&["ArrowUp","ArrowDown"].includes(n)))return ZDe[n]}function Xue(t,e=!1){const r=document.activeElement;for(const n of t)if(n===r||(n.focus({preventScroll:e}),document.activeElement!==r))return}function QDe(t,e){return t.map((r,n)=>t[(e+n)%t.length])}var R8=Kue,D8=Yue,S$=["Enter"," "],JDe=["ArrowDown","PageUp","Home"],Que=["ArrowUp","PageDown","End"],eLe=[...JDe,...Que],tLe={ltr:[...S$,"ArrowRight"],rtl:[...S$,"ArrowLeft"]},rLe={ltr:["ArrowLeft"],rtl:["ArrowRight"]},TT="Menu",[ok,nLe,sLe]=hT(TT),[a0,Jue]=Yo(TT,[sLe,gx,Uj]),jD=gx(),ede=Uj(),[iLe,o0]=a0(TT),[aLe,ET]=a0(TT),tde=t=>{const{__scopeMenu:e,open:r=!1,children:n,dir:i,onOpenChange:o,modal:c=!0}=t,a=jD(e),[m,g]=D.useState(null),_=D.useRef(!1),j=Oo(o),N=i0(i);return D.useEffect(()=>{const C=()=>{_.current=!0,document.addEventListener("pointerdown",P,{capture:!0,once:!0}),document.addEventListener("pointermove",P,{capture:!0,once:!0})},P=()=>_.current=!1;return document.addEventListener("keydown",C,{capture:!0}),()=>{document.removeEventListener("keydown",C,{capture:!0}),document.removeEventListener("pointerdown",P,{capture:!0}),document.removeEventListener("pointermove",P,{capture:!0})}},[]),s.jsx(aD,{...a,children:s.jsx(iLe,{scope:e,open:r,onOpenChange:j,content:m,onContentChange:g,children:s.jsx(aLe,{scope:e,onClose:D.useCallback(()=>j(!1),[j]),isUsingKeyboardRef:_,dir:N,modal:c,children:n})})})};tde.displayName=TT;var oLe="MenuAnchor",L8=D.forwardRef((t,e)=>{const{__scopeMenu:r,...n}=t,i=jD(r);return s.jsx(bT,{...i,...n,ref:e})});L8.displayName=oLe;var F8="MenuPortal",[lLe,rde]=a0(F8,{forceMount:void 0}),nde=t=>{const{__scopeMenu:e,forceMount:r,children:n,container:i}=t,o=o0(F8,e);return s.jsx(lLe,{scope:e,forceMount:r,children:s.jsx(gl,{present:r||o.open,children:s.jsx(Tj,{asChild:!0,container:i,children:n})})})};nde.displayName=F8;var lh="MenuContent",[cLe,z8]=a0(lh),sde=D.forwardRef((t,e)=>{const r=rde(lh,t.__scopeMenu),{forceMount:n=r.forceMount,...i}=t,o=o0(lh,t.__scopeMenu),c=ET(lh,t.__scopeMenu);return s.jsx(ok.Provider,{scope:t.__scopeMenu,children:s.jsx(gl,{present:n||o.open,children:s.jsx(ok.Slot,{scope:t.__scopeMenu,children:c.modal?s.jsx(uLe,{...i,ref:e}):s.jsx(dLe,{...i,ref:e})})})})}),uLe=D.forwardRef((t,e)=>{const r=o0(lh,t.__scopeMenu),n=D.useRef(null),i=vs(e,n);return D.useEffect(()=>{const o=n.current;if(o)return yD(o)},[]),s.jsx(B8,{...t,ref:i,trapFocus:r.open,disableOutsidePointerEvents:r.open,disableOutsideScroll:!0,onFocusOutside:Yr(t.onFocusOutside,o=>o.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>r.onOpenChange(!1)})}),dLe=D.forwardRef((t,e)=>{const r=o0(lh,t.__scopeMenu);return s.jsx(B8,{...t,ref:e,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>r.onOpenChange(!1)})}),hLe=nx("MenuContent.ScrollLock"),B8=D.forwardRef((t,e)=>{const{__scopeMenu:r,loop:n=!1,trapFocus:i,onOpenAutoFocus:o,onCloseAutoFocus:c,disableOutsidePointerEvents:a,onEntryFocus:m,onEscapeKeyDown:g,onPointerDownOutside:_,onFocusOutside:j,onInteractOutside:N,onDismiss:C,disableOutsideScroll:P,...A}=t,I=o0(lh,r),O=ET(lh,r),R=jD(r),z=ede(r),W=nLe(r),[V,K]=D.useState(null),Q=D.useRef(null),te=vs(e,Q,I.onContentChange),X=D.useRef(0),ie=D.useRef(""),he=D.useRef(0),xe=D.useRef(null),pe=D.useRef("right"),ve=D.useRef(0),ge=P?ST:D.Fragment,ke=P?{as:hLe,allowPinchZoom:!0}:void 0,Ce=je=>{var gt,Me;const et=ie.current+je,bt=W().filter(Oe=>!Oe.disabled),_e=document.activeElement,Ye=(gt=bt.find(Oe=>Oe.ref.current===_e))==null?void 0:gt.textValue,pt=bt.map(Oe=>Oe.textValue),nt=SLe(pt,et,Ye),Qt=(Me=bt.find(Oe=>Oe.textValue===nt))==null?void 0:Me.ref.current;(function Oe(Ie){ie.current=Ie,window.clearTimeout(X.current),Ie!==""&&(X.current=window.setTimeout(()=>Oe(""),1e3))})(et),Qt&&setTimeout(()=>Qt.focus())};D.useEffect(()=>()=>window.clearTimeout(X.current),[]),mD();const Se=D.useCallback(je=>{var bt,_e;return pe.current===((bt=xe.current)==null?void 0:bt.side)&&CLe(je,(_e=xe.current)==null?void 0:_e.area)},[]);return s.jsx(cLe,{scope:r,searchRef:ie,onItemEnter:D.useCallback(je=>{Se(je)&&je.preventDefault()},[Se]),onItemLeave:D.useCallback(je=>{var et;Se(je)||((et=Q.current)==null||et.focus(),K(null))},[Se]),onTriggerLeave:D.useCallback(je=>{Se(je)&&je.preventDefault()},[Se]),pointerGraceTimerRef:he,onPointerGraceIntentChange:D.useCallback(je=>{xe.current=je},[]),children:s.jsx(ge,{...ke,children:s.jsx(jT,{asChild:!0,trapped:i,onMountAutoFocus:Yr(o,je=>{var et;je.preventDefault(),(et=Q.current)==null||et.focus({preventScroll:!0})}),onUnmountAutoFocus:c,children:s.jsx(t0,{asChild:!0,disableOutsidePointerEvents:a,onEscapeKeyDown:g,onPointerDownOutside:_,onFocusOutside:j,onInteractOutside:N,onDismiss:C,children:s.jsx(R8,{asChild:!0,...z,dir:O.dir,orientation:"vertical",loop:n,currentTabStopId:V,onCurrentTabStopIdChange:K,onEntryFocus:Yr(m,je=>{O.isUsingKeyboardRef.current||je.preventDefault()}),preventScrollOnEntryFocus:!0,children:s.jsx(oD,{role:"menu","aria-orientation":"vertical","data-state":_de(I.open),"data-radix-menu-content":"",dir:O.dir,...R,...A,ref:te,style:{outline:"none",...A.style},onKeyDown:Yr(A.onKeyDown,je=>{const bt=je.target.closest("[data-radix-menu-content]")===je.currentTarget,_e=je.ctrlKey||je.altKey||je.metaKey,Ye=je.key.length===1;bt&&(je.key==="Tab"&&je.preventDefault(),!_e&&Ye&&Ce(je.key));const pt=Q.current;if(je.target!==pt||!eLe.includes(je.key))return;je.preventDefault();const Qt=W().filter(gt=>!gt.disabled).map(gt=>gt.ref.current);Que.includes(je.key)&&Qt.reverse(),wLe(Qt)}),onBlur:Yr(t.onBlur,je=>{je.currentTarget.contains(je.target)||(window.clearTimeout(X.current),ie.current="")}),onPointerMove:Yr(t.onPointerMove,lk(je=>{const et=je.target,bt=ve.current!==je.clientX;if(je.currentTarget.contains(et)&&bt){const _e=je.clientX>ve.current?"right":"left";pe.current=_e,ve.current=je.clientX}}))})})})})})})});sde.displayName=lh;var fLe="MenuGroup",$8=D.forwardRef((t,e)=>{const{__scopeMenu:r,...n}=t;return s.jsx(yn.div,{role:"group",...n,ref:e})});$8.displayName=fLe;var pLe="MenuLabel",ide=D.forwardRef((t,e)=>{const{__scopeMenu:r,...n}=t;return s.jsx(yn.div,{...n,ref:e})});ide.displayName=pLe;var RM="MenuItem",OX="menu.itemSelect",SD=D.forwardRef((t,e)=>{const{disabled:r=!1,onSelect:n,...i}=t,o=D.useRef(null),c=ET(RM,t.__scopeMenu),a=z8(RM,t.__scopeMenu),m=vs(e,o),g=D.useRef(!1),_=()=>{const j=o.current;if(!r&&j){const N=new CustomEvent(OX,{bubbles:!0,cancelable:!0});j.addEventListener(OX,C=>n==null?void 0:n(C),{once:!0}),$6(j,N),N.defaultPrevented?g.current=!1:c.onClose()}};return s.jsx(ade,{...i,ref:m,disabled:r,onClick:Yr(t.onClick,_),onPointerDown:j=>{var N;(N=t.onPointerDown)==null||N.call(t,j),g.current=!0},onPointerUp:Yr(t.onPointerUp,j=>{var N;g.current||(N=j.currentTarget)==null||N.click()}),onKeyDown:Yr(t.onKeyDown,j=>{const N=a.searchRef.current!=="";r||N&&j.key===" "||S$.includes(j.key)&&(j.currentTarget.click(),j.preventDefault())})})});SD.displayName=RM;var ade=D.forwardRef((t,e)=>{const{__scopeMenu:r,disabled:n=!1,textValue:i,...o}=t,c=z8(RM,r),a=ede(r),m=D.useRef(null),g=vs(e,m),[_,j]=D.useState(!1),[N,C]=D.useState("");return D.useEffect(()=>{const P=m.current;P&&C((P.textContent??"").trim())},[o.children]),s.jsx(ok.ItemSlot,{scope:r,disabled:n,textValue:i??N,children:s.jsx(D8,{asChild:!0,...a,focusable:!n,children:s.jsx(yn.div,{role:"menuitem","data-highlighted":_?"":void 0,"aria-disabled":n||void 0,"data-disabled":n?"":void 0,...o,ref:g,onPointerMove:Yr(t.onPointerMove,lk(P=>{n?c.onItemLeave(P):(c.onItemEnter(P),P.defaultPrevented||P.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:Yr(t.onPointerLeave,lk(P=>c.onItemLeave(P))),onFocus:Yr(t.onFocus,()=>j(!0)),onBlur:Yr(t.onBlur,()=>j(!1))})})})}),mLe="MenuCheckboxItem",ode=D.forwardRef((t,e)=>{const{checked:r=!1,onCheckedChange:n,...i}=t;return s.jsx(hde,{scope:t.__scopeMenu,checked:r,children:s.jsx(SD,{role:"menuitemcheckbox","aria-checked":DM(r)?"mixed":r,...i,ref:e,"data-state":V8(r),onSelect:Yr(i.onSelect,()=>n==null?void 0:n(DM(r)?!0:!r),{checkForDefaultPrevented:!1})})})});ode.displayName=mLe;var lde="MenuRadioGroup",[gLe,yLe]=a0(lde,{value:void 0,onValueChange:()=>{}}),cde=D.forwardRef((t,e)=>{const{value:r,onValueChange:n,...i}=t,o=Oo(n);return s.jsx(gLe,{scope:t.__scopeMenu,value:r,onValueChange:o,children:s.jsx($8,{...i,ref:e})})});cde.displayName=lde;var ude="MenuRadioItem",dde=D.forwardRef((t,e)=>{const{value:r,...n}=t,i=yLe(ude,t.__scopeMenu),o=r===i.value;return s.jsx(hde,{scope:t.__scopeMenu,checked:o,children:s.jsx(SD,{role:"menuitemradio","aria-checked":o,...n,ref:e,"data-state":V8(o),onSelect:Yr(n.onSelect,()=>{var c;return(c=i.onValueChange)==null?void 0:c.call(i,r)},{checkForDefaultPrevented:!1})})})});dde.displayName=ude;var U8="MenuItemIndicator",[hde,xLe]=a0(U8,{checked:!1}),fde=D.forwardRef((t,e)=>{const{__scopeMenu:r,forceMount:n,...i}=t,o=xLe(U8,r);return s.jsx(gl,{present:n||DM(o.checked)||o.checked===!0,children:s.jsx(yn.span,{...i,ref:e,"data-state":V8(o.checked)})})});fde.displayName=U8;var vLe="MenuSeparator",pde=D.forwardRef((t,e)=>{const{__scopeMenu:r,...n}=t;return s.jsx(yn.div,{role:"separator","aria-orientation":"horizontal",...n,ref:e})});pde.displayName=vLe;var _Le="MenuArrow",mde=D.forwardRef((t,e)=>{const{__scopeMenu:r,...n}=t,i=jD(r);return s.jsx(lD,{...i,...n,ref:e})});mde.displayName=_Le;var bLe="MenuSub",[owt,gde]=a0(bLe),BC="MenuSubTrigger",yde=D.forwardRef((t,e)=>{const r=o0(BC,t.__scopeMenu),n=ET(BC,t.__scopeMenu),i=gde(BC,t.__scopeMenu),o=z8(BC,t.__scopeMenu),c=D.useRef(null),{pointerGraceTimerRef:a,onPointerGraceIntentChange:m}=o,g={__scopeMenu:t.__scopeMenu},_=D.useCallback(()=>{c.current&&window.clearTimeout(c.current),c.current=null},[]);return D.useEffect(()=>_,[_]),D.useEffect(()=>{const j=a.current;return()=>{window.clearTimeout(j),m(null)}},[a,m]),s.jsx(L8,{asChild:!0,...g,children:s.jsx(ade,{id:i.triggerId,"aria-haspopup":"menu","aria-expanded":r.open,"aria-controls":i.contentId,"data-state":_de(r.open),...t,ref:qm(e,i.onTriggerChange),onClick:j=>{var N;(N=t.onClick)==null||N.call(t,j),!(t.disabled||j.defaultPrevented)&&(j.currentTarget.focus(),r.open||r.onOpenChange(!0))},onPointerMove:Yr(t.onPointerMove,lk(j=>{o.onItemEnter(j),!j.defaultPrevented&&!t.disabled&&!r.open&&!c.current&&(o.onPointerGraceIntentChange(null),c.current=window.setTimeout(()=>{r.onOpenChange(!0),_()},100))})),onPointerLeave:Yr(t.onPointerLeave,lk(j=>{var C,P;_();const N=(C=r.content)==null?void 0:C.getBoundingClientRect();if(N){const A=(P=r.content)==null?void 0:P.dataset.side,I=A==="right",O=I?-5:5,R=N[I?"left":"right"],z=N[I?"right":"left"];o.onPointerGraceIntentChange({area:[{x:j.clientX+O,y:j.clientY},{x:R,y:N.top},{x:z,y:N.top},{x:z,y:N.bottom},{x:R,y:N.bottom}],side:A}),window.clearTimeout(a.current),a.current=window.setTimeout(()=>o.onPointerGraceIntentChange(null),300)}else{if(o.onTriggerLeave(j),j.defaultPrevented)return;o.onPointerGraceIntentChange(null)}})),onKeyDown:Yr(t.onKeyDown,j=>{var C;const N=o.searchRef.current!=="";t.disabled||N&&j.key===" "||tLe[n.dir].includes(j.key)&&(r.onOpenChange(!0),(C=r.content)==null||C.focus(),j.preventDefault())})})})});yde.displayName=BC;var xde="MenuSubContent",vde=D.forwardRef((t,e)=>{const r=rde(lh,t.__scopeMenu),{forceMount:n=r.forceMount,...i}=t,o=o0(lh,t.__scopeMenu),c=ET(lh,t.__scopeMenu),a=gde(xde,t.__scopeMenu),m=D.useRef(null),g=vs(e,m);return s.jsx(ok.Provider,{scope:t.__scopeMenu,children:s.jsx(gl,{present:n||o.open,children:s.jsx(ok.Slot,{scope:t.__scopeMenu,children:s.jsx(B8,{id:a.contentId,"aria-labelledby":a.triggerId,...i,ref:g,align:"start",side:c.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:_=>{var j;c.isUsingKeyboardRef.current&&((j=m.current)==null||j.focus()),_.preventDefault()},onCloseAutoFocus:_=>_.preventDefault(),onFocusOutside:Yr(t.onFocusOutside,_=>{_.target!==a.trigger&&o.onOpenChange(!1)}),onEscapeKeyDown:Yr(t.onEscapeKeyDown,_=>{c.onClose(),_.preventDefault()}),onKeyDown:Yr(t.onKeyDown,_=>{var C;const j=_.currentTarget.contains(_.target),N=rLe[c.dir].includes(_.key);j&&N&&(o.onOpenChange(!1),(C=a.trigger)==null||C.focus(),_.preventDefault())})})})})})});vde.displayName=xde;function _de(t){return t?"open":"closed"}function DM(t){return t==="indeterminate"}function V8(t){return DM(t)?"indeterminate":t?"checked":"unchecked"}function wLe(t){const e=document.activeElement;for(const r of t)if(r===e||(r.focus(),document.activeElement!==e))return}function jLe(t,e){return t.map((r,n)=>t[(e+n)%t.length])}function SLe(t,e,r){const i=e.length>1&&Array.from(e).every(g=>g===e[0])?e[0]:e,o=r?t.indexOf(r):-1;let c=jLe(t,Math.max(o,0));i.length===1&&(c=c.filter(g=>g!==r));const m=c.find(g=>g.toLowerCase().startsWith(i.toLowerCase()));return m!==r?m:void 0}function NLe(t,e){const{x:r,y:n}=t;let i=!1;for(let o=0,c=e.length-1;on!=N>n&&r<(j-g)*(n-_)/(N-_)+g&&(i=!i)}return i}function CLe(t,e){if(!e)return!1;const r={x:t.clientX,y:t.clientY};return NLe(r,e)}function lk(t){return e=>e.pointerType==="mouse"?t(e):void 0}var kLe=tde,TLe=L8,ELe=nde,ALe=sde,PLe=$8,ILe=ide,MLe=SD,OLe=ode,RLe=cde,DLe=dde,LLe=fde,FLe=pde,zLe=mde,BLe=yde,$Le=vde,ND="DropdownMenu",[ULe]=Yo(ND,[Jue]),gu=Jue(),[VLe,bde]=ULe(ND),wde=t=>{const{__scopeDropdownMenu:e,children:r,dir:n,open:i,defaultOpen:o,onOpenChange:c,modal:a=!0}=t,m=gu(e),g=D.useRef(null),[_,j]=Uu({prop:i,defaultProp:o??!1,onChange:c,caller:ND});return s.jsx(VLe,{scope:e,triggerId:Al(),triggerRef:g,contentId:Al(),open:_,onOpenChange:j,onOpenToggle:D.useCallback(()=>j(N=>!N),[j]),modal:a,children:s.jsx(kLe,{...m,open:_,onOpenChange:j,dir:n,modal:a,children:r})})};wde.displayName=ND;var jde="DropdownMenuTrigger",Sde=D.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,disabled:n=!1,...i}=t,o=bde(jde,r),c=gu(r);return s.jsx(TLe,{asChild:!0,...c,children:s.jsx(yn.button,{type:"button",id:o.triggerId,"aria-haspopup":"menu","aria-expanded":o.open,"aria-controls":o.open?o.contentId:void 0,"data-state":o.open?"open":"closed","data-disabled":n?"":void 0,disabled:n,...i,ref:qm(e,o.triggerRef),onPointerDown:Yr(t.onPointerDown,a=>{!n&&a.button===0&&a.ctrlKey===!1&&(o.onOpenToggle(),o.open||a.preventDefault())}),onKeyDown:Yr(t.onKeyDown,a=>{n||(["Enter"," "].includes(a.key)&&o.onOpenToggle(),a.key==="ArrowDown"&&o.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(a.key)&&a.preventDefault())})})})});Sde.displayName=jde;var qLe="DropdownMenuPortal",Nde=t=>{const{__scopeDropdownMenu:e,...r}=t,n=gu(e);return s.jsx(ELe,{...n,...r})};Nde.displayName=qLe;var Cde="DropdownMenuContent",kde=D.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=bde(Cde,r),o=gu(r),c=D.useRef(!1);return s.jsx(ALe,{id:i.contentId,"aria-labelledby":i.triggerId,...o,...n,ref:e,onCloseAutoFocus:Yr(t.onCloseAutoFocus,a=>{var m;c.current||(m=i.triggerRef.current)==null||m.focus(),c.current=!1,a.preventDefault()}),onInteractOutside:Yr(t.onInteractOutside,a=>{const m=a.detail.originalEvent,g=m.button===0&&m.ctrlKey===!0,_=m.button===2||g;(!i.modal||_)&&(c.current=!0)}),style:{...t.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});kde.displayName=Cde;var HLe="DropdownMenuGroup",WLe=D.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=gu(r);return s.jsx(PLe,{...i,...n,ref:e})});WLe.displayName=HLe;var GLe="DropdownMenuLabel",Tde=D.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=gu(r);return s.jsx(ILe,{...i,...n,ref:e})});Tde.displayName=GLe;var KLe="DropdownMenuItem",Ede=D.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=gu(r);return s.jsx(MLe,{...i,...n,ref:e})});Ede.displayName=KLe;var ZLe="DropdownMenuCheckboxItem",Ade=D.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=gu(r);return s.jsx(OLe,{...i,...n,ref:e})});Ade.displayName=ZLe;var YLe="DropdownMenuRadioGroup",XLe=D.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=gu(r);return s.jsx(RLe,{...i,...n,ref:e})});XLe.displayName=YLe;var QLe="DropdownMenuRadioItem",Pde=D.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=gu(r);return s.jsx(DLe,{...i,...n,ref:e})});Pde.displayName=QLe;var JLe="DropdownMenuItemIndicator",Ide=D.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=gu(r);return s.jsx(LLe,{...i,...n,ref:e})});Ide.displayName=JLe;var e4e="DropdownMenuSeparator",Mde=D.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=gu(r);return s.jsx(FLe,{...i,...n,ref:e})});Mde.displayName=e4e;var t4e="DropdownMenuArrow",r4e=D.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=gu(r);return s.jsx(zLe,{...i,...n,ref:e})});r4e.displayName=t4e;var n4e="DropdownMenuSubTrigger",Ode=D.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=gu(r);return s.jsx(BLe,{...i,...n,ref:e})});Ode.displayName=n4e;var s4e="DropdownMenuSubContent",Rde=D.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=gu(r);return s.jsx($Le,{...i,...n,ref:e,style:{...t.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});Rde.displayName=s4e;var i4e=wde,a4e=Sde,o4e=Nde,Dde=kde,Lde=Tde,Fde=Ede,zde=Ade,Bde=Pde,$de=Ide,Ude=Mde,Vde=Ode,qde=Rde;const rg=i4e,ng=a4e,l4e=D.forwardRef(({className:t,inset:e,children:r,...n},i)=>s.jsxs(Vde,{ref:i,className:ar("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[state=open]:bg-accent focus:bg-accent",e&&"pl-8",t),...n,children:[r,s.jsx(wd,{className:"ml-auto h-4 w-4"})]}));l4e.displayName=Vde.displayName;const c4e=D.forwardRef(({className:t,...e},r)=>s.jsx(qde,{ref:r,className:ar("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...e}));c4e.displayName=qde.displayName;const Op=D.forwardRef(({className:t,sideOffset:e=4,...r},n)=>s.jsx(o4e,{children:s.jsx(Dde,{ref:n,sideOffset:e,className:ar("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...r})}));Op.displayName=Dde.displayName;const Ro=D.forwardRef(({className:t,inset:e,...r},n)=>s.jsx(Fde,{ref:n,className:ar("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",e&&"pl-8",t),...r}));Ro.displayName=Fde.displayName;const u4e=D.forwardRef(({className:t,children:e,checked:r,...n},i)=>s.jsxs(zde,{ref:i,className:ar("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",t),checked:r,...n,children:[s.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:s.jsx($de,{children:s.jsx(ru,{className:"h-4 w-4"})})}),e]}));u4e.displayName=zde.displayName;const d4e=D.forwardRef(({className:t,children:e,...r},n)=>s.jsxs(Bde,{ref:n,className:ar("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",t),...r,children:[s.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:s.jsx($de,{children:s.jsx(hM,{className:"h-2 w-2 fill-current"})})}),e]}));d4e.displayName=Bde.displayName;const h4e=D.forwardRef(({className:t,inset:e,...r},n)=>s.jsx(Lde,{ref:n,className:ar("px-2 py-1.5 text-sm font-semibold",e&&"pl-8",t),...r}));h4e.displayName=Lde.displayName;const Hde=D.forwardRef(({className:t,...e},r)=>s.jsx(Ude,{ref:r,className:ar("-mx-1 my-1 h-px bg-muted",t),...e}));Hde.displayName=Ude.displayName;var CD="Collapsible",[f4e]=Yo(CD),[p4e,q8]=f4e(CD),Wde=D.forwardRef((t,e)=>{const{__scopeCollapsible:r,open:n,defaultOpen:i,disabled:o,onOpenChange:c,...a}=t,[m,g]=Uu({prop:n,defaultProp:i??!1,onChange:c,caller:CD});return s.jsx(p4e,{scope:r,disabled:o,contentId:Al(),open:m,onOpenToggle:D.useCallback(()=>g(_=>!_),[g]),children:s.jsx(yn.div,{"data-state":W8(m),"data-disabled":o?"":void 0,...a,ref:e})})});Wde.displayName=CD;var Gde="CollapsibleTrigger",Kde=D.forwardRef((t,e)=>{const{__scopeCollapsible:r,...n}=t,i=q8(Gde,r);return s.jsx(yn.button,{type:"button","aria-controls":i.contentId,"aria-expanded":i.open||!1,"data-state":W8(i.open),"data-disabled":i.disabled?"":void 0,disabled:i.disabled,...n,ref:e,onClick:Yr(t.onClick,i.onOpenToggle)})});Kde.displayName=Gde;var H8="CollapsibleContent",Zde=D.forwardRef((t,e)=>{const{forceMount:r,...n}=t,i=q8(H8,t.__scopeCollapsible);return s.jsx(gl,{present:r||i.open,children:({present:o})=>s.jsx(m4e,{...n,ref:e,present:o})})});Zde.displayName=H8;var m4e=D.forwardRef((t,e)=>{const{__scopeCollapsible:r,present:n,children:i,...o}=t,c=q8(H8,r),[a,m]=D.useState(n),g=D.useRef(null),_=vs(e,g),j=D.useRef(0),N=j.current,C=D.useRef(0),P=C.current,A=c.open||a,I=D.useRef(A),O=D.useRef(void 0);return D.useEffect(()=>{const R=requestAnimationFrame(()=>I.current=!1);return()=>cancelAnimationFrame(R)},[]),Lo(()=>{const R=g.current;if(R){O.current=O.current||{transitionDuration:R.style.transitionDuration,animationName:R.style.animationName},R.style.transitionDuration="0s",R.style.animationName="none";const z=R.getBoundingClientRect();j.current=z.height,C.current=z.width,I.current||(R.style.transitionDuration=O.current.transitionDuration,R.style.animationName=O.current.animationName),m(n)}},[c.open,n]),s.jsx(yn.div,{"data-state":W8(c.open),"data-disabled":c.disabled?"":void 0,id:c.contentId,hidden:!A,...o,ref:_,style:{"--radix-collapsible-content-height":N?`${N}px`:void 0,"--radix-collapsible-content-width":P?`${P}px`:void 0,...t.style},children:A&&i})});function W8(t){return t?"open":"closed"}var g4e=Wde;const y4e=g4e,x4e=Kde,v4e=Zde,RX="/assets/levelup-logo-Eif24dqY.png";var AT=t=>t.type==="checkbox",Kv=t=>t instanceof Date,eu=t=>t==null;const Yde=t=>typeof t=="object";var Zo=t=>!eu(t)&&!Array.isArray(t)&&Yde(t)&&!Kv(t),Xde=t=>Zo(t)&&t.target?AT(t.target)?t.target.checked:t.target.value:t,_4e=t=>t.substring(0,t.search(/\.\d+(\.|$)/))||t,Qde=(t,e)=>t.has(_4e(e)),b4e=t=>{const e=t.constructor&&t.constructor.prototype;return Zo(e)&&e.hasOwnProperty("isPrototypeOf")},G8=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function jl(t){let e;const r=Array.isArray(t),n=typeof FileList<"u"?t instanceof FileList:!1;if(t instanceof Date)e=new Date(t);else if(!(G8&&(t instanceof Blob||n))&&(r||Zo(t)))if(e=r?[]:{},!r&&!b4e(t))e=t;else for(const i in t)t.hasOwnProperty(i)&&(e[i]=jl(t[i]));else return t;return e}var kD=t=>/^\w*$/.test(t),qo=t=>t===void 0,K8=t=>Array.isArray(t)?t.filter(Boolean):[],Z8=t=>K8(t.replace(/["|']|\]/g,"").split(/\.|\[/)),Nn=(t,e,r)=>{if(!e||!Zo(t))return r;const n=(kD(e)?[e]:Z8(e)).reduce((i,o)=>eu(i)?i:i[o],t);return qo(n)||n===t?qo(t[e])?r:t[e]:n},ld=t=>typeof t=="boolean",ja=(t,e,r)=>{let n=-1;const i=kD(e)?[e]:Z8(e),o=i.length,c=o-1;for(;++nVe.useContext(Y8),w4e=t=>{const{children:e,...r}=t;return Ve.createElement(Y8.Provider,{value:r},e)};var Jde=(t,e,r,n=!0)=>{const i={defaultValues:e._defaultValues};for(const o in t)Object.defineProperty(i,o,{get:()=>{const c=o;return e._proxyFormState[c]!==df.all&&(e._proxyFormState[c]=!n||df.all),r&&(r[c]=!0),t[c]}});return i};const X8=typeof window<"u"?Ve.useLayoutEffect:Ve.useEffect;function j4e(t){const e=TD(),{control:r=e.control,disabled:n,name:i,exact:o}=t||{},[c,a]=Ve.useState(r._formState),m=Ve.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,validatingFields:!1,isValidating:!1,isValid:!1,errors:!1});return X8(()=>r._subscribe({name:i,formState:m.current,exact:o,callback:g=>{!n&&a({...r._formState,...g})}}),[i,n,o]),Ve.useEffect(()=>{m.current.isValid&&r._setValid(!0)},[r]),Ve.useMemo(()=>Jde(c,r,m.current,!1),[c,r])}var dp=t=>typeof t=="string",ehe=(t,e,r,n,i)=>dp(t)?(n&&e.watch.add(t),Nn(r,t,i)):Array.isArray(t)?t.map(o=>(n&&e.watch.add(o),Nn(r,o))):(n&&(e.watchAll=!0),r),N$=t=>eu(t)||!Yde(t);function km(t,e,r=new WeakSet){if(N$(t)||N$(e))return t===e;if(Kv(t)&&Kv(e))return t.getTime()===e.getTime();const n=Object.keys(t),i=Object.keys(e);if(n.length!==i.length)return!1;if(r.has(t)||r.has(e))return!0;r.add(t),r.add(e);for(const o of n){const c=t[o];if(!i.includes(o))return!1;if(o!=="ref"){const a=e[o];if(Kv(c)&&Kv(a)||Zo(c)&&Zo(a)||Array.isArray(c)&&Array.isArray(a)?!km(c,a,r):c!==a)return!1}}return!0}function S4e(t){const e=TD(),{control:r=e.control,name:n,defaultValue:i,disabled:o,exact:c,compute:a}=t||{},m=Ve.useRef(i),g=Ve.useRef(a),_=Ve.useRef(void 0);g.current=a;const j=Ve.useMemo(()=>r._getWatch(n,m.current),[r,n]),[N,C]=Ve.useState(g.current?g.current(j):j);return X8(()=>r._subscribe({name:n,formState:{values:!0},exact:c,callback:P=>{if(!o){const A=ehe(n,r._names,P.values||r._formValues,!1,m.current);if(g.current){const I=g.current(A);km(I,_.current)||(C(I),_.current=I)}else C(A)}}}),[r,o,n,c]),Ve.useEffect(()=>r._removeUnmounted()),N}function N4e(t){const e=TD(),{name:r,disabled:n,control:i=e.control,shouldUnregister:o,defaultValue:c}=t,a=Qde(i._names.array,r),m=Ve.useMemo(()=>Nn(i._formValues,r,Nn(i._defaultValues,r,c)),[i,r,c]),g=S4e({control:i,name:r,defaultValue:m,exact:!0}),_=j4e({control:i,name:r,exact:!0}),j=Ve.useRef(t),N=Ve.useRef(i.register(r,{...t.rules,value:g,...ld(t.disabled)?{disabled:t.disabled}:{}}));j.current=t;const C=Ve.useMemo(()=>Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!Nn(_.errors,r)},isDirty:{enumerable:!0,get:()=>!!Nn(_.dirtyFields,r)},isTouched:{enumerable:!0,get:()=>!!Nn(_.touchedFields,r)},isValidating:{enumerable:!0,get:()=>!!Nn(_.validatingFields,r)},error:{enumerable:!0,get:()=>Nn(_.errors,r)}}),[_,r]),P=Ve.useCallback(R=>N.current.onChange({target:{value:Xde(R),name:r},type:LM.CHANGE}),[r]),A=Ve.useCallback(()=>N.current.onBlur({target:{value:Nn(i._formValues,r),name:r},type:LM.BLUR}),[r,i._formValues]),I=Ve.useCallback(R=>{const z=Nn(i._fields,r);z&&R&&(z._f.ref={focus:()=>R.focus&&R.focus(),select:()=>R.select&&R.select(),setCustomValidity:W=>R.setCustomValidity(W),reportValidity:()=>R.reportValidity()})},[i._fields,r]),O=Ve.useMemo(()=>({name:r,value:g,...ld(n)||_.disabled?{disabled:_.disabled||n}:{},onChange:P,onBlur:A,ref:I}),[r,n,_.disabled,P,A,I,g]);return Ve.useEffect(()=>{const R=i._options.shouldUnregister||o;i.register(r,{...j.current.rules,...ld(j.current.disabled)?{disabled:j.current.disabled}:{}});const z=(W,V)=>{const K=Nn(i._fields,W);K&&K._f&&(K._f.mount=V)};if(z(r,!0),R){const W=jl(Nn(i._options.defaultValues,r));ja(i._defaultValues,r,W),qo(Nn(i._formValues,r))&&ja(i._formValues,r,W)}return!a&&i.register(r),()=>{(a?R&&!i._state.action:R)?i.unregister(r):z(r,!1)}},[r,i,a,o]),Ve.useEffect(()=>{i._setDisabledField({disabled:n,name:r})},[n,r,i]),Ve.useMemo(()=>({field:O,formState:_,fieldState:C}),[O,_,C])}const C4e=t=>t.render(N4e(t));var the=(t,e,r,n,i)=>e?{...r[t],types:{...r[t]&&r[t].types?r[t].types:{},[n]:i||!0}}:{},c2=t=>Array.isArray(t)?t:[t],DX=()=>{let t=[];return{get observers(){return t},next:i=>{for(const o of t)o.next&&o.next(i)},subscribe:i=>(t.push(i),{unsubscribe:()=>{t=t.filter(o=>o!==i)}}),unsubscribe:()=>{t=[]}}},Au=t=>Zo(t)&&!Object.keys(t).length,Q8=t=>t.type==="file",hf=t=>typeof t=="function",FM=t=>{if(!G8)return!1;const e=t?t.ownerDocument:0;return t instanceof(e&&e.defaultView?e.defaultView.HTMLElement:HTMLElement)},rhe=t=>t.type==="select-multiple",J8=t=>t.type==="radio",k4e=t=>J8(t)||AT(t),uz=t=>FM(t)&&t.isConnected;function T4e(t,e){const r=e.slice(0,-1).length;let n=0;for(;n{for(const e in t)if(hf(t[e]))return!0;return!1};function zM(t,e={}){const r=Array.isArray(t);if(Zo(t)||r)for(const n in t)Array.isArray(t[n])||Zo(t[n])&&!nhe(t[n])?(e[n]=Array.isArray(t[n])?[]:{},zM(t[n],e[n])):eu(t[n])||(e[n]=!0);return e}function she(t,e,r){const n=Array.isArray(t);if(Zo(t)||n)for(const i in t)Array.isArray(t[i])||Zo(t[i])&&!nhe(t[i])?qo(e)||N$(r[i])?r[i]=Array.isArray(t[i])?zM(t[i],[]):{...zM(t[i])}:she(t[i],eu(e)?{}:e[i],r[i]):r[i]=!km(t[i],e[i]);return r}var fC=(t,e)=>she(t,e,zM(e));const LX={value:!1,isValid:!1},FX={value:!0,isValid:!0};var ihe=t=>{if(Array.isArray(t)){if(t.length>1){const e=t.filter(r=>r&&r.checked&&!r.disabled).map(r=>r.value);return{value:e,isValid:!!e.length}}return t[0].checked&&!t[0].disabled?t[0].attributes&&!qo(t[0].attributes.value)?qo(t[0].value)||t[0].value===""?FX:{value:t[0].value,isValid:!0}:FX:LX}return LX},ahe=(t,{valueAsNumber:e,valueAsDate:r,setValueAs:n})=>qo(t)?t:e?t===""?NaN:t&&+t:r&&dp(t)?new Date(t):n?n(t):t;const zX={isValid:!1,value:null};var ohe=t=>Array.isArray(t)?t.reduce((e,r)=>r&&r.checked&&!r.disabled?{isValid:!0,value:r.value}:e,zX):zX;function BX(t){const e=t.ref;return Q8(e)?e.files:J8(e)?ohe(t.refs).value:rhe(e)?[...e.selectedOptions].map(({value:r})=>r):AT(e)?ihe(t.refs).value:ahe(qo(e.value)?t.ref.value:e.value,t)}var A4e=(t,e,r,n)=>{const i={};for(const o of t){const c=Nn(e,o);c&&ja(i,o,c._f)}return{criteriaMode:r,names:[...t],fields:i,shouldUseNativeValidation:n}},BM=t=>t instanceof RegExp,pC=t=>qo(t)?t:BM(t)?t.source:Zo(t)?BM(t.value)?t.value.source:t.value:t,$X=t=>({isOnSubmit:!t||t===df.onSubmit,isOnBlur:t===df.onBlur,isOnChange:t===df.onChange,isOnAll:t===df.all,isOnTouch:t===df.onTouched});const UX="AsyncFunction";var P4e=t=>!!t&&!!t.validate&&!!(hf(t.validate)&&t.validate.constructor.name===UX||Zo(t.validate)&&Object.values(t.validate).find(e=>e.constructor.name===UX)),I4e=t=>t.mount&&(t.required||t.min||t.max||t.maxLength||t.minLength||t.pattern||t.validate),VX=(t,e,r)=>!r&&(e.watchAll||e.watch.has(t)||[...e.watch].some(n=>t.startsWith(n)&&/^\.\w+/.test(t.slice(n.length))));const u2=(t,e,r,n)=>{for(const i of r||Object.keys(t)){const o=Nn(t,i);if(o){const{_f:c,...a}=o;if(c){if(c.refs&&c.refs[0]&&e(c.refs[0],i)&&!n)return!0;if(c.ref&&e(c.ref,c.name)&&!n)return!0;if(u2(a,e))break}else if(Zo(a)&&u2(a,e))break}}};function qX(t,e,r){const n=Nn(t,r);if(n||kD(r))return{error:n,name:r};const i=r.split(".");for(;i.length;){const o=i.join("."),c=Nn(e,o),a=Nn(t,o);if(c&&!Array.isArray(c)&&r!==o)return{name:r};if(a&&a.type)return{name:o,error:a};if(a&&a.root&&a.root.type)return{name:`${o}.root`,error:a.root};i.pop()}return{name:r}}var M4e=(t,e,r,n)=>{r(t);const{name:i,...o}=t;return Au(o)||Object.keys(o).length>=Object.keys(e).length||Object.keys(o).find(c=>e[c]===(!n||df.all))},O4e=(t,e,r)=>!t||!e||t===e||c2(t).some(n=>n&&(r?n===e:n.startsWith(e)||e.startsWith(n))),R4e=(t,e,r,n,i)=>i.isOnAll?!1:!r&&i.isOnTouch?!(e||t):(r?n.isOnBlur:i.isOnBlur)?!t:(r?n.isOnChange:i.isOnChange)?t:!0,D4e=(t,e)=>!K8(Nn(t,e)).length&&al(t,e),L4e=(t,e,r)=>{const n=c2(Nn(t,r));return ja(n,"root",e[r]),ja(t,r,n),t},AI=t=>dp(t);function HX(t,e,r="validate"){if(AI(t)||Array.isArray(t)&&t.every(AI)||ld(t)&&!t)return{type:r,message:AI(t)?t:"",ref:e}}var cw=t=>Zo(t)&&!BM(t)?t:{value:t,message:""},WX=async(t,e,r,n,i,o)=>{const{ref:c,refs:a,required:m,maxLength:g,minLength:_,min:j,max:N,pattern:C,validate:P,name:A,valueAsNumber:I,mount:O}=t._f,R=Nn(r,A);if(!O||e.has(A))return{};const z=a?a[0]:c,W=xe=>{i&&z.reportValidity&&(z.setCustomValidity(ld(xe)?"":xe||""),z.reportValidity())},V={},K=J8(c),Q=AT(c),te=K||Q,X=(I||Q8(c))&&qo(c.value)&&qo(R)||FM(c)&&c.value===""||R===""||Array.isArray(R)&&!R.length,ie=the.bind(null,A,n,V),he=(xe,pe,ve,ge=hm.maxLength,ke=hm.minLength)=>{const Ce=xe?pe:ve;V[A]={type:xe?ge:ke,message:Ce,ref:c,...ie(xe?ge:ke,Ce)}};if(o?!Array.isArray(R)||!R.length:m&&(!te&&(X||eu(R))||ld(R)&&!R||Q&&!ihe(a).isValid||K&&!ohe(a).isValid)){const{value:xe,message:pe}=AI(m)?{value:!!m,message:m}:cw(m);if(xe&&(V[A]={type:hm.required,message:pe,ref:z,...ie(hm.required,pe)},!n))return W(pe),V}if(!X&&(!eu(j)||!eu(N))){let xe,pe;const ve=cw(N),ge=cw(j);if(!eu(R)&&!isNaN(R)){const ke=c.valueAsNumber||R&&+R;eu(ve.value)||(xe=ke>ve.value),eu(ge.value)||(pe=kenew Date(new Date().toDateString()+" "+et),Se=c.type=="time",je=c.type=="week";dp(ve.value)&&R&&(xe=Se?Ce(R)>Ce(ve.value):je?R>ve.value:ke>new Date(ve.value)),dp(ge.value)&&R&&(pe=Se?Ce(R)+xe.value,ge=!eu(pe.value)&&R.length<+pe.value;if((ve||ge)&&(he(ve,xe.message,pe.message),!n))return W(V[A].message),V}if(C&&!X&&dp(R)){const{value:xe,message:pe}=cw(C);if(BM(xe)&&!R.match(xe)&&(V[A]={type:hm.pattern,message:pe,ref:c,...ie(hm.pattern,pe)},!n))return W(pe),V}if(P){if(hf(P)){const xe=await P(R,r),pe=HX(xe,z);if(pe&&(V[A]={...pe,...ie(hm.validate,pe.message)},!n))return W(pe.message),V}else if(Zo(P)){let xe={};for(const pe in P){if(!Au(xe)&&!n)break;const ve=HX(await P[pe](R,r),z,pe);ve&&(xe={...ve,...ie(pe,ve.message)},W(ve.message),n&&(V[A]=xe))}if(!Au(xe)&&(V[A]={ref:z,...xe},!n))return V}}return W(!0),V};const F4e={mode:df.onSubmit,reValidateMode:df.onChange,shouldFocusError:!0};function z4e(t={}){let e={...F4e,...t},r={submitCount:0,isDirty:!1,isReady:!1,isLoading:hf(e.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{},errors:e.errors||{},disabled:e.disabled||!1},n={},i=Zo(e.defaultValues)||Zo(e.values)?jl(e.defaultValues||e.values)||{}:{},o=e.shouldUnregister?{}:jl(i),c={action:!1,mount:!1,watch:!1},a={mount:new Set,disabled:new Set,unMount:new Set,array:new Set,watch:new Set},m,g=0;const _={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1};let j={..._};const N={array:DX(),state:DX()},C=e.criteriaMode===df.all,P=rt=>We=>{clearTimeout(g),g=setTimeout(rt,We)},A=async rt=>{if(!e.disabled&&(_.isValid||j.isValid||rt)){const We=e.resolver?Au((await Q()).errors):await X(n,!0);We!==r.isValid&&N.state.next({isValid:We})}},I=(rt,We)=>{!e.disabled&&(_.isValidating||_.validatingFields||j.isValidating||j.validatingFields)&&((rt||Array.from(a.mount)).forEach(_t=>{_t&&(We?ja(r.validatingFields,_t,We):al(r.validatingFields,_t))}),N.state.next({validatingFields:r.validatingFields,isValidating:!Au(r.validatingFields)}))},O=(rt,We=[],_t,Gt,rr=!0,pr=!0)=>{if(Gt&&_t&&!e.disabled){if(c.action=!0,pr&&Array.isArray(Nn(n,rt))){const kr=_t(Nn(n,rt),Gt.argA,Gt.argB);rr&&ja(n,rt,kr)}if(pr&&Array.isArray(Nn(r.errors,rt))){const kr=_t(Nn(r.errors,rt),Gt.argA,Gt.argB);rr&&ja(r.errors,rt,kr),D4e(r.errors,rt)}if((_.touchedFields||j.touchedFields)&&pr&&Array.isArray(Nn(r.touchedFields,rt))){const kr=_t(Nn(r.touchedFields,rt),Gt.argA,Gt.argB);rr&&ja(r.touchedFields,rt,kr)}(_.dirtyFields||j.dirtyFields)&&(r.dirtyFields=fC(i,o)),N.state.next({name:rt,isDirty:he(rt,We),dirtyFields:r.dirtyFields,errors:r.errors,isValid:r.isValid})}else ja(o,rt,We)},R=(rt,We)=>{ja(r.errors,rt,We),N.state.next({errors:r.errors})},z=rt=>{r.errors=rt,N.state.next({errors:r.errors,isValid:!1})},W=(rt,We,_t,Gt)=>{const rr=Nn(n,rt);if(rr){const pr=Nn(o,rt,qo(_t)?Nn(i,rt):_t);qo(pr)||Gt&&Gt.defaultChecked||We?ja(o,rt,We?pr:BX(rr._f)):ve(rt,pr),c.mount&&A()}},V=(rt,We,_t,Gt,rr)=>{let pr=!1,kr=!1;const Hr={name:rt};if(!e.disabled){if(!_t||Gt){(_.isDirty||j.isDirty)&&(kr=r.isDirty,r.isDirty=Hr.isDirty=he(),pr=kr!==Hr.isDirty);const Fn=km(Nn(i,rt),We);kr=!!Nn(r.dirtyFields,rt),Fn?al(r.dirtyFields,rt):ja(r.dirtyFields,rt,!0),Hr.dirtyFields=r.dirtyFields,pr=pr||(_.dirtyFields||j.dirtyFields)&&kr!==!Fn}if(_t){const Fn=Nn(r.touchedFields,rt);Fn||(ja(r.touchedFields,rt,_t),Hr.touchedFields=r.touchedFields,pr=pr||(_.touchedFields||j.touchedFields)&&Fn!==_t)}pr&&rr&&N.state.next(Hr)}return pr?Hr:{}},K=(rt,We,_t,Gt)=>{const rr=Nn(r.errors,rt),pr=(_.isValid||j.isValid)&&ld(We)&&r.isValid!==We;if(e.delayError&&_t?(m=P(()=>R(rt,_t)),m(e.delayError)):(clearTimeout(g),m=null,_t?ja(r.errors,rt,_t):al(r.errors,rt)),(_t?!km(rr,_t):rr)||!Au(Gt)||pr){const kr={...Gt,...pr&&ld(We)?{isValid:We}:{},errors:r.errors,name:rt};r={...r,...kr},N.state.next(kr)}},Q=async rt=>{I(rt,!0);const We=await e.resolver(o,e.context,A4e(rt||a.mount,n,e.criteriaMode,e.shouldUseNativeValidation));return I(rt),We},te=async rt=>{const{errors:We}=await Q(rt);if(rt)for(const _t of rt){const Gt=Nn(We,_t);Gt?ja(r.errors,_t,Gt):al(r.errors,_t)}else r.errors=We;return We},X=async(rt,We,_t={valid:!0})=>{for(const Gt in rt){const rr=rt[Gt];if(rr){const{_f:pr,...kr}=rr;if(pr){const Hr=a.array.has(pr.name),Fn=rr._f&&P4e(rr._f);Fn&&_.validatingFields&&I([Gt],!0);const Os=await WX(rr,a.disabled,o,C,e.shouldUseNativeValidation&&!We,Hr);if(Fn&&_.validatingFields&&I([Gt]),Os[pr.name]&&(_t.valid=!1,We))break;!We&&(Nn(Os,pr.name)?Hr?L4e(r.errors,Os,pr.name):ja(r.errors,pr.name,Os[pr.name]):al(r.errors,pr.name))}!Au(kr)&&await X(kr,We,_t)}}return _t.valid},ie=()=>{for(const rt of a.unMount){const We=Nn(n,rt);We&&(We._f.refs?We._f.refs.every(_t=>!uz(_t)):!uz(We._f.ref))&>(rt)}a.unMount=new Set},he=(rt,We)=>!e.disabled&&(rt&&We&&ja(o,rt,We),!km(et(),i)),xe=(rt,We,_t)=>ehe(rt,a,{...c.mount?o:qo(We)?i:dp(rt)?{[rt]:We}:We},_t,We),pe=rt=>K8(Nn(c.mount?o:i,rt,e.shouldUnregister?Nn(i,rt,[]):[])),ve=(rt,We,_t={})=>{const Gt=Nn(n,rt);let rr=We;if(Gt){const pr=Gt._f;pr&&(!pr.disabled&&ja(o,rt,ahe(We,pr)),rr=FM(pr.ref)&&eu(We)?"":We,rhe(pr.ref)?[...pr.ref.options].forEach(kr=>kr.selected=rr.includes(kr.value)):pr.refs?AT(pr.ref)?pr.refs.forEach(kr=>{(!kr.defaultChecked||!kr.disabled)&&(Array.isArray(rr)?kr.checked=!!rr.find(Hr=>Hr===kr.value):kr.checked=rr===kr.value||!!rr)}):pr.refs.forEach(kr=>kr.checked=kr.value===rr):Q8(pr.ref)?pr.ref.value="":(pr.ref.value=rr,pr.ref.type||N.state.next({name:rt,values:jl(o)})))}(_t.shouldDirty||_t.shouldTouch)&&V(rt,rr,_t.shouldTouch,_t.shouldDirty,!0),_t.shouldValidate&&je(rt)},ge=(rt,We,_t)=>{for(const Gt in We){if(!We.hasOwnProperty(Gt))return;const rr=We[Gt],pr=rt+"."+Gt,kr=Nn(n,pr);(a.array.has(rt)||Zo(rr)||kr&&!kr._f)&&!Kv(rr)?ge(pr,rr,_t):ve(pr,rr,_t)}},ke=(rt,We,_t={})=>{const Gt=Nn(n,rt),rr=a.array.has(rt),pr=jl(We);ja(o,rt,pr),rr?(N.array.next({name:rt,values:jl(o)}),(_.isDirty||_.dirtyFields||j.isDirty||j.dirtyFields)&&_t.shouldDirty&&N.state.next({name:rt,dirtyFields:fC(i,o),isDirty:he(rt,pr)})):Gt&&!Gt._f&&!eu(pr)?ge(rt,pr,_t):ve(rt,pr,_t),VX(rt,a)&&N.state.next({...r,name:rt}),N.state.next({name:c.mount?rt:void 0,values:jl(o)})},Ce=async rt=>{c.mount=!0;const We=rt.target;let _t=We.name,Gt=!0;const rr=Nn(n,_t),pr=Fn=>{Gt=Number.isNaN(Fn)||Kv(Fn)&&isNaN(Fn.getTime())||km(Fn,Nn(o,_t,Fn))},kr=$X(e.mode),Hr=$X(e.reValidateMode);if(rr){let Fn,Os;const ia=We.type?BX(rr._f):Xde(rt),pa=rt.type===LM.BLUR||rt.type===LM.FOCUS_OUT,zo=!I4e(rr._f)&&!e.resolver&&!Nn(r.errors,_t)&&!rr._f.deps||R4e(pa,Nn(r.touchedFields,_t),r.isSubmitted,Hr,kr),Xo=VX(_t,a,pa);ja(o,_t,ia),pa?(rr._f.onBlur&&rr._f.onBlur(rt),m&&m(0)):rr._f.onChange&&rr._f.onChange(rt);const Xs=V(_t,ia,pa),Ma=!Au(Xs)||Xo;if(!pa&&N.state.next({name:_t,type:rt.type,values:jl(o)}),zo)return(_.isValid||j.isValid)&&(e.mode==="onBlur"?pa&&A():pa||A()),Ma&&N.state.next({name:_t,...Xo?{}:Xs});if(!pa&&Xo&&N.state.next({...r}),e.resolver){const{errors:Qo}=await Q([_t]);if(pr(ia),Gt){const ec=qX(r.errors,n,_t),yl=qX(Qo,n,ec.name||_t);Fn=yl.error,_t=yl.name,Os=Au(Qo)}}else I([_t],!0),Fn=(await WX(rr,a.disabled,o,C,e.shouldUseNativeValidation))[_t],I([_t]),pr(ia),Gt&&(Fn?Os=!1:(_.isValid||j.isValid)&&(Os=await X(n,!0)));Gt&&(rr._f.deps&&je(rr._f.deps),K(_t,Os,Fn,Xs))}},Se=(rt,We)=>{if(Nn(r.errors,We)&&rt.focus)return rt.focus(),1},je=async(rt,We={})=>{let _t,Gt;const rr=c2(rt);if(e.resolver){const pr=await te(qo(rt)?rt:rr);_t=Au(pr),Gt=rt?!rr.some(kr=>Nn(pr,kr)):_t}else rt?(Gt=(await Promise.all(rr.map(async pr=>{const kr=Nn(n,pr);return await X(kr&&kr._f?{[pr]:kr}:kr)}))).every(Boolean),!(!Gt&&!r.isValid)&&A()):Gt=_t=await X(n);return N.state.next({...!dp(rt)||(_.isValid||j.isValid)&&_t!==r.isValid?{}:{name:rt},...e.resolver||!rt?{isValid:_t}:{},errors:r.errors}),We.shouldFocus&&!Gt&&u2(n,Se,rt?rr:a.mount),Gt},et=rt=>{const We={...c.mount?o:i};return qo(rt)?We:dp(rt)?Nn(We,rt):rt.map(_t=>Nn(We,_t))},bt=(rt,We)=>({invalid:!!Nn((We||r).errors,rt),isDirty:!!Nn((We||r).dirtyFields,rt),error:Nn((We||r).errors,rt),isValidating:!!Nn(r.validatingFields,rt),isTouched:!!Nn((We||r).touchedFields,rt)}),_e=rt=>{rt&&c2(rt).forEach(We=>al(r.errors,We)),N.state.next({errors:rt?r.errors:{}})},Ye=(rt,We,_t)=>{const Gt=(Nn(n,rt,{_f:{}})._f||{}).ref,rr=Nn(r.errors,rt)||{},{ref:pr,message:kr,type:Hr,...Fn}=rr;ja(r.errors,rt,{...Fn,...We,ref:Gt}),N.state.next({name:rt,errors:r.errors,isValid:!1}),_t&&_t.shouldFocus&&Gt&&Gt.focus&&Gt.focus()},pt=(rt,We)=>hf(rt)?N.state.subscribe({next:_t=>"values"in _t&&rt(xe(void 0,We),_t)}):xe(rt,We,!0),nt=rt=>N.state.subscribe({next:We=>{O4e(rt.name,We.name,rt.exact)&&M4e(We,rt.formState||_,Lt,rt.reRenderRoot)&&rt.callback({values:{...o},...r,...We,defaultValues:i})}}).unsubscribe,Qt=rt=>(c.mount=!0,j={...j,...rt.formState},nt({...rt,formState:j})),gt=(rt,We={})=>{for(const _t of rt?c2(rt):a.mount)a.mount.delete(_t),a.array.delete(_t),We.keepValue||(al(n,_t),al(o,_t)),!We.keepError&&al(r.errors,_t),!We.keepDirty&&al(r.dirtyFields,_t),!We.keepTouched&&al(r.touchedFields,_t),!We.keepIsValidating&&al(r.validatingFields,_t),!e.shouldUnregister&&!We.keepDefaultValue&&al(i,_t);N.state.next({values:jl(o)}),N.state.next({...r,...We.keepDirty?{isDirty:he()}:{}}),!We.keepIsValid&&A()},Me=({disabled:rt,name:We})=>{(ld(rt)&&c.mount||rt||a.disabled.has(We))&&(rt?a.disabled.add(We):a.disabled.delete(We))},Oe=(rt,We={})=>{let _t=Nn(n,rt);const Gt=ld(We.disabled)||ld(e.disabled);return ja(n,rt,{..._t||{},_f:{..._t&&_t._f?_t._f:{ref:{name:rt}},name:rt,mount:!0,...We}}),a.mount.add(rt),_t?Me({disabled:ld(We.disabled)?We.disabled:e.disabled,name:rt}):W(rt,!0,We.value),{...Gt?{disabled:We.disabled||e.disabled}:{},...e.progressive?{required:!!We.required,min:pC(We.min),max:pC(We.max),minLength:pC(We.minLength),maxLength:pC(We.maxLength),pattern:pC(We.pattern)}:{},name:rt,onChange:Ce,onBlur:Ce,ref:rr=>{if(rr){Oe(rt,We),_t=Nn(n,rt);const pr=qo(rr.value)&&rr.querySelectorAll&&rr.querySelectorAll("input,select,textarea")[0]||rr,kr=k4e(pr),Hr=_t._f.refs||[];if(kr?Hr.find(Fn=>Fn===pr):pr===_t._f.ref)return;ja(n,rt,{_f:{..._t._f,...kr?{refs:[...Hr.filter(uz),pr,...Array.isArray(Nn(i,rt))?[{}]:[]],ref:{type:pr.type,name:rt}}:{ref:pr}}}),W(rt,!1,void 0,pr)}else _t=Nn(n,rt,{}),_t._f&&(_t._f.mount=!1),(e.shouldUnregister||We.shouldUnregister)&&!(Qde(a.array,rt)&&c.action)&&a.unMount.add(rt)}}},Ie=()=>e.shouldFocusError&&u2(n,Se,a.mount),Be=rt=>{ld(rt)&&(N.state.next({disabled:rt}),u2(n,(We,_t)=>{const Gt=Nn(n,_t);Gt&&(We.disabled=Gt._f.disabled||rt,Array.isArray(Gt._f.refs)&&Gt._f.refs.forEach(rr=>{rr.disabled=Gt._f.disabled||rt}))},0,!1))},Pe=(rt,We)=>async _t=>{let Gt;_t&&(_t.preventDefault&&_t.preventDefault(),_t.persist&&_t.persist());let rr=jl(o);if(N.state.next({isSubmitting:!0}),e.resolver){const{errors:pr,values:kr}=await Q();r.errors=pr,rr=jl(kr)}else await X(n);if(a.disabled.size)for(const pr of a.disabled)al(rr,pr);if(al(r.errors,"root"),Au(r.errors)){N.state.next({errors:{}});try{await rt(rr,_t)}catch(pr){Gt=pr}}else We&&await We({...r.errors},_t),Ie(),setTimeout(Ie);if(N.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:Au(r.errors)&&!Gt,submitCount:r.submitCount+1,errors:r.errors}),Gt)throw Gt},ut=(rt,We={})=>{Nn(n,rt)&&(qo(We.defaultValue)?ke(rt,jl(Nn(i,rt))):(ke(rt,We.defaultValue),ja(i,rt,jl(We.defaultValue))),We.keepTouched||al(r.touchedFields,rt),We.keepDirty||(al(r.dirtyFields,rt),r.isDirty=We.defaultValue?he(rt,jl(Nn(i,rt))):he()),We.keepError||(al(r.errors,rt),_.isValid&&A()),N.state.next({...r}))},jt=(rt,We={})=>{const _t=rt?jl(rt):i,Gt=jl(_t),rr=Au(rt),pr=rr?i:Gt;if(We.keepDefaultValues||(i=_t),!We.keepValues){if(We.keepDirtyValues){const kr=new Set([...a.mount,...Object.keys(fC(i,o))]);for(const Hr of Array.from(kr))Nn(r.dirtyFields,Hr)?ja(pr,Hr,Nn(o,Hr)):ke(Hr,Nn(pr,Hr))}else{if(G8&&qo(rt))for(const kr of a.mount){const Hr=Nn(n,kr);if(Hr&&Hr._f){const Fn=Array.isArray(Hr._f.refs)?Hr._f.refs[0]:Hr._f.ref;if(FM(Fn)){const Os=Fn.closest("form");if(Os){Os.reset();break}}}}if(We.keepFieldsRef)for(const kr of a.mount)ke(kr,Nn(pr,kr));else n={}}o=e.shouldUnregister?We.keepDefaultValues?jl(i):{}:jl(pr),N.array.next({values:{...pr}}),N.state.next({values:{...pr}})}a={mount:We.keepDirtyValues?a.mount:new Set,unMount:new Set,array:new Set,disabled:new Set,watch:new Set,watchAll:!1,focus:""},c.mount=!_.isValid||!!We.keepIsValid||!!We.keepDirtyValues,c.watch=!!e.shouldUnregister,N.state.next({submitCount:We.keepSubmitCount?r.submitCount:0,isDirty:rr?!1:We.keepDirty?r.isDirty:!!(We.keepDefaultValues&&!km(rt,i)),isSubmitted:We.keepIsSubmitted?r.isSubmitted:!1,dirtyFields:rr?{}:We.keepDirtyValues?We.keepDefaultValues&&o?fC(i,o):r.dirtyFields:We.keepDefaultValues&&rt?fC(i,rt):We.keepDirty?r.dirtyFields:{},touchedFields:We.keepTouched?r.touchedFields:{},errors:We.keepErrors?r.errors:{},isSubmitSuccessful:We.keepIsSubmitSuccessful?r.isSubmitSuccessful:!1,isSubmitting:!1})},$t=(rt,We)=>jt(hf(rt)?rt(o):rt,We),Ht=(rt,We={})=>{const _t=Nn(n,rt),Gt=_t&&_t._f;if(Gt){const rr=Gt.refs?Gt.refs[0]:Gt.ref;rr.focus&&(rr.focus(),We.shouldSelect&&hf(rr.select)&&rr.select())}},Lt=rt=>{r={...r,...rt}},Ar={control:{register:Oe,unregister:gt,getFieldState:bt,handleSubmit:Pe,setError:Ye,_subscribe:nt,_runSchema:Q,_focusError:Ie,_getWatch:xe,_getDirty:he,_setValid:A,_setFieldArray:O,_setDisabledField:Me,_setErrors:z,_getFieldArray:pe,_reset:jt,_resetDefaultValues:()=>hf(e.defaultValues)&&e.defaultValues().then(rt=>{$t(rt,e.resetOptions),N.state.next({isLoading:!1})}),_removeUnmounted:ie,_disableForm:Be,_subjects:N,_proxyFormState:_,get _fields(){return n},get _formValues(){return o},get _state(){return c},set _state(rt){c=rt},get _defaultValues(){return i},get _names(){return a},set _names(rt){a=rt},get _formState(){return r},get _options(){return e},set _options(rt){e={...e,...rt}}},subscribe:Qt,trigger:je,register:Oe,handleSubmit:Pe,watch:pt,setValue:ke,getValues:et,reset:$t,resetField:ut,clearErrors:_e,unregister:gt,setError:Ye,setFocus:Ht,getFieldState:bt};return{...Ar,formControl:Ar}}function eq(t={}){const e=Ve.useRef(void 0),r=Ve.useRef(void 0),[n,i]=Ve.useState({isDirty:!1,isValidating:!1,isLoading:hf(t.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},validatingFields:{},errors:t.errors||{},disabled:t.disabled||!1,isReady:!1,defaultValues:hf(t.defaultValues)?void 0:t.defaultValues});if(!e.current)if(t.formControl)e.current={...t.formControl,formState:n},t.defaultValues&&!hf(t.defaultValues)&&t.formControl.reset(t.defaultValues,t.resetOptions);else{const{formControl:c,...a}=z4e(t);e.current={...a,formState:n}}const o=e.current.control;return o._options=t,X8(()=>{const c=o._subscribe({formState:o._proxyFormState,callback:()=>i({...o._formState}),reRenderRoot:!0});return i(a=>({...a,isReady:!0})),o._formState.isReady=!0,c},[o]),Ve.useEffect(()=>o._disableForm(t.disabled),[o,t.disabled]),Ve.useEffect(()=>{t.mode&&(o._options.mode=t.mode),t.reValidateMode&&(o._options.reValidateMode=t.reValidateMode)},[o,t.mode,t.reValidateMode]),Ve.useEffect(()=>{t.errors&&(o._setErrors(t.errors),o._focusError())},[o,t.errors]),Ve.useEffect(()=>{t.shouldUnregister&&o._subjects.state.next({values:o._getWatch()})},[o,t.shouldUnregister]),Ve.useEffect(()=>{if(o._proxyFormState.isDirty){const c=o._getDirty();c!==n.isDirty&&o._subjects.state.next({isDirty:c})}},[o,n.isDirty]),Ve.useEffect(()=>{t.values&&!km(t.values,r.current)?(o._reset(t.values,{keepFieldsRef:!0,...o._options.resetOptions}),r.current=t.values,i(c=>({...c}))):o._resetDefaultValues()},[o,t.values]),Ve.useEffect(()=>{o._state.mount||(o._setValid(),o._state.mount=!0),o._state.watch&&(o._state.watch=!1,o._subjects.state.next({...o._formState})),o._removeUnmounted()}),e.current.formState=Jde(n,o),e.current}const GX=(t,e,r)=>{if(t&&"reportValidity"in t){const n=Nn(r,e);t.setCustomValidity(n&&n.message||""),t.reportValidity()}},lhe=(t,e)=>{for(const r in e.fields){const n=e.fields[r];n&&n.ref&&"reportValidity"in n.ref?GX(n.ref,r,t):n.refs&&n.refs.forEach(i=>GX(i,r,t))}},B4e=(t,e)=>{e.shouldUseNativeValidation&&lhe(t,e);const r={};for(const n in t){const i=Nn(e.fields,n),o=Object.assign(t[n]||{},{ref:i&&i.ref});if($4e(e.names||Object.keys(t),n)){const c=Object.assign({},Nn(r,n));ja(c,"root",o),ja(r,n,c)}else ja(r,n,o)}return r},$4e=(t,e)=>t.some(r=>r.startsWith(e+"."));var U4e=function(t,e){for(var r={};t.length;){var n=t[0],i=n.code,o=n.message,c=n.path.join(".");if(!r[c])if("unionErrors"in n){var a=n.unionErrors[0].errors[0];r[c]={message:a.message,type:a.code}}else r[c]={message:o,type:i};if("unionErrors"in n&&n.unionErrors.forEach(function(_){return _.errors.forEach(function(j){return t.push(j)})}),e){var m=r[c].types,g=m&&m[n.code];r[c]=the(c,e,r,i,g?[].concat(g,n.message):n.message)}t.shift()}return r},tq=function(t,e,r){return r===void 0&&(r={}),function(n,i,o){try{return Promise.resolve(function(c,a){try{var m=Promise.resolve(t[r.mode==="sync"?"parse":"parseAsync"](n,e)).then(function(g){return o.shouldUseNativeValidation&&lhe({},o),{errors:{},values:r.raw?n:g}})}catch(g){return a(g)}return m&&m.then?m.then(void 0,a):m}(0,function(c){if(function(a){return Array.isArray(a==null?void 0:a.errors)}(c))return{values:{},errors:B4e(U4e(c.errors,!o.shouldUseNativeValidation&&o.criteriaMode==="all"),o)};throw c}))}catch(c){return Promise.reject(c)}}};const rq=w4e,che=D.createContext({}),Sl=({...t})=>s.jsx(che.Provider,{value:{name:t.name},children:s.jsx(C4e,{...t})}),ED=()=>{const t=D.useContext(che),e=D.useContext(uhe),{getFieldState:r,formState:n}=TD(),i=r(t.name,n);if(!t)throw new Error("useFormField should be used within ");const{id:o}=e;return{id:o,name:t.name,formItemId:`${o}-form-item`,formDescriptionId:`${o}-form-item-description`,formMessageId:`${o}-form-item-message`,...i}},uhe=D.createContext({}),cl=D.forwardRef(({className:t,...e},r)=>{const n=D.useId();return s.jsx(uhe.Provider,{value:{id:n},children:s.jsx("div",{ref:r,className:ar("space-y-2",t),...e})})});cl.displayName="FormItem";const ul=D.forwardRef(({className:t,...e},r)=>{const{error:n,formItemId:i}=ED();return s.jsx(mt,{ref:r,className:ar(n&&"text-destructive",t),htmlFor:i,...e})});ul.displayName="FormLabel";const dl=D.forwardRef(({...t},e)=>{const{error:r,formItemId:n,formDescriptionId:i,formMessageId:o}=ED();return s.jsx(Cae,{ref:e,id:n,"aria-describedby":r?`${i} ${o}`:`${i}`,"aria-invalid":!!r,...t})});dl.displayName="FormControl";const PI=D.forwardRef(({className:t,...e},r)=>{const{formDescriptionId:n}=ED();return s.jsx("p",{ref:r,id:n,className:ar("text-sm text-muted-foreground",t),...e})});PI.displayName="FormDescription";const gf=D.forwardRef(({className:t,children:e,...r},n)=>{const{error:i,formMessageId:o}=ED(),c=i?String(i==null?void 0:i.message):e;return c?s.jsx("p",{ref:n,id:o,className:ar("text-sm font-medium text-destructive",t),...r,children:c}):null});gf.displayName="FormMessage";const mi=D.forwardRef(({className:t,...e},r)=>s.jsx("textarea",{className:ar("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",t),ref:r,...e}));mi.displayName="Textarea";function ck(t,[e,r]){return Math.min(r,Math.max(e,t))}function PT(t){const e=D.useRef({value:t,previous:t});return D.useMemo(()=>(e.current.value!==t&&(e.current.previous=e.current.value,e.current.value=t),e.current.previous),[t])}var V4e=[" ","Enter","ArrowUp","ArrowDown"],q4e=[" ","Enter"],L_="Select",[AD,PD,H4e]=hT(L_),[Vj]=Yo(L_,[H4e,gx]),ID=gx(),[W4e,bx]=Vj(L_),[G4e,K4e]=Vj(L_),dhe=t=>{const{__scopeSelect:e,children:r,open:n,defaultOpen:i,onOpenChange:o,value:c,defaultValue:a,onValueChange:m,dir:g,name:_,autoComplete:j,disabled:N,required:C,form:P}=t,A=ID(e),[I,O]=D.useState(null),[R,z]=D.useState(null),[W,V]=D.useState(!1),K=i0(g),[Q,te]=Uu({prop:n,defaultProp:i??!1,onChange:o,caller:L_}),[X,ie]=Uu({prop:c,defaultProp:a,onChange:m,caller:L_}),he=D.useRef(null),xe=I?P||!!I.closest("form"):!0,[pe,ve]=D.useState(new Set),ge=Array.from(pe).map(ke=>ke.props.value).join(";");return s.jsx(aD,{...A,children:s.jsxs(W4e,{required:C,scope:e,trigger:I,onTriggerChange:O,valueNode:R,onValueNodeChange:z,valueNodeHasChildren:W,onValueNodeHasChildrenChange:V,contentId:Al(),value:X,onValueChange:ie,open:Q,onOpenChange:te,dir:K,triggerPointerDownPosRef:he,disabled:N,children:[s.jsx(AD.Provider,{scope:e,children:s.jsx(G4e,{scope:t.__scopeSelect,onNativeOptionAdd:D.useCallback(ke=>{ve(Ce=>new Set(Ce).add(ke))},[]),onNativeOptionRemove:D.useCallback(ke=>{ve(Ce=>{const Se=new Set(Ce);return Se.delete(ke),Se})},[]),children:r})}),xe?s.jsxs(Rhe,{"aria-hidden":!0,required:C,tabIndex:-1,name:_,autoComplete:j,value:X,onChange:ke=>ie(ke.target.value),disabled:N,form:P,children:[X===void 0?s.jsx("option",{value:""}):null,Array.from(pe)]},ge):null]})})};dhe.displayName=L_;var hhe="SelectTrigger",fhe=D.forwardRef((t,e)=>{const{__scopeSelect:r,disabled:n=!1,...i}=t,o=ID(r),c=bx(hhe,r),a=c.disabled||n,m=vs(e,c.onTriggerChange),g=PD(r),_=D.useRef("touch"),[j,N,C]=Lhe(A=>{const I=g().filter(z=>!z.disabled),O=I.find(z=>z.value===c.value),R=Fhe(I,A,O);R!==void 0&&c.onValueChange(R.value)}),P=A=>{a||(c.onOpenChange(!0),C()),A&&(c.triggerPointerDownPosRef.current={x:Math.round(A.pageX),y:Math.round(A.pageY)})};return s.jsx(bT,{asChild:!0,...o,children:s.jsx(yn.button,{type:"button",role:"combobox","aria-controls":c.contentId,"aria-expanded":c.open,"aria-required":c.required,"aria-autocomplete":"none",dir:c.dir,"data-state":c.open?"open":"closed",disabled:a,"data-disabled":a?"":void 0,"data-placeholder":Dhe(c.value)?"":void 0,...i,ref:m,onClick:Yr(i.onClick,A=>{A.currentTarget.focus(),_.current!=="mouse"&&P(A)}),onPointerDown:Yr(i.onPointerDown,A=>{_.current=A.pointerType;const I=A.target;I.hasPointerCapture(A.pointerId)&&I.releasePointerCapture(A.pointerId),A.button===0&&A.ctrlKey===!1&&A.pointerType==="mouse"&&(P(A),A.preventDefault())}),onKeyDown:Yr(i.onKeyDown,A=>{const I=j.current!=="";!(A.ctrlKey||A.altKey||A.metaKey)&&A.key.length===1&&N(A.key),!(I&&A.key===" ")&&V4e.includes(A.key)&&(P(),A.preventDefault())})})})});fhe.displayName=hhe;var phe="SelectValue",mhe=D.forwardRef((t,e)=>{const{__scopeSelect:r,className:n,style:i,children:o,placeholder:c="",...a}=t,m=bx(phe,r),{onValueNodeHasChildrenChange:g}=m,_=o!==void 0,j=vs(e,m.onValueNodeChange);return Lo(()=>{g(_)},[g,_]),s.jsx(yn.span,{...a,ref:j,style:{pointerEvents:"none"},children:Dhe(m.value)?s.jsx(s.Fragment,{children:c}):o})});mhe.displayName=phe;var Z4e="SelectIcon",ghe=D.forwardRef((t,e)=>{const{__scopeSelect:r,children:n,...i}=t;return s.jsx(yn.span,{"aria-hidden":!0,...i,ref:e,children:n||"▼"})});ghe.displayName=Z4e;var Y4e="SelectPortal",yhe=t=>s.jsx(Tj,{asChild:!0,...t});yhe.displayName=Y4e;var F_="SelectContent",xhe=D.forwardRef((t,e)=>{const r=bx(F_,t.__scopeSelect),[n,i]=D.useState();if(Lo(()=>{i(new DocumentFragment)},[]),!r.open){const o=n;return o?e0.createPortal(s.jsx(vhe,{scope:t.__scopeSelect,children:s.jsx(AD.Slot,{scope:t.__scopeSelect,children:s.jsx("div",{children:t.children})})}),o):null}return s.jsx(_he,{...t,ref:e})});xhe.displayName=F_;var ef=10,[vhe,wx]=Vj(F_),X4e="SelectContentImpl",Q4e=nx("SelectContent.RemoveScroll"),_he=D.forwardRef((t,e)=>{const{__scopeSelect:r,position:n="item-aligned",onCloseAutoFocus:i,onEscapeKeyDown:o,onPointerDownOutside:c,side:a,sideOffset:m,align:g,alignOffset:_,arrowPadding:j,collisionBoundary:N,collisionPadding:C,sticky:P,hideWhenDetached:A,avoidCollisions:I,...O}=t,R=bx(F_,r),[z,W]=D.useState(null),[V,K]=D.useState(null),Q=vs(e,gt=>W(gt)),[te,X]=D.useState(null),[ie,he]=D.useState(null),xe=PD(r),[pe,ve]=D.useState(!1),ge=D.useRef(!1);D.useEffect(()=>{if(z)return yD(z)},[z]),mD();const ke=D.useCallback(gt=>{const[Me,...Oe]=xe().map(Pe=>Pe.ref.current),[Ie]=Oe.slice(-1),Be=document.activeElement;for(const Pe of gt)if(Pe===Be||(Pe==null||Pe.scrollIntoView({block:"nearest"}),Pe===Me&&V&&(V.scrollTop=0),Pe===Ie&&V&&(V.scrollTop=V.scrollHeight),Pe==null||Pe.focus(),document.activeElement!==Be))return},[xe,V]),Ce=D.useCallback(()=>ke([te,z]),[ke,te,z]);D.useEffect(()=>{pe&&Ce()},[pe,Ce]);const{onOpenChange:Se,triggerPointerDownPosRef:je}=R;D.useEffect(()=>{if(z){let gt={x:0,y:0};const Me=Ie=>{var Be,Pe;gt={x:Math.abs(Math.round(Ie.pageX)-(((Be=je.current)==null?void 0:Be.x)??0)),y:Math.abs(Math.round(Ie.pageY)-(((Pe=je.current)==null?void 0:Pe.y)??0))}},Oe=Ie=>{gt.x<=10&>.y<=10?Ie.preventDefault():z.contains(Ie.target)||Se(!1),document.removeEventListener("pointermove",Me),je.current=null};return je.current!==null&&(document.addEventListener("pointermove",Me),document.addEventListener("pointerup",Oe,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",Me),document.removeEventListener("pointerup",Oe,{capture:!0})}}},[z,Se,je]),D.useEffect(()=>{const gt=()=>Se(!1);return window.addEventListener("blur",gt),window.addEventListener("resize",gt),()=>{window.removeEventListener("blur",gt),window.removeEventListener("resize",gt)}},[Se]);const[et,bt]=Lhe(gt=>{const Me=xe().filter(Be=>!Be.disabled),Oe=Me.find(Be=>Be.ref.current===document.activeElement),Ie=Fhe(Me,gt,Oe);Ie&&setTimeout(()=>Ie.ref.current.focus())}),_e=D.useCallback((gt,Me,Oe)=>{const Ie=!ge.current&&!Oe;(R.value!==void 0&&R.value===Me||Ie)&&(X(gt),Ie&&(ge.current=!0))},[R.value]),Ye=D.useCallback(()=>z==null?void 0:z.focus(),[z]),pt=D.useCallback((gt,Me,Oe)=>{const Ie=!ge.current&&!Oe;(R.value!==void 0&&R.value===Me||Ie)&&he(gt)},[R.value]),nt=n==="popper"?C$:bhe,Qt=nt===C$?{side:a,sideOffset:m,align:g,alignOffset:_,arrowPadding:j,collisionBoundary:N,collisionPadding:C,sticky:P,hideWhenDetached:A,avoidCollisions:I}:{};return s.jsx(vhe,{scope:r,content:z,viewport:V,onViewportChange:K,itemRefCallback:_e,selectedItem:te,onItemLeave:Ye,itemTextRefCallback:pt,focusSelectedItem:Ce,selectedItemText:ie,position:n,isPositioned:pe,searchRef:et,children:s.jsx(ST,{as:Q4e,allowPinchZoom:!0,children:s.jsx(jT,{asChild:!0,trapped:R.open,onMountAutoFocus:gt=>{gt.preventDefault()},onUnmountAutoFocus:Yr(i,gt=>{var Me;(Me=R.trigger)==null||Me.focus({preventScroll:!0}),gt.preventDefault()}),children:s.jsx(t0,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:o,onPointerDownOutside:c,onFocusOutside:gt=>gt.preventDefault(),onDismiss:()=>R.onOpenChange(!1),children:s.jsx(nt,{role:"listbox",id:R.contentId,"data-state":R.open?"open":"closed",dir:R.dir,onContextMenu:gt=>gt.preventDefault(),...O,...Qt,onPlaced:()=>ve(!0),ref:Q,style:{display:"flex",flexDirection:"column",outline:"none",...O.style},onKeyDown:Yr(O.onKeyDown,gt=>{const Me=gt.ctrlKey||gt.altKey||gt.metaKey;if(gt.key==="Tab"&>.preventDefault(),!Me&>.key.length===1&&bt(gt.key),["ArrowUp","ArrowDown","Home","End"].includes(gt.key)){let Ie=xe().filter(Be=>!Be.disabled).map(Be=>Be.ref.current);if(["ArrowUp","End"].includes(gt.key)&&(Ie=Ie.slice().reverse()),["ArrowUp","ArrowDown"].includes(gt.key)){const Be=gt.target,Pe=Ie.indexOf(Be);Ie=Ie.slice(Pe+1)}setTimeout(()=>ke(Ie)),gt.preventDefault()}})})})})})})});_he.displayName=X4e;var J4e="SelectItemAlignedPosition",bhe=D.forwardRef((t,e)=>{const{__scopeSelect:r,onPlaced:n,...i}=t,o=bx(F_,r),c=wx(F_,r),[a,m]=D.useState(null),[g,_]=D.useState(null),j=vs(e,Q=>_(Q)),N=PD(r),C=D.useRef(!1),P=D.useRef(!0),{viewport:A,selectedItem:I,selectedItemText:O,focusSelectedItem:R}=c,z=D.useCallback(()=>{if(o.trigger&&o.valueNode&&a&&g&&A&&I&&O){const Q=o.trigger.getBoundingClientRect(),te=g.getBoundingClientRect(),X=o.valueNode.getBoundingClientRect(),ie=O.getBoundingClientRect();if(o.dir!=="rtl"){const Be=ie.left-te.left,Pe=X.left-Be,ut=Q.left-Pe,jt=Q.width+ut,$t=Math.max(jt,te.width),Ht=window.innerWidth-ef,Lt=ck(Pe,[ef,Math.max(ef,Ht-$t)]);a.style.minWidth=jt+"px",a.style.left=Lt+"px"}else{const Be=te.right-ie.right,Pe=window.innerWidth-X.right-Be,ut=window.innerWidth-Q.right-Pe,jt=Q.width+ut,$t=Math.max(jt,te.width),Ht=window.innerWidth-ef,Lt=ck(Pe,[ef,Math.max(ef,Ht-$t)]);a.style.minWidth=jt+"px",a.style.right=Lt+"px"}const he=N(),xe=window.innerHeight-ef*2,pe=A.scrollHeight,ve=window.getComputedStyle(g),ge=parseInt(ve.borderTopWidth,10),ke=parseInt(ve.paddingTop,10),Ce=parseInt(ve.borderBottomWidth,10),Se=parseInt(ve.paddingBottom,10),je=ge+ke+pe+Se+Ce,et=Math.min(I.offsetHeight*5,je),bt=window.getComputedStyle(A),_e=parseInt(bt.paddingTop,10),Ye=parseInt(bt.paddingBottom,10),pt=Q.top+Q.height/2-ef,nt=xe-pt,Qt=I.offsetHeight/2,gt=I.offsetTop+Qt,Me=ge+ke+gt,Oe=je-Me;if(Me<=pt){const Be=he.length>0&&I===he[he.length-1].ref.current;a.style.bottom="0px";const Pe=g.clientHeight-A.offsetTop-A.offsetHeight,ut=Math.max(nt,Qt+(Be?Ye:0)+Pe+Ce),jt=Me+ut;a.style.height=jt+"px"}else{const Be=he.length>0&&I===he[0].ref.current;a.style.top="0px";const ut=Math.max(pt,ge+A.offsetTop+(Be?_e:0)+Qt)+Oe;a.style.height=ut+"px",A.scrollTop=Me-pt+A.offsetTop}a.style.margin=`${ef}px 0`,a.style.minHeight=et+"px",a.style.maxHeight=xe+"px",n==null||n(),requestAnimationFrame(()=>C.current=!0)}},[N,o.trigger,o.valueNode,a,g,A,I,O,o.dir,n]);Lo(()=>z(),[z]);const[W,V]=D.useState();Lo(()=>{g&&V(window.getComputedStyle(g).zIndex)},[g]);const K=D.useCallback(Q=>{Q&&P.current===!0&&(z(),R==null||R(),P.current=!1)},[z,R]);return s.jsx(t3e,{scope:r,contentWrapper:a,shouldExpandOnScrollRef:C,onScrollButtonChange:K,children:s.jsx("div",{ref:m,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:W},children:s.jsx(yn.div,{...i,ref:j,style:{boxSizing:"border-box",maxHeight:"100%",...i.style}})})})});bhe.displayName=J4e;var e3e="SelectPopperPosition",C$=D.forwardRef((t,e)=>{const{__scopeSelect:r,align:n="start",collisionPadding:i=ef,...o}=t,c=ID(r);return s.jsx(oD,{...c,...o,ref:e,align:n,collisionPadding:i,style:{boxSizing:"border-box",...o.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});C$.displayName=e3e;var[t3e,nq]=Vj(F_,{}),k$="SelectViewport",whe=D.forwardRef((t,e)=>{const{__scopeSelect:r,nonce:n,...i}=t,o=wx(k$,r),c=nq(k$,r),a=vs(e,o.onViewportChange),m=D.useRef(0);return s.jsxs(s.Fragment,{children:[s.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:n}),s.jsx(AD.Slot,{scope:r,children:s.jsx(yn.div,{"data-radix-select-viewport":"",role:"presentation",...i,ref:a,style:{position:"relative",flex:1,overflow:"hidden auto",...i.style},onScroll:Yr(i.onScroll,g=>{const _=g.currentTarget,{contentWrapper:j,shouldExpandOnScrollRef:N}=c;if(N!=null&&N.current&&j){const C=Math.abs(m.current-_.scrollTop);if(C>0){const P=window.innerHeight-ef*2,A=parseFloat(j.style.minHeight),I=parseFloat(j.style.height),O=Math.max(A,I);if(O0?W:0,j.style.justifyContent="flex-end")}}}m.current=_.scrollTop})})})]})});whe.displayName=k$;var jhe="SelectGroup",[r3e,n3e]=Vj(jhe),s3e=D.forwardRef((t,e)=>{const{__scopeSelect:r,...n}=t,i=Al();return s.jsx(r3e,{scope:r,id:i,children:s.jsx(yn.div,{role:"group","aria-labelledby":i,...n,ref:e})})});s3e.displayName=jhe;var She="SelectLabel",Nhe=D.forwardRef((t,e)=>{const{__scopeSelect:r,...n}=t,i=n3e(She,r);return s.jsx(yn.div,{id:i.id,...n,ref:e})});Nhe.displayName=She;var $M="SelectItem",[i3e,Che]=Vj($M),khe=D.forwardRef((t,e)=>{const{__scopeSelect:r,value:n,disabled:i=!1,textValue:o,...c}=t,a=bx($M,r),m=wx($M,r),g=a.value===n,[_,j]=D.useState(o??""),[N,C]=D.useState(!1),P=vs(e,R=>{var z;return(z=m.itemRefCallback)==null?void 0:z.call(m,R,n,i)}),A=Al(),I=D.useRef("touch"),O=()=>{i||(a.onValueChange(n),a.onOpenChange(!1))};if(n==="")throw new Error("A must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return s.jsx(i3e,{scope:r,value:n,disabled:i,textId:A,isSelected:g,onItemTextChange:D.useCallback(R=>{j(z=>z||((R==null?void 0:R.textContent)??"").trim())},[]),children:s.jsx(AD.ItemSlot,{scope:r,value:n,disabled:i,textValue:_,children:s.jsx(yn.div,{role:"option","aria-labelledby":A,"data-highlighted":N?"":void 0,"aria-selected":g&&N,"data-state":g?"checked":"unchecked","aria-disabled":i||void 0,"data-disabled":i?"":void 0,tabIndex:i?void 0:-1,...c,ref:P,onFocus:Yr(c.onFocus,()=>C(!0)),onBlur:Yr(c.onBlur,()=>C(!1)),onClick:Yr(c.onClick,()=>{I.current!=="mouse"&&O()}),onPointerUp:Yr(c.onPointerUp,()=>{I.current==="mouse"&&O()}),onPointerDown:Yr(c.onPointerDown,R=>{I.current=R.pointerType}),onPointerMove:Yr(c.onPointerMove,R=>{var z;I.current=R.pointerType,i?(z=m.onItemLeave)==null||z.call(m):I.current==="mouse"&&R.currentTarget.focus({preventScroll:!0})}),onPointerLeave:Yr(c.onPointerLeave,R=>{var z;R.currentTarget===document.activeElement&&((z=m.onItemLeave)==null||z.call(m))}),onKeyDown:Yr(c.onKeyDown,R=>{var W;((W=m.searchRef)==null?void 0:W.current)!==""&&R.key===" "||(q4e.includes(R.key)&&O(),R.key===" "&&R.preventDefault())})})})})});khe.displayName=$M;var $C="SelectItemText",The=D.forwardRef((t,e)=>{const{__scopeSelect:r,className:n,style:i,...o}=t,c=bx($C,r),a=wx($C,r),m=Che($C,r),g=K4e($C,r),[_,j]=D.useState(null),N=vs(e,O=>j(O),m.onItemTextChange,O=>{var R;return(R=a.itemTextRefCallback)==null?void 0:R.call(a,O,m.value,m.disabled)}),C=_==null?void 0:_.textContent,P=D.useMemo(()=>s.jsx("option",{value:m.value,disabled:m.disabled,children:C},m.value),[m.disabled,m.value,C]),{onNativeOptionAdd:A,onNativeOptionRemove:I}=g;return Lo(()=>(A(P),()=>I(P)),[A,I,P]),s.jsxs(s.Fragment,{children:[s.jsx(yn.span,{id:m.textId,...o,ref:N}),m.isSelected&&c.valueNode&&!c.valueNodeHasChildren?e0.createPortal(o.children,c.valueNode):null]})});The.displayName=$C;var Ehe="SelectItemIndicator",Ahe=D.forwardRef((t,e)=>{const{__scopeSelect:r,...n}=t;return Che(Ehe,r).isSelected?s.jsx(yn.span,{"aria-hidden":!0,...n,ref:e}):null});Ahe.displayName=Ehe;var T$="SelectScrollUpButton",Phe=D.forwardRef((t,e)=>{const r=wx(T$,t.__scopeSelect),n=nq(T$,t.__scopeSelect),[i,o]=D.useState(!1),c=vs(e,n.onScrollButtonChange);return Lo(()=>{if(r.viewport&&r.isPositioned){let a=function(){const g=m.scrollTop>0;o(g)};const m=r.viewport;return a(),m.addEventListener("scroll",a),()=>m.removeEventListener("scroll",a)}},[r.viewport,r.isPositioned]),i?s.jsx(Mhe,{...t,ref:c,onAutoScroll:()=>{const{viewport:a,selectedItem:m}=r;a&&m&&(a.scrollTop=a.scrollTop-m.offsetHeight)}}):null});Phe.displayName=T$;var E$="SelectScrollDownButton",Ihe=D.forwardRef((t,e)=>{const r=wx(E$,t.__scopeSelect),n=nq(E$,t.__scopeSelect),[i,o]=D.useState(!1),c=vs(e,n.onScrollButtonChange);return Lo(()=>{if(r.viewport&&r.isPositioned){let a=function(){const g=m.scrollHeight-m.clientHeight,_=Math.ceil(m.scrollTop)m.removeEventListener("scroll",a)}},[r.viewport,r.isPositioned]),i?s.jsx(Mhe,{...t,ref:c,onAutoScroll:()=>{const{viewport:a,selectedItem:m}=r;a&&m&&(a.scrollTop=a.scrollTop+m.offsetHeight)}}):null});Ihe.displayName=E$;var Mhe=D.forwardRef((t,e)=>{const{__scopeSelect:r,onAutoScroll:n,...i}=t,o=wx("SelectScrollButton",r),c=D.useRef(null),a=PD(r),m=D.useCallback(()=>{c.current!==null&&(window.clearInterval(c.current),c.current=null)},[]);return D.useEffect(()=>()=>m(),[m]),Lo(()=>{var _;const g=a().find(j=>j.ref.current===document.activeElement);(_=g==null?void 0:g.ref.current)==null||_.scrollIntoView({block:"nearest"})},[a]),s.jsx(yn.div,{"aria-hidden":!0,...i,ref:e,style:{flexShrink:0,...i.style},onPointerDown:Yr(i.onPointerDown,()=>{c.current===null&&(c.current=window.setInterval(n,50))}),onPointerMove:Yr(i.onPointerMove,()=>{var g;(g=o.onItemLeave)==null||g.call(o),c.current===null&&(c.current=window.setInterval(n,50))}),onPointerLeave:Yr(i.onPointerLeave,()=>{m()})})}),a3e="SelectSeparator",Ohe=D.forwardRef((t,e)=>{const{__scopeSelect:r,...n}=t;return s.jsx(yn.div,{"aria-hidden":!0,...n,ref:e})});Ohe.displayName=a3e;var A$="SelectArrow",o3e=D.forwardRef((t,e)=>{const{__scopeSelect:r,...n}=t,i=ID(r),o=bx(A$,r),c=wx(A$,r);return o.open&&c.position==="popper"?s.jsx(lD,{...i,...n,ref:e}):null});o3e.displayName=A$;var l3e="SelectBubbleInput",Rhe=D.forwardRef(({__scopeSelect:t,value:e,...r},n)=>{const i=D.useRef(null),o=vs(n,i),c=PT(e);return D.useEffect(()=>{const a=i.current;if(!a)return;const m=window.HTMLSelectElement.prototype,_=Object.getOwnPropertyDescriptor(m,"value").set;if(c!==e&&_){const j=new Event("change",{bubbles:!0});_.call(a,e),a.dispatchEvent(j)}},[c,e]),s.jsx(yn.select,{...r,style:{...Iae,...r.style},ref:o,defaultValue:e})});Rhe.displayName=l3e;function Dhe(t){return t===""||t===void 0}function Lhe(t){const e=Oo(t),r=D.useRef(""),n=D.useRef(0),i=D.useCallback(c=>{const a=r.current+c;e(a),function m(g){r.current=g,window.clearTimeout(n.current),g!==""&&(n.current=window.setTimeout(()=>m(""),1e3))}(a)},[e]),o=D.useCallback(()=>{r.current="",window.clearTimeout(n.current)},[]);return D.useEffect(()=>()=>window.clearTimeout(n.current),[]),[r,i,o]}function Fhe(t,e,r){const i=e.length>1&&Array.from(e).every(g=>g===e[0])?e[0]:e,o=r?t.indexOf(r):-1;let c=c3e(t,Math.max(o,0));i.length===1&&(c=c.filter(g=>g!==r));const m=c.find(g=>g.textValue.toLowerCase().startsWith(i.toLowerCase()));return m!==r?m:void 0}function c3e(t,e){return t.map((r,n)=>t[(e+n)%t.length])}var u3e=dhe,zhe=fhe,d3e=mhe,h3e=ghe,f3e=yhe,Bhe=xhe,p3e=whe,$he=Nhe,Uhe=khe,m3e=The,g3e=Ahe,Vhe=Phe,qhe=Ihe,Hhe=Ohe;const Kn=u3e,Zn=d3e,qn=D.forwardRef(({className:t,children:e,...r},n)=>s.jsxs(zhe,{ref:n,className:ar("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",t),...r,children:[e,s.jsx(h3e,{asChild:!0,children:s.jsx(pT,{className:"h-4 w-4 opacity-50"})})]}));qn.displayName=zhe.displayName;const Whe=D.forwardRef(({className:t,...e},r)=>s.jsx(Vhe,{ref:r,className:ar("flex cursor-default items-center justify-center py-1",t),...e,children:s.jsx(W6,{className:"h-4 w-4"})}));Whe.displayName=Vhe.displayName;const Ghe=D.forwardRef(({className:t,...e},r)=>s.jsx(qhe,{ref:r,className:ar("flex cursor-default items-center justify-center py-1",t),...e,children:s.jsx(pT,{className:"h-4 w-4"})}));Ghe.displayName=qhe.displayName;const Hn=D.forwardRef(({className:t,children:e,position:r="popper",...n},i)=>s.jsx(f3e,{children:s.jsxs(Bhe,{ref:i,className:ar("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",r==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",t),position:r,...n,children:[s.jsx(Whe,{}),s.jsx(p3e,{className:ar("p-1",r==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:e}),s.jsx(Ghe,{})]})}));Hn.displayName=Bhe.displayName;const y3e=D.forwardRef(({className:t,...e},r)=>s.jsx($he,{ref:r,className:ar("py-1.5 pl-8 pr-2 text-sm font-semibold",t),...e}));y3e.displayName=$he.displayName;const _r=D.forwardRef(({className:t,children:e,...r},n)=>s.jsxs(Uhe,{ref:n,className:ar("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",t),...r,children:[s.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:s.jsx(g3e,{children:s.jsx(ru,{className:"h-4 w-4"})})}),s.jsx(m3e,{children:e})]}));_r.displayName=Uhe.displayName;const x3e=D.forwardRef(({className:t,...e},r)=>s.jsx(Hhe,{ref:r,className:ar("-mx-1 my-1 h-px bg-muted",t),...e}));x3e.displayName=Hhe.displayName;const v3e=wD({category:Tue(["general","technology","crm","marketing"]),subject:id().min(5,"Subject must be at least 5 characters").max(200),description:id().min(20,"Please provide more details (at least 20 characters)").max(2e3)}),_3e={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function P$({trigger:t}){const[e,r]=D.useState(!1),[n,i]=D.useState(!1),{user:o}=rn(),c=eq({resolver:tq(v3e),defaultValues:{category:"general",subject:"",description:""}}),a=async m=>{if(!o){Dt.error("You must be logged in to submit a ticket");return}i(!0);try{const{error:g}=await ae.from("support_tickets").insert({user_id:o.id,category:m.category,subject:m.subject,description:m.description});if(g)throw g;try{await ae.functions.invoke("support-ticket-notify",{body:{category:_3e[m.category],subject:m.subject}})}catch(_){console.log("Notification send attempted:",_)}Dt.success("Support ticket submitted successfully!"),c.reset(),r(!1)}catch(g){console.error("Error submitting ticket:",g),Dt.error("Failed to submit ticket. Please try again.")}finally{i(!1)}};return s.jsxs(mn,{open:e,onOpenChange:r,children:[s.jsx(Do,{asChild:!0,children:t||s.jsxs(de,{variant:"ghost",size:"icon",className:"relative",children:[s.jsx(R2e,{className:"h-5 w-5"}),s.jsx("span",{className:"sr-only",children:"Support"})]})}),s.jsxs(pn,{className:"sm:max-w-[500px]",children:[s.jsxs(xn,{children:[s.jsx(gn,{children:"Need Help?"}),s.jsx(fi,{children:"Submit a support ticket and we'll get back to you as soon as possible."})]}),s.jsxs("div",{className:"flex items-center gap-2 p-3 bg-muted rounded-lg mb-4",children:[s.jsx(Yl,{className:"h-4 w-4 text-muted-foreground"}),s.jsxs("span",{className:"text-sm text-muted-foreground",children:["You can also text us at: ",s.jsx("span",{className:"font-medium text-foreground",children:"1-866-527-8668"})]})]}),s.jsx(rq,{...c,children:s.jsxs("form",{onSubmit:c.handleSubmit(a),className:"space-y-4",children:[s.jsx(Sl,{control:c.control,name:"category",render:({field:m})=>s.jsxs(cl,{children:[s.jsx(ul,{children:"Category"}),s.jsxs(Kn,{onValueChange:m.onChange,defaultValue:m.value,children:[s.jsx(dl,{children:s.jsx(qn,{children:s.jsx(Zn,{placeholder:"Select a category"})})}),s.jsxs(Hn,{children:[s.jsx(_r,{value:"general",children:"General Support"}),s.jsx(_r,{value:"technology",children:"Technology Support"}),s.jsx(_r,{value:"crm",children:"CRM Support"}),s.jsx(_r,{value:"marketing",children:"Marketing Support"})]})]}),s.jsx(gf,{})]})}),s.jsx(Sl,{control:c.control,name:"subject",render:({field:m})=>s.jsxs(cl,{children:[s.jsx(ul,{children:"Subject"}),s.jsx(dl,{children:s.jsx(Et,{placeholder:"Brief description of your issue",...m})}),s.jsx(gf,{})]})}),s.jsx(Sl,{control:c.control,name:"description",render:({field:m})=>s.jsxs(cl,{children:[s.jsx(ul,{children:"Description"}),s.jsx(dl,{children:s.jsx(mi,{placeholder:"Please describe your issue in detail...",className:"min-h-[120px]",...m})}),s.jsx(gf,{})]})}),s.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[s.jsx(de,{type:"button",variant:"outline",onClick:()=>r(!1),children:"Cancel"}),s.jsx(de,{type:"submit",disabled:n,children:n?"Submitting...":"Submit Ticket"})]})]})})]})]})}const b3e=Ej("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground"}},defaultVariants:{variant:"default"}});function ir({className:t,variant:e,...r}){return s.jsx("div",{className:ar(b3e({variant:e}),t),...r})}function As(t){const e=Object.prototype.toString.call(t);return t instanceof Date||typeof t=="object"&&e==="[object Date]"?new t.constructor(+t):typeof t=="number"||e==="[object Number]"||typeof t=="string"||e==="[object String]"?new Date(t):new Date(NaN)}function uu(t,e){return t instanceof Date?new t.constructor(e):new Date(e)}function hc(t,e){const r=As(t);return isNaN(e)?uu(t,NaN):(e&&r.setDate(r.getDate()+e),r)}function gh(t,e){const r=As(t);if(isNaN(e))return uu(t,NaN);if(!e)return r;const n=r.getDate(),i=uu(t,r.getTime());i.setMonth(r.getMonth()+e+1,0);const o=i.getDate();return n>=o?i:(r.setFullYear(i.getFullYear(),i.getMonth(),n),r)}function Khe(t,e){const r=+As(t);return uu(t,r+e)}const sq=6048e5,w3e=864e5,j3e=6e4,S3e=36e5,PP=43200,KX=1440;function Zhe(t,e){return Khe(t,e*S3e)}let N3e={};function qj(){return N3e}function Np(t,e){var a,m,g,_;const r=qj(),n=(e==null?void 0:e.weekStartsOn)??((m=(a=e==null?void 0:e.locale)==null?void 0:a.options)==null?void 0:m.weekStartsOn)??r.weekStartsOn??((_=(g=r.locale)==null?void 0:g.options)==null?void 0:_.weekStartsOn)??0,i=As(t),o=i.getDay(),c=(o=i.getTime()?r+1:e.getTime()>=c.getTime()?r:r-1}function Cp(t){const e=As(t);return e.setHours(0,0,0,0),e}function W1(t){const e=As(t),r=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));return r.setUTCFullYear(e.getFullYear()),+t-+r}function yf(t,e){const r=Cp(t),n=Cp(e),i=+r-W1(r),o=+n-W1(n);return Math.round((i-o)/w3e)}function C3e(t){const e=Yhe(t),r=uu(t,0);return r.setFullYear(e,0,4),r.setHours(0,0,0,0),z_(r)}function Xhe(t,e){return Khe(t,e*j3e)}function I$(t,e){const r=e*7;return hc(t,r)}function k3e(t,e){return gh(t,e*12)}function T3e(t){let e;return t.forEach(function(r){const n=As(r);(e===void 0||e{const n=As(r);(!e||e>n||isNaN(+n))&&(e=n)}),e||new Date(NaN)}function II(t,e){const r=As(t),n=As(e),i=r.getTime()-n.getTime();return i<0?-1:i>0?1:i}function A3e(t){return uu(t,Date.now())}function Wo(t,e){const r=Cp(t),n=Cp(e);return+r==+n}function iq(t){return t instanceof Date||typeof t=="object"&&Object.prototype.toString.call(t)==="[object Date]"}function P3e(t){if(!iq(t)&&typeof t!="number")return!1;const e=As(t);return!isNaN(Number(e))}function G1(t,e){const r=As(t),n=As(e),i=r.getFullYear()-n.getFullYear(),o=r.getMonth()-n.getMonth();return i*12+o}function I3e(t,e,r){const n=Np(t,r),i=Np(e,r),o=+n-W1(n),c=+i-W1(i);return Math.round((o-c)/sq)}function Qhe(t,e){const r=As(t),n=As(e),i=ZX(r,n),o=Math.abs(yf(r,n));r.setDate(r.getDate()-i*o);const c=+(ZX(r,n)===-i),a=i*(o-c);return a===0?0:a}function ZX(t,e){const r=t.getFullYear()-e.getFullYear()||t.getMonth()-e.getMonth()||t.getDate()-e.getDate()||t.getHours()-e.getHours()||t.getMinutes()-e.getMinutes()||t.getSeconds()-e.getSeconds()||t.getMilliseconds()-e.getMilliseconds();return r<0?-1:r>0?1:r}function M3e(t){return e=>{const n=(t?Math[t]:Math.trunc)(e);return n===0?0:n}}function O3e(t,e){return+As(t)-+As(e)}function R3e(t){const e=As(t);return e.setHours(23,59,59,999),e}function MD(t){const e=As(t),r=e.getMonth();return e.setFullYear(e.getFullYear(),r+1,0),e.setHours(23,59,59,999),e}function D3e(t){const e=As(t);return+R3e(e)==+MD(e)}function L3e(t,e){const r=As(t),n=As(e),i=II(r,n),o=Math.abs(G1(r,n));let c;if(o<1)c=0;else{r.getMonth()===1&&r.getDate()>27&&r.setDate(30),r.setMonth(r.getMonth()-i*o);let a=II(r,n)===-i;D3e(As(t))&&o===1&&II(t,n)===1&&(a=!1),c=i*(o-Number(a))}return c===0?0:c}function F3e(t,e,r){const n=O3e(t,e)/1e3;return M3e(r==null?void 0:r.roundingMethod)(n)}function zu(t){const e=As(t);return e.setDate(1),e.setHours(0,0,0,0),e}function Jhe(t){const e=As(t),r=uu(t,0);return r.setFullYear(e.getFullYear(),0,1),r.setHours(0,0,0,0),r}function aq(t,e){var a,m,g,_;const r=qj(),n=(e==null?void 0:e.weekStartsOn)??((m=(a=e==null?void 0:e.locale)==null?void 0:a.options)==null?void 0:m.weekStartsOn)??r.weekStartsOn??((_=(g=r.locale)==null?void 0:g.options)==null?void 0:_.weekStartsOn)??0,i=As(t),o=i.getDay(),c=(o{let n;const i=z3e[t];return typeof i=="string"?n=i:e===1?n=i.one:n=i.other.replace("{{count}}",e.toString()),r!=null&&r.addSuffix?r.comparison&&r.comparison>0?"in "+n:n+" ago":n};function dz(t){return(e={})=>{const r=e.width?String(e.width):t.defaultWidth;return t.formats[r]||t.formats[t.defaultWidth]}}const $3e={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},U3e={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},V3e={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},q3e={date:dz({formats:$3e,defaultWidth:"full"}),time:dz({formats:U3e,defaultWidth:"full"}),dateTime:dz({formats:V3e,defaultWidth:"full"})},H3e={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},W3e=(t,e,r,n)=>H3e[t];function mC(t){return(e,r)=>{const n=r!=null&&r.context?String(r.context):"standalone";let i;if(n==="formatting"&&t.formattingValues){const c=t.defaultFormattingWidth||t.defaultWidth,a=r!=null&&r.width?String(r.width):c;i=t.formattingValues[a]||t.formattingValues[c]}else{const c=t.defaultWidth,a=r!=null&&r.width?String(r.width):t.defaultWidth;i=t.values[a]||t.values[c]}const o=t.argumentCallback?t.argumentCallback(e):e;return i[o]}}const G3e={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},K3e={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},Z3e={narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},Y3e={narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},X3e={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},Q3e={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},J3e=(t,e)=>{const r=Number(t),n=r%100;if(n>20||n<10)switch(n%10){case 1:return r+"st";case 2:return r+"nd";case 3:return r+"rd"}return r+"th"},eFe={ordinalNumber:J3e,era:mC({values:G3e,defaultWidth:"wide"}),quarter:mC({values:K3e,defaultWidth:"wide",argumentCallback:t=>t-1}),month:mC({values:Z3e,defaultWidth:"wide"}),day:mC({values:Y3e,defaultWidth:"wide"}),dayPeriod:mC({values:X3e,defaultWidth:"wide",formattingValues:Q3e,defaultFormattingWidth:"wide"})};function gC(t){return(e,r={})=>{const n=r.width,i=n&&t.matchPatterns[n]||t.matchPatterns[t.defaultMatchWidth],o=e.match(i);if(!o)return null;const c=o[0],a=n&&t.parsePatterns[n]||t.parsePatterns[t.defaultParseWidth],m=Array.isArray(a)?rFe(a,j=>j.test(c)):tFe(a,j=>j.test(c));let g;g=t.valueCallback?t.valueCallback(m):m,g=r.valueCallback?r.valueCallback(g):g;const _=e.slice(c.length);return{value:g,rest:_}}}function tFe(t,e){for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)&&e(t[r]))return r}function rFe(t,e){for(let r=0;r{const n=e.match(t.matchPattern);if(!n)return null;const i=n[0],o=e.match(t.parsePattern);if(!o)return null;let c=t.valueCallback?t.valueCallback(o[0]):o[0];c=r.valueCallback?r.valueCallback(c):c;const a=e.slice(i.length);return{value:c,rest:a}}}const sFe=/^(\d+)(th|st|nd|rd)?/i,iFe=/\d+/i,aFe={narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},oFe={any:[/^b/i,/^(a|c)/i]},lFe={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},cFe={any:[/1/i,/2/i,/3/i,/4/i]},uFe={narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},dFe={narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},hFe={narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},fFe={narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},pFe={narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},mFe={any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},gFe={ordinalNumber:nFe({matchPattern:sFe,parsePattern:iFe,valueCallback:t=>parseInt(t,10)}),era:gC({matchPatterns:aFe,defaultMatchWidth:"wide",parsePatterns:oFe,defaultParseWidth:"any"}),quarter:gC({matchPatterns:lFe,defaultMatchWidth:"wide",parsePatterns:cFe,defaultParseWidth:"any",valueCallback:t=>t+1}),month:gC({matchPatterns:uFe,defaultMatchWidth:"wide",parsePatterns:dFe,defaultParseWidth:"any"}),day:gC({matchPatterns:hFe,defaultMatchWidth:"wide",parsePatterns:fFe,defaultParseWidth:"any"}),dayPeriod:gC({matchPatterns:pFe,defaultMatchWidth:"any",parsePatterns:mFe,defaultParseWidth:"any"})},oq={code:"en-US",formatDistance:B3e,formatLong:q3e,formatRelative:W3e,localize:eFe,match:gFe,options:{weekStartsOn:0,firstWeekContainsDate:1}};function yFe(t){const e=As(t);return yf(e,Jhe(e))+1}function tfe(t){const e=As(t),r=+z_(e)-+C3e(e);return Math.round(r/sq)+1}function rfe(t,e){var _,j,N,C;const r=As(t),n=r.getFullYear(),i=qj(),o=(e==null?void 0:e.firstWeekContainsDate)??((j=(_=e==null?void 0:e.locale)==null?void 0:_.options)==null?void 0:j.firstWeekContainsDate)??i.firstWeekContainsDate??((C=(N=i.locale)==null?void 0:N.options)==null?void 0:C.firstWeekContainsDate)??1,c=uu(t,0);c.setFullYear(n+1,0,o),c.setHours(0,0,0,0);const a=Np(c,e),m=uu(t,0);m.setFullYear(n,0,o),m.setHours(0,0,0,0);const g=Np(m,e);return r.getTime()>=a.getTime()?n+1:r.getTime()>=g.getTime()?n:n-1}function xFe(t,e){var a,m,g,_;const r=qj(),n=(e==null?void 0:e.firstWeekContainsDate)??((m=(a=e==null?void 0:e.locale)==null?void 0:a.options)==null?void 0:m.firstWeekContainsDate)??r.firstWeekContainsDate??((_=(g=r.locale)==null?void 0:g.options)==null?void 0:_.firstWeekContainsDate)??1,i=rfe(t,e),o=uu(t,0);return o.setFullYear(i,0,n),o.setHours(0,0,0,0),Np(o,e)}function nfe(t,e){const r=As(t),n=+Np(r,e)-+xFe(r,e);return Math.round(n/sq)+1}function Sa(t,e){const r=t<0?"-":"",n=Math.abs(t).toString().padStart(e,"0");return r+n}const Yg={y(t,e){const r=t.getFullYear(),n=r>0?r:1-r;return Sa(e==="yy"?n%100:n,e.length)},M(t,e){const r=t.getMonth();return e==="M"?String(r+1):Sa(r+1,2)},d(t,e){return Sa(t.getDate(),e.length)},a(t,e){const r=t.getHours()/12>=1?"pm":"am";switch(e){case"a":case"aa":return r.toUpperCase();case"aaa":return r;case"aaaaa":return r[0];case"aaaa":default:return r==="am"?"a.m.":"p.m."}},h(t,e){return Sa(t.getHours()%12||12,e.length)},H(t,e){return Sa(t.getHours(),e.length)},m(t,e){return Sa(t.getMinutes(),e.length)},s(t,e){return Sa(t.getSeconds(),e.length)},S(t,e){const r=e.length,n=t.getMilliseconds(),i=Math.trunc(n*Math.pow(10,r-3));return Sa(i,e.length)}},uw={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},YX={G:function(t,e,r){const n=t.getFullYear()>0?1:0;switch(e){case"G":case"GG":case"GGG":return r.era(n,{width:"abbreviated"});case"GGGGG":return r.era(n,{width:"narrow"});case"GGGG":default:return r.era(n,{width:"wide"})}},y:function(t,e,r){if(e==="yo"){const n=t.getFullYear(),i=n>0?n:1-n;return r.ordinalNumber(i,{unit:"year"})}return Yg.y(t,e)},Y:function(t,e,r,n){const i=rfe(t,n),o=i>0?i:1-i;if(e==="YY"){const c=o%100;return Sa(c,2)}return e==="Yo"?r.ordinalNumber(o,{unit:"year"}):Sa(o,e.length)},R:function(t,e){const r=Yhe(t);return Sa(r,e.length)},u:function(t,e){const r=t.getFullYear();return Sa(r,e.length)},Q:function(t,e,r){const n=Math.ceil((t.getMonth()+1)/3);switch(e){case"Q":return String(n);case"QQ":return Sa(n,2);case"Qo":return r.ordinalNumber(n,{unit:"quarter"});case"QQQ":return r.quarter(n,{width:"abbreviated",context:"formatting"});case"QQQQQ":return r.quarter(n,{width:"narrow",context:"formatting"});case"QQQQ":default:return r.quarter(n,{width:"wide",context:"formatting"})}},q:function(t,e,r){const n=Math.ceil((t.getMonth()+1)/3);switch(e){case"q":return String(n);case"qq":return Sa(n,2);case"qo":return r.ordinalNumber(n,{unit:"quarter"});case"qqq":return r.quarter(n,{width:"abbreviated",context:"standalone"});case"qqqqq":return r.quarter(n,{width:"narrow",context:"standalone"});case"qqqq":default:return r.quarter(n,{width:"wide",context:"standalone"})}},M:function(t,e,r){const n=t.getMonth();switch(e){case"M":case"MM":return Yg.M(t,e);case"Mo":return r.ordinalNumber(n+1,{unit:"month"});case"MMM":return r.month(n,{width:"abbreviated",context:"formatting"});case"MMMMM":return r.month(n,{width:"narrow",context:"formatting"});case"MMMM":default:return r.month(n,{width:"wide",context:"formatting"})}},L:function(t,e,r){const n=t.getMonth();switch(e){case"L":return String(n+1);case"LL":return Sa(n+1,2);case"Lo":return r.ordinalNumber(n+1,{unit:"month"});case"LLL":return r.month(n,{width:"abbreviated",context:"standalone"});case"LLLLL":return r.month(n,{width:"narrow",context:"standalone"});case"LLLL":default:return r.month(n,{width:"wide",context:"standalone"})}},w:function(t,e,r,n){const i=nfe(t,n);return e==="wo"?r.ordinalNumber(i,{unit:"week"}):Sa(i,e.length)},I:function(t,e,r){const n=tfe(t);return e==="Io"?r.ordinalNumber(n,{unit:"week"}):Sa(n,e.length)},d:function(t,e,r){return e==="do"?r.ordinalNumber(t.getDate(),{unit:"date"}):Yg.d(t,e)},D:function(t,e,r){const n=yFe(t);return e==="Do"?r.ordinalNumber(n,{unit:"dayOfYear"}):Sa(n,e.length)},E:function(t,e,r){const n=t.getDay();switch(e){case"E":case"EE":case"EEE":return r.day(n,{width:"abbreviated",context:"formatting"});case"EEEEE":return r.day(n,{width:"narrow",context:"formatting"});case"EEEEEE":return r.day(n,{width:"short",context:"formatting"});case"EEEE":default:return r.day(n,{width:"wide",context:"formatting"})}},e:function(t,e,r,n){const i=t.getDay(),o=(i-n.weekStartsOn+8)%7||7;switch(e){case"e":return String(o);case"ee":return Sa(o,2);case"eo":return r.ordinalNumber(o,{unit:"day"});case"eee":return r.day(i,{width:"abbreviated",context:"formatting"});case"eeeee":return r.day(i,{width:"narrow",context:"formatting"});case"eeeeee":return r.day(i,{width:"short",context:"formatting"});case"eeee":default:return r.day(i,{width:"wide",context:"formatting"})}},c:function(t,e,r,n){const i=t.getDay(),o=(i-n.weekStartsOn+8)%7||7;switch(e){case"c":return String(o);case"cc":return Sa(o,e.length);case"co":return r.ordinalNumber(o,{unit:"day"});case"ccc":return r.day(i,{width:"abbreviated",context:"standalone"});case"ccccc":return r.day(i,{width:"narrow",context:"standalone"});case"cccccc":return r.day(i,{width:"short",context:"standalone"});case"cccc":default:return r.day(i,{width:"wide",context:"standalone"})}},i:function(t,e,r){const n=t.getDay(),i=n===0?7:n;switch(e){case"i":return String(i);case"ii":return Sa(i,e.length);case"io":return r.ordinalNumber(i,{unit:"day"});case"iii":return r.day(n,{width:"abbreviated",context:"formatting"});case"iiiii":return r.day(n,{width:"narrow",context:"formatting"});case"iiiiii":return r.day(n,{width:"short",context:"formatting"});case"iiii":default:return r.day(n,{width:"wide",context:"formatting"})}},a:function(t,e,r){const i=t.getHours()/12>=1?"pm":"am";switch(e){case"a":case"aa":return r.dayPeriod(i,{width:"abbreviated",context:"formatting"});case"aaa":return r.dayPeriod(i,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return r.dayPeriod(i,{width:"narrow",context:"formatting"});case"aaaa":default:return r.dayPeriod(i,{width:"wide",context:"formatting"})}},b:function(t,e,r){const n=t.getHours();let i;switch(n===12?i=uw.noon:n===0?i=uw.midnight:i=n/12>=1?"pm":"am",e){case"b":case"bb":return r.dayPeriod(i,{width:"abbreviated",context:"formatting"});case"bbb":return r.dayPeriod(i,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return r.dayPeriod(i,{width:"narrow",context:"formatting"});case"bbbb":default:return r.dayPeriod(i,{width:"wide",context:"formatting"})}},B:function(t,e,r){const n=t.getHours();let i;switch(n>=17?i=uw.evening:n>=12?i=uw.afternoon:n>=4?i=uw.morning:i=uw.night,e){case"B":case"BB":case"BBB":return r.dayPeriod(i,{width:"abbreviated",context:"formatting"});case"BBBBB":return r.dayPeriod(i,{width:"narrow",context:"formatting"});case"BBBB":default:return r.dayPeriod(i,{width:"wide",context:"formatting"})}},h:function(t,e,r){if(e==="ho"){let n=t.getHours()%12;return n===0&&(n=12),r.ordinalNumber(n,{unit:"hour"})}return Yg.h(t,e)},H:function(t,e,r){return e==="Ho"?r.ordinalNumber(t.getHours(),{unit:"hour"}):Yg.H(t,e)},K:function(t,e,r){const n=t.getHours()%12;return e==="Ko"?r.ordinalNumber(n,{unit:"hour"}):Sa(n,e.length)},k:function(t,e,r){let n=t.getHours();return n===0&&(n=24),e==="ko"?r.ordinalNumber(n,{unit:"hour"}):Sa(n,e.length)},m:function(t,e,r){return e==="mo"?r.ordinalNumber(t.getMinutes(),{unit:"minute"}):Yg.m(t,e)},s:function(t,e,r){return e==="so"?r.ordinalNumber(t.getSeconds(),{unit:"second"}):Yg.s(t,e)},S:function(t,e){return Yg.S(t,e)},X:function(t,e,r){const n=t.getTimezoneOffset();if(n===0)return"Z";switch(e){case"X":return QX(n);case"XXXX":case"XX":return Rv(n);case"XXXXX":case"XXX":default:return Rv(n,":")}},x:function(t,e,r){const n=t.getTimezoneOffset();switch(e){case"x":return QX(n);case"xxxx":case"xx":return Rv(n);case"xxxxx":case"xxx":default:return Rv(n,":")}},O:function(t,e,r){const n=t.getTimezoneOffset();switch(e){case"O":case"OO":case"OOO":return"GMT"+XX(n,":");case"OOOO":default:return"GMT"+Rv(n,":")}},z:function(t,e,r){const n=t.getTimezoneOffset();switch(e){case"z":case"zz":case"zzz":return"GMT"+XX(n,":");case"zzzz":default:return"GMT"+Rv(n,":")}},t:function(t,e,r){const n=Math.trunc(t.getTime()/1e3);return Sa(n,e.length)},T:function(t,e,r){const n=t.getTime();return Sa(n,e.length)}};function XX(t,e=""){const r=t>0?"-":"+",n=Math.abs(t),i=Math.trunc(n/60),o=n%60;return o===0?r+String(i):r+String(i)+e+Sa(o,2)}function QX(t,e){return t%60===0?(t>0?"-":"+")+Sa(Math.abs(t)/60,2):Rv(t,e)}function Rv(t,e=""){const r=t>0?"-":"+",n=Math.abs(t),i=Sa(Math.trunc(n/60),2),o=Sa(n%60,2);return r+i+e+o}const JX=(t,e)=>{switch(t){case"P":return e.date({width:"short"});case"PP":return e.date({width:"medium"});case"PPP":return e.date({width:"long"});case"PPPP":default:return e.date({width:"full"})}},sfe=(t,e)=>{switch(t){case"p":return e.time({width:"short"});case"pp":return e.time({width:"medium"});case"ppp":return e.time({width:"long"});case"pppp":default:return e.time({width:"full"})}},vFe=(t,e)=>{const r=t.match(/(P+)(p+)?/)||[],n=r[1],i=r[2];if(!i)return JX(t,e);let o;switch(n){case"P":o=e.dateTime({width:"short"});break;case"PP":o=e.dateTime({width:"medium"});break;case"PPP":o=e.dateTime({width:"long"});break;case"PPPP":default:o=e.dateTime({width:"full"});break}return o.replace("{{date}}",JX(n,e)).replace("{{time}}",sfe(i,e))},_Fe={p:sfe,P:vFe},bFe=/^D+$/,wFe=/^Y+$/,jFe=["D","DD","YY","YYYY"];function SFe(t){return bFe.test(t)}function NFe(t){return wFe.test(t)}function CFe(t,e,r){const n=kFe(t,e,r);if(console.warn(n),jFe.includes(t))throw new RangeError(n)}function kFe(t,e,r){const n=t[0]==="Y"?"years":"days of the month";return`Use \`${t.toLowerCase()}\` instead of \`${t}\` (in \`${e}\`) for formatting ${n} to the input \`${r}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}const TFe=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,EFe=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,AFe=/^'([^]*?)'?$/,PFe=/''/g,IFe=/[a-zA-Z]/;function Vn(t,e,r){var _,j,N,C,P,A,I,O;const n=qj(),i=(r==null?void 0:r.locale)??n.locale??oq,o=(r==null?void 0:r.firstWeekContainsDate)??((j=(_=r==null?void 0:r.locale)==null?void 0:_.options)==null?void 0:j.firstWeekContainsDate)??n.firstWeekContainsDate??((C=(N=n.locale)==null?void 0:N.options)==null?void 0:C.firstWeekContainsDate)??1,c=(r==null?void 0:r.weekStartsOn)??((A=(P=r==null?void 0:r.locale)==null?void 0:P.options)==null?void 0:A.weekStartsOn)??n.weekStartsOn??((O=(I=n.locale)==null?void 0:I.options)==null?void 0:O.weekStartsOn)??0,a=As(t);if(!P3e(a))throw new RangeError("Invalid time value");let m=e.match(EFe).map(R=>{const z=R[0];if(z==="p"||z==="P"){const W=_Fe[z];return W(R,i.formatLong)}return R}).join("").match(TFe).map(R=>{if(R==="''")return{isToken:!1,value:"'"};const z=R[0];if(z==="'")return{isToken:!1,value:MFe(R)};if(YX[z])return{isToken:!0,value:R};if(z.match(IFe))throw new RangeError("Format string contains an unescaped latin alphabet character `"+z+"`");return{isToken:!1,value:R}});i.localize.preprocessor&&(m=i.localize.preprocessor(a,m));const g={firstWeekContainsDate:o,weekStartsOn:c,locale:i};return m.map(R=>{if(!R.isToken)return R.value;const z=R.value;(!(r!=null&&r.useAdditionalWeekYearTokens)&&NFe(z)||!(r!=null&&r.useAdditionalDayOfYearTokens)&&SFe(z))&&CFe(z,e,String(t));const W=YX[z[0]];return W(a,z,i.localize,g)}).join("")}function MFe(t){const e=t.match(AFe);return e?e[1].replace(PFe,"'"):t}function OFe(t,e,r){const n=qj(),i=(r==null?void 0:r.locale)??n.locale??oq,o=2520,c=II(t,e);if(isNaN(c))throw new RangeError("Invalid time value");const a=Object.assign({},r,{addSuffix:r==null?void 0:r.addSuffix,comparison:c});let m,g;c>0?(m=As(e),g=As(t)):(m=As(t),g=As(e));const _=F3e(g,m),j=(W1(g)-W1(m))/1e3,N=Math.round((_-j)/60);let C;if(N<2)return r!=null&&r.includeSeconds?_<5?i.formatDistance("lessThanXSeconds",5,a):_<10?i.formatDistance("lessThanXSeconds",10,a):_<20?i.formatDistance("lessThanXSeconds",20,a):_<40?i.formatDistance("halfAMinute",0,a):_<60?i.formatDistance("lessThanXMinutes",1,a):i.formatDistance("xMinutes",1,a):N===0?i.formatDistance("lessThanXMinutes",1,a):i.formatDistance("xMinutes",N,a);if(N<45)return i.formatDistance("xMinutes",N,a);if(N<90)return i.formatDistance("aboutXHours",1,a);if(Nn.getTime()}function lq(t,e){const r=As(t),n=As(e);return+r<+n}function VM(t){return+As(t)o-c);return r>=n&&r<=i}function hz(t,e){return hc(t,-e)}function fz(t,e){const r=As(t),n=r.getFullYear(),i=r.getDate(),o=uu(t,0);o.setFullYear(n,e,15),o.setHours(0,0,0,0);const c=RFe(o);return r.setMonth(e,Math.min(i,c)),r}function eQ(t,e){const r=As(t);return isNaN(+r)?uu(t,NaN):(r.setFullYear(e),r)}function BFe(t,e){return gh(t,-12)}function $Fe(t,e){return D.useReducer((r,n)=>e[r][n]??r,t)}var uq="ScrollArea",[afe]=Yo(uq),[UFe,vh]=afe(uq),ofe=D.forwardRef((t,e)=>{const{__scopeScrollArea:r,type:n="hover",dir:i,scrollHideDelay:o=600,...c}=t,[a,m]=D.useState(null),[g,_]=D.useState(null),[j,N]=D.useState(null),[C,P]=D.useState(null),[A,I]=D.useState(null),[O,R]=D.useState(0),[z,W]=D.useState(0),[V,K]=D.useState(!1),[Q,te]=D.useState(!1),X=vs(e,he=>m(he)),ie=i0(i);return s.jsx(UFe,{scope:r,type:n,dir:ie,scrollHideDelay:o,scrollArea:a,viewport:g,onViewportChange:_,content:j,onContentChange:N,scrollbarX:C,onScrollbarXChange:P,scrollbarXEnabled:V,onScrollbarXEnabledChange:K,scrollbarY:A,onScrollbarYChange:I,scrollbarYEnabled:Q,onScrollbarYEnabledChange:te,onCornerWidthChange:R,onCornerHeightChange:W,children:s.jsx(yn.div,{dir:ie,...c,ref:X,style:{position:"relative","--radix-scroll-area-corner-width":O+"px","--radix-scroll-area-corner-height":z+"px",...t.style}})})});ofe.displayName=uq;var lfe="ScrollAreaViewport",cfe=D.forwardRef((t,e)=>{const{__scopeScrollArea:r,children:n,nonce:i,...o}=t,c=vh(lfe,r),a=D.useRef(null),m=vs(e,a,c.onViewportChange);return s.jsxs(s.Fragment,{children:[s.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-scroll-area-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-scroll-area-viewport]::-webkit-scrollbar{display:none}"},nonce:i}),s.jsx(yn.div,{"data-radix-scroll-area-viewport":"",...o,ref:m,style:{overflowX:c.scrollbarXEnabled?"scroll":"hidden",overflowY:c.scrollbarYEnabled?"scroll":"hidden",...t.style},children:s.jsx("div",{ref:c.onContentChange,style:{minWidth:"100%",display:"table"},children:n})})]})});cfe.displayName=lfe;var Rp="ScrollAreaScrollbar",dq=D.forwardRef((t,e)=>{const{forceMount:r,...n}=t,i=vh(Rp,t.__scopeScrollArea),{onScrollbarXEnabledChange:o,onScrollbarYEnabledChange:c}=i,a=t.orientation==="horizontal";return D.useEffect(()=>(a?o(!0):c(!0),()=>{a?o(!1):c(!1)}),[a,o,c]),i.type==="hover"?s.jsx(VFe,{...n,ref:e,forceMount:r}):i.type==="scroll"?s.jsx(qFe,{...n,ref:e,forceMount:r}):i.type==="auto"?s.jsx(ufe,{...n,ref:e,forceMount:r}):i.type==="always"?s.jsx(hq,{...n,ref:e}):null});dq.displayName=Rp;var VFe=D.forwardRef((t,e)=>{const{forceMount:r,...n}=t,i=vh(Rp,t.__scopeScrollArea),[o,c]=D.useState(!1);return D.useEffect(()=>{const a=i.scrollArea;let m=0;if(a){const g=()=>{window.clearTimeout(m),c(!0)},_=()=>{m=window.setTimeout(()=>c(!1),i.scrollHideDelay)};return a.addEventListener("pointerenter",g),a.addEventListener("pointerleave",_),()=>{window.clearTimeout(m),a.removeEventListener("pointerenter",g),a.removeEventListener("pointerleave",_)}}},[i.scrollArea,i.scrollHideDelay]),s.jsx(gl,{present:r||o,children:s.jsx(ufe,{"data-state":o?"visible":"hidden",...n,ref:e})})}),qFe=D.forwardRef((t,e)=>{const{forceMount:r,...n}=t,i=vh(Rp,t.__scopeScrollArea),o=t.orientation==="horizontal",c=RD(()=>m("SCROLL_END"),100),[a,m]=$Fe("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return D.useEffect(()=>{if(a==="idle"){const g=window.setTimeout(()=>m("HIDE"),i.scrollHideDelay);return()=>window.clearTimeout(g)}},[a,i.scrollHideDelay,m]),D.useEffect(()=>{const g=i.viewport,_=o?"scrollLeft":"scrollTop";if(g){let j=g[_];const N=()=>{const C=g[_];j!==C&&(m("SCROLL"),c()),j=C};return g.addEventListener("scroll",N),()=>g.removeEventListener("scroll",N)}},[i.viewport,o,m,c]),s.jsx(gl,{present:r||a!=="hidden",children:s.jsx(hq,{"data-state":a==="hidden"?"hidden":"visible",...n,ref:e,onPointerEnter:Yr(t.onPointerEnter,()=>m("POINTER_ENTER")),onPointerLeave:Yr(t.onPointerLeave,()=>m("POINTER_LEAVE"))})})}),ufe=D.forwardRef((t,e)=>{const r=vh(Rp,t.__scopeScrollArea),{forceMount:n,...i}=t,[o,c]=D.useState(!1),a=t.orientation==="horizontal",m=RD(()=>{if(r.viewport){const g=r.viewport.offsetWidth{const{orientation:r="vertical",...n}=t,i=vh(Rp,t.__scopeScrollArea),o=D.useRef(null),c=D.useRef(0),[a,m]=D.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),g=mfe(a.viewport,a.content),_={...n,sizes:a,onSizesChange:m,hasThumb:g>0&&g<1,onThumbChange:N=>o.current=N,onThumbPointerUp:()=>c.current=0,onThumbPointerDown:N=>c.current=N};function j(N,C){return YFe(N,c.current,a,C)}return r==="horizontal"?s.jsx(HFe,{..._,ref:e,onThumbPositionChange:()=>{if(i.viewport&&o.current){const N=i.viewport.scrollLeft,C=tQ(N,a,i.dir);o.current.style.transform=`translate3d(${C}px, 0, 0)`}},onWheelScroll:N=>{i.viewport&&(i.viewport.scrollLeft=N)},onDragScroll:N=>{i.viewport&&(i.viewport.scrollLeft=j(N,i.dir))}}):r==="vertical"?s.jsx(WFe,{..._,ref:e,onThumbPositionChange:()=>{if(i.viewport&&o.current){const N=i.viewport.scrollTop,C=tQ(N,a);o.current.style.transform=`translate3d(0, ${C}px, 0)`}},onWheelScroll:N=>{i.viewport&&(i.viewport.scrollTop=N)},onDragScroll:N=>{i.viewport&&(i.viewport.scrollTop=j(N))}}):null}),HFe=D.forwardRef((t,e)=>{const{sizes:r,onSizesChange:n,...i}=t,o=vh(Rp,t.__scopeScrollArea),[c,a]=D.useState(),m=D.useRef(null),g=vs(e,m,o.onScrollbarXChange);return D.useEffect(()=>{m.current&&a(getComputedStyle(m.current))},[m]),s.jsx(hfe,{"data-orientation":"horizontal",...i,ref:g,sizes:r,style:{bottom:0,left:o.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:o.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":OD(r)+"px",...t.style},onThumbPointerDown:_=>t.onThumbPointerDown(_.x),onDragScroll:_=>t.onDragScroll(_.x),onWheelScroll:(_,j)=>{if(o.viewport){const N=o.viewport.scrollLeft+_.deltaX;t.onWheelScroll(N),yfe(N,j)&&_.preventDefault()}},onResize:()=>{m.current&&o.viewport&&c&&n({content:o.viewport.scrollWidth,viewport:o.viewport.offsetWidth,scrollbar:{size:m.current.clientWidth,paddingStart:HM(c.paddingLeft),paddingEnd:HM(c.paddingRight)}})}})}),WFe=D.forwardRef((t,e)=>{const{sizes:r,onSizesChange:n,...i}=t,o=vh(Rp,t.__scopeScrollArea),[c,a]=D.useState(),m=D.useRef(null),g=vs(e,m,o.onScrollbarYChange);return D.useEffect(()=>{m.current&&a(getComputedStyle(m.current))},[m]),s.jsx(hfe,{"data-orientation":"vertical",...i,ref:g,sizes:r,style:{top:0,right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":OD(r)+"px",...t.style},onThumbPointerDown:_=>t.onThumbPointerDown(_.y),onDragScroll:_=>t.onDragScroll(_.y),onWheelScroll:(_,j)=>{if(o.viewport){const N=o.viewport.scrollTop+_.deltaY;t.onWheelScroll(N),yfe(N,j)&&_.preventDefault()}},onResize:()=>{m.current&&o.viewport&&c&&n({content:o.viewport.scrollHeight,viewport:o.viewport.offsetHeight,scrollbar:{size:m.current.clientHeight,paddingStart:HM(c.paddingTop),paddingEnd:HM(c.paddingBottom)}})}})}),[GFe,dfe]=afe(Rp),hfe=D.forwardRef((t,e)=>{const{__scopeScrollArea:r,sizes:n,hasThumb:i,onThumbChange:o,onThumbPointerUp:c,onThumbPointerDown:a,onThumbPositionChange:m,onDragScroll:g,onWheelScroll:_,onResize:j,...N}=t,C=vh(Rp,r),[P,A]=D.useState(null),I=vs(e,X=>A(X)),O=D.useRef(null),R=D.useRef(""),z=C.viewport,W=n.content-n.viewport,V=Oo(_),K=Oo(m),Q=RD(j,10);function te(X){if(O.current){const ie=X.clientX-O.current.left,he=X.clientY-O.current.top;g({x:ie,y:he})}}return D.useEffect(()=>{const X=ie=>{const he=ie.target;(P==null?void 0:P.contains(he))&&V(ie,W)};return document.addEventListener("wheel",X,{passive:!1}),()=>document.removeEventListener("wheel",X,{passive:!1})},[z,P,W,V]),D.useEffect(K,[n,K]),K1(P,Q),K1(C.content,Q),s.jsx(GFe,{scope:r,scrollbar:P,hasThumb:i,onThumbChange:Oo(o),onThumbPointerUp:Oo(c),onThumbPositionChange:K,onThumbPointerDown:Oo(a),children:s.jsx(yn.div,{...N,ref:I,style:{position:"absolute",...N.style},onPointerDown:Yr(t.onPointerDown,X=>{X.button===0&&(X.target.setPointerCapture(X.pointerId),O.current=P.getBoundingClientRect(),R.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",C.viewport&&(C.viewport.style.scrollBehavior="auto"),te(X))}),onPointerMove:Yr(t.onPointerMove,te),onPointerUp:Yr(t.onPointerUp,X=>{const ie=X.target;ie.hasPointerCapture(X.pointerId)&&ie.releasePointerCapture(X.pointerId),document.body.style.webkitUserSelect=R.current,C.viewport&&(C.viewport.style.scrollBehavior=""),O.current=null})})})}),qM="ScrollAreaThumb",ffe=D.forwardRef((t,e)=>{const{forceMount:r,...n}=t,i=dfe(qM,t.__scopeScrollArea);return s.jsx(gl,{present:r||i.hasThumb,children:s.jsx(KFe,{ref:e,...n})})}),KFe=D.forwardRef((t,e)=>{const{__scopeScrollArea:r,style:n,...i}=t,o=vh(qM,r),c=dfe(qM,r),{onThumbPositionChange:a}=c,m=vs(e,j=>c.onThumbChange(j)),g=D.useRef(void 0),_=RD(()=>{g.current&&(g.current(),g.current=void 0)},100);return D.useEffect(()=>{const j=o.viewport;if(j){const N=()=>{if(_(),!g.current){const C=XFe(j,a);g.current=C,a()}};return a(),j.addEventListener("scroll",N),()=>j.removeEventListener("scroll",N)}},[o.viewport,_,a]),s.jsx(yn.div,{"data-state":c.hasThumb?"visible":"hidden",...i,ref:m,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...n},onPointerDownCapture:Yr(t.onPointerDownCapture,j=>{const C=j.target.getBoundingClientRect(),P=j.clientX-C.left,A=j.clientY-C.top;c.onThumbPointerDown({x:P,y:A})}),onPointerUp:Yr(t.onPointerUp,c.onThumbPointerUp)})});ffe.displayName=qM;var fq="ScrollAreaCorner",pfe=D.forwardRef((t,e)=>{const r=vh(fq,t.__scopeScrollArea),n=!!(r.scrollbarX&&r.scrollbarY);return r.type!=="scroll"&&n?s.jsx(ZFe,{...t,ref:e}):null});pfe.displayName=fq;var ZFe=D.forwardRef((t,e)=>{const{__scopeScrollArea:r,...n}=t,i=vh(fq,r),[o,c]=D.useState(0),[a,m]=D.useState(0),g=!!(o&&a);return K1(i.scrollbarX,()=>{var j;const _=((j=i.scrollbarX)==null?void 0:j.offsetHeight)||0;i.onCornerHeightChange(_),m(_)}),K1(i.scrollbarY,()=>{var j;const _=((j=i.scrollbarY)==null?void 0:j.offsetWidth)||0;i.onCornerWidthChange(_),c(_)}),g?s.jsx(yn.div,{...n,ref:e,style:{width:o,height:a,position:"absolute",right:i.dir==="ltr"?0:void 0,left:i.dir==="rtl"?0:void 0,bottom:0,...t.style}}):null});function HM(t){return t?parseInt(t,10):0}function mfe(t,e){const r=t/e;return isNaN(r)?0:r}function OD(t){const e=mfe(t.viewport,t.content),r=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,n=(t.scrollbar.size-r)*e;return Math.max(n,18)}function YFe(t,e,r,n="ltr"){const i=OD(r),o=i/2,c=e||o,a=i-c,m=r.scrollbar.paddingStart+c,g=r.scrollbar.size-r.scrollbar.paddingEnd-a,_=r.content-r.viewport,j=n==="ltr"?[0,_]:[_*-1,0];return gfe([m,g],j)(t)}function tQ(t,e,r="ltr"){const n=OD(e),i=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,o=e.scrollbar.size-i,c=e.content-e.viewport,a=o-n,m=r==="ltr"?[0,c]:[c*-1,0],g=ck(t,m);return gfe([0,c],[0,a])(g)}function gfe(t,e){return r=>{if(t[0]===t[1]||e[0]===e[1])return e[0];const n=(e[1]-e[0])/(t[1]-t[0]);return e[0]+n*(r-t[0])}}function yfe(t,e){return t>0&&t{})=>{let r={left:t.scrollLeft,top:t.scrollTop},n=0;return function i(){const o={left:t.scrollLeft,top:t.scrollTop},c=r.left!==o.left,a=r.top!==o.top;(c||a)&&e(),r=o,n=window.requestAnimationFrame(i)}(),()=>window.cancelAnimationFrame(n)};function RD(t,e){const r=Oo(t),n=D.useRef(0);return D.useEffect(()=>()=>window.clearTimeout(n.current),[]),D.useCallback(()=>{window.clearTimeout(n.current),n.current=window.setTimeout(r,e)},[r,e])}function K1(t,e){const r=Oo(e);Lo(()=>{let n=0;if(t){const i=new ResizeObserver(()=>{cancelAnimationFrame(n),n=window.requestAnimationFrame(r)});return i.observe(t),()=>{window.cancelAnimationFrame(n),i.unobserve(t)}}},[t,r])}var xfe=ofe,QFe=cfe,JFe=pfe;const qu=D.forwardRef(({className:t,children:e,...r},n)=>s.jsxs(xfe,{ref:n,className:ar("relative overflow-hidden",t),...r,children:[s.jsx(QFe,{className:"h-full w-full rounded-[inherit]",children:e}),s.jsx(vfe,{}),s.jsx(JFe,{})]}));qu.displayName=xfe.displayName;const vfe=D.forwardRef(({className:t,orientation:e="vertical",...r},n)=>s.jsx(dq,{ref:n,orientation:e,className:ar("flex touch-none select-none transition-colors",e==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",e==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",t),...r,children:s.jsx(ffe,{className:"relative flex-1 rounded-full bg-border"})}));vfe.displayName=dq.displayName;const eze=()=>{const{user:t}=rn(),e=Bs(),[r,n]=D.useState([]),[i,o]=D.useState(0),[c,a]=D.useState(!1),[m,g]=D.useState(null);D.useEffect(()=>{if(!t)return;const C=`notification_last_read_${t.id}`;let P=m;if(!P){const O=localStorage.getItem(C);O&&(P=O,g(O))}(async()=>{const{data:O,error:R}=await ae.from("push_notifications").select("*").order("created_at",{ascending:!1}).limit(20);if(!R&&O){n(O);const z=P?new Date(P):null,W=O.filter(V=>z?new Date(V.created_at)>z:!0);o(W.length)}})();const I=ae.channel("push-notifications").on("postgres_changes",{event:"INSERT",schema:"public",table:"push_notifications"},O=>{const R=O.new;n(W=>[R,...W].slice(0,20));const z=P?new Date(P):null;(!z||new Date(R.created_at)>z)&&o(W=>W+1),Notification.permission==="granted"&&new Notification(R.title,{body:R.body,icon:"/favicon.ico"})}).subscribe();return()=>{ae.removeChannel(I)}},[t,m]);const _=C=>{const P=C.toLowerCase();return P.includes("academy")||P.includes("video")?Ia:P.includes("template")?A_:P.includes("event")?ko:P.includes("newsletter")?gT:P.includes("brokerage")?Hm:P.includes("swag")||P.includes("social")?yd:P.includes("toolbox")||P.includes("tool")?xT:P.includes("brief")?cu:Tf},j=C=>{a(!1),C.url&&C.url!=="/"&&e(C.url)},N=()=>{if(!t)return;const C=new Date().toISOString(),P=`notification_last_read_${t.id}`;localStorage.setItem(P,C),g(C),o(0)};return s.jsxs(rg,{open:c,onOpenChange:a,children:[s.jsx(ng,{asChild:!0,children:s.jsxs(de,{variant:"ghost",size:"icon",className:"relative",children:[s.jsx(QR,{className:"h-5 w-5"}),i>0&&s.jsx(ir,{variant:"destructive",className:"absolute -top-1 -right-1 h-5 w-5 flex items-center justify-center p-0 text-xs",children:i>9?"9+":i})]})}),s.jsxs(Op,{align:"end",className:"w-80",children:[s.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b",children:[s.jsx("span",{className:"font-semibold",children:"Notifications"}),r.length>0&&s.jsx(de,{variant:"ghost",size:"sm",className:"text-xs h-6",onClick:N,children:"Mark all read"})]}),s.jsx(qu,{className:"h-[300px]",children:r.length===0?s.jsx("div",{className:"p-4 text-center text-muted-foreground text-sm",children:"No notifications yet"}):r.map(C=>{const P=_(C.title);return s.jsxs(Ro,{className:"flex items-start gap-3 p-3 cursor-pointer",onClick:()=>j(C),children:[s.jsx("div",{className:"flex-shrink-0 mt-0.5",children:s.jsx(P,{className:"h-4 w-4 text-primary"})}),s.jsxs("div",{className:"flex flex-col gap-1 min-w-0",children:[s.jsx("span",{className:"font-medium text-sm",children:C.title}),s.jsx("span",{className:"text-xs text-muted-foreground line-clamp-2",children:C.body}),s.jsx("span",{className:"text-xs text-muted-foreground",children:Bu(new Date(C.created_at),{addSuffix:!0})})]})]},C.id)})})]})]})};var rQ=1,tze=.9,rze=.8,nze=.17,pz=.1,mz=.999,sze=.9999,ize=.99,aze=/[\\\/_+.#"@\[\(\{&]/,oze=/[\\\/_+.#"@\[\(\{&]/g,lze=/[\s-]/,_fe=/[\s-]/g;function M$(t,e,r,n,i,o,c){if(o===e.length)return i===t.length?rQ:ize;var a=`${i},${o}`;if(c[a]!==void 0)return c[a];for(var m=n.charAt(o),g=r.indexOf(m,i),_=0,j,N,C,P;g>=0;)j=M$(t,e,r,n,g+1,o+1,c),j>_&&(g===i?j*=rQ:aze.test(t.charAt(g-1))?(j*=rze,C=t.slice(i,g-1).match(oze),C&&i>0&&(j*=Math.pow(mz,C.length))):lze.test(t.charAt(g-1))?(j*=tze,P=t.slice(i,g-1).match(_fe),P&&i>0&&(j*=Math.pow(mz,P.length))):(j*=nze,i>0&&(j*=Math.pow(mz,g-i))),t.charAt(g)!==e.charAt(o)&&(j*=sze)),(jj&&(j=N*pz)),j>_&&(_=j),g=r.indexOf(m,g+1);return c[a]=_,_}function nQ(t){return t.toLowerCase().replace(_fe," ")}function cze(t,e,r){return t=r&&r.length>0?`${t+" "+r.join(" ")}`:t,M$(t,e,nQ(t),nQ(e),0,0,{})}var yC='[cmdk-group=""]',gz='[cmdk-group-items=""]',uze='[cmdk-group-heading=""]',bfe='[cmdk-item=""]',sQ=`${bfe}:not([aria-disabled="true"])`,O$="cmdk-item-select",ww="data-value",dze=(t,e,r)=>cze(t,e,r),wfe=D.createContext(void 0),IT=()=>D.useContext(wfe),jfe=D.createContext(void 0),pq=()=>D.useContext(jfe),Sfe=D.createContext(void 0),Nfe=D.forwardRef((t,e)=>{let r=jw(()=>{var _e,Ye;return{search:"",value:(Ye=(_e=t.value)!=null?_e:t.defaultValue)!=null?Ye:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),n=jw(()=>new Set),i=jw(()=>new Map),o=jw(()=>new Map),c=jw(()=>new Set),a=Cfe(t),{label:m,children:g,value:_,onValueChange:j,filter:N,shouldFilter:C,loop:P,disablePointerSelection:A=!1,vimBindings:I=!0,...O}=t,R=Al(),z=Al(),W=Al(),V=D.useRef(null),K=wze();B_(()=>{if(_!==void 0){let _e=_.trim();r.current.value=_e,Q.emit()}},[_]),B_(()=>{K(6,pe)},[]);let Q=D.useMemo(()=>({subscribe:_e=>(c.current.add(_e),()=>c.current.delete(_e)),snapshot:()=>r.current,setState:(_e,Ye,pt)=>{var nt,Qt,gt,Me;if(!Object.is(r.current[_e],Ye)){if(r.current[_e]=Ye,_e==="search")xe(),ie(),K(1,he);else if(_e==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let Oe=document.getElementById(W);Oe?Oe.focus():(nt=document.getElementById(R))==null||nt.focus()}if(K(7,()=>{var Oe;r.current.selectedItemId=(Oe=ve())==null?void 0:Oe.id,Q.emit()}),pt||K(5,pe),((Qt=a.current)==null?void 0:Qt.value)!==void 0){let Oe=Ye??"";(Me=(gt=a.current).onValueChange)==null||Me.call(gt,Oe);return}}Q.emit()}},emit:()=>{c.current.forEach(_e=>_e())}}),[]),te=D.useMemo(()=>({value:(_e,Ye,pt)=>{var nt;Ye!==((nt=o.current.get(_e))==null?void 0:nt.value)&&(o.current.set(_e,{value:Ye,keywords:pt}),r.current.filtered.items.set(_e,X(Ye,pt)),K(2,()=>{ie(),Q.emit()}))},item:(_e,Ye)=>(n.current.add(_e),Ye&&(i.current.has(Ye)?i.current.get(Ye).add(_e):i.current.set(Ye,new Set([_e]))),K(3,()=>{xe(),ie(),r.current.value||he(),Q.emit()}),()=>{o.current.delete(_e),n.current.delete(_e),r.current.filtered.items.delete(_e);let pt=ve();K(4,()=>{xe(),(pt==null?void 0:pt.getAttribute("id"))===_e&&he(),Q.emit()})}),group:_e=>(i.current.has(_e)||i.current.set(_e,new Set),()=>{o.current.delete(_e),i.current.delete(_e)}),filter:()=>a.current.shouldFilter,label:m||t["aria-label"],getDisablePointerSelection:()=>a.current.disablePointerSelection,listId:R,inputId:W,labelId:z,listInnerRef:V}),[]);function X(_e,Ye){var pt,nt;let Qt=(nt=(pt=a.current)==null?void 0:pt.filter)!=null?nt:dze;return _e?Qt(_e,r.current.search,Ye):0}function ie(){if(!r.current.search||a.current.shouldFilter===!1)return;let _e=r.current.filtered.items,Ye=[];r.current.filtered.groups.forEach(nt=>{let Qt=i.current.get(nt),gt=0;Qt.forEach(Me=>{let Oe=_e.get(Me);gt=Math.max(Oe,gt)}),Ye.push([nt,gt])});let pt=V.current;ge().sort((nt,Qt)=>{var gt,Me;let Oe=nt.getAttribute("id"),Ie=Qt.getAttribute("id");return((gt=_e.get(Ie))!=null?gt:0)-((Me=_e.get(Oe))!=null?Me:0)}).forEach(nt=>{let Qt=nt.closest(gz);Qt?Qt.appendChild(nt.parentElement===Qt?nt:nt.closest(`${gz} > *`)):pt.appendChild(nt.parentElement===pt?nt:nt.closest(`${gz} > *`))}),Ye.sort((nt,Qt)=>Qt[1]-nt[1]).forEach(nt=>{var Qt;let gt=(Qt=V.current)==null?void 0:Qt.querySelector(`${yC}[${ww}="${encodeURIComponent(nt[0])}"]`);gt==null||gt.parentElement.appendChild(gt)})}function he(){let _e=ge().find(pt=>pt.getAttribute("aria-disabled")!=="true"),Ye=_e==null?void 0:_e.getAttribute(ww);Q.setState("value",Ye||void 0)}function xe(){var _e,Ye,pt,nt;if(!r.current.search||a.current.shouldFilter===!1){r.current.filtered.count=n.current.size;return}r.current.filtered.groups=new Set;let Qt=0;for(let gt of n.current){let Me=(Ye=(_e=o.current.get(gt))==null?void 0:_e.value)!=null?Ye:"",Oe=(nt=(pt=o.current.get(gt))==null?void 0:pt.keywords)!=null?nt:[],Ie=X(Me,Oe);r.current.filtered.items.set(gt,Ie),Ie>0&&Qt++}for(let[gt,Me]of i.current)for(let Oe of Me)if(r.current.filtered.items.get(Oe)>0){r.current.filtered.groups.add(gt);break}r.current.filtered.count=Qt}function pe(){var _e,Ye,pt;let nt=ve();nt&&(((_e=nt.parentElement)==null?void 0:_e.firstChild)===nt&&((pt=(Ye=nt.closest(yC))==null?void 0:Ye.querySelector(uze))==null||pt.scrollIntoView({block:"nearest"})),nt.scrollIntoView({block:"nearest"}))}function ve(){var _e;return(_e=V.current)==null?void 0:_e.querySelector(`${bfe}[aria-selected="true"]`)}function ge(){var _e;return Array.from(((_e=V.current)==null?void 0:_e.querySelectorAll(sQ))||[])}function ke(_e){let Ye=ge()[_e];Ye&&Q.setState("value",Ye.getAttribute(ww))}function Ce(_e){var Ye;let pt=ve(),nt=ge(),Qt=nt.findIndex(Me=>Me===pt),gt=nt[Qt+_e];(Ye=a.current)!=null&&Ye.loop&&(gt=Qt+_e<0?nt[nt.length-1]:Qt+_e===nt.length?nt[0]:nt[Qt+_e]),gt&&Q.setState("value",gt.getAttribute(ww))}function Se(_e){let Ye=ve(),pt=Ye==null?void 0:Ye.closest(yC),nt;for(;pt&&!nt;)pt=_e>0?_ze(pt,yC):bze(pt,yC),nt=pt==null?void 0:pt.querySelector(sQ);nt?Q.setState("value",nt.getAttribute(ww)):Ce(_e)}let je=()=>ke(ge().length-1),et=_e=>{_e.preventDefault(),_e.metaKey?je():_e.altKey?Se(1):Ce(1)},bt=_e=>{_e.preventDefault(),_e.metaKey?ke(0):_e.altKey?Se(-1):Ce(-1)};return D.createElement(yn.div,{ref:e,tabIndex:-1,...O,"cmdk-root":"",onKeyDown:_e=>{var Ye;(Ye=O.onKeyDown)==null||Ye.call(O,_e);let pt=_e.nativeEvent.isComposing||_e.keyCode===229;if(!(_e.defaultPrevented||pt))switch(_e.key){case"n":case"j":{I&&_e.ctrlKey&&et(_e);break}case"ArrowDown":{et(_e);break}case"p":case"k":{I&&_e.ctrlKey&&bt(_e);break}case"ArrowUp":{bt(_e);break}case"Home":{_e.preventDefault(),ke(0);break}case"End":{_e.preventDefault(),je();break}case"Enter":{_e.preventDefault();let nt=ve();if(nt){let Qt=new Event(O$);nt.dispatchEvent(Qt)}}}}},D.createElement("label",{"cmdk-label":"",htmlFor:te.inputId,id:te.labelId,style:Sze},m),DD(t,_e=>D.createElement(jfe.Provider,{value:Q},D.createElement(wfe.Provider,{value:te},_e))))}),hze=D.forwardRef((t,e)=>{var r,n;let i=Al(),o=D.useRef(null),c=D.useContext(Sfe),a=IT(),m=Cfe(t),g=(n=(r=m.current)==null?void 0:r.forceMount)!=null?n:c==null?void 0:c.forceMount;B_(()=>{if(!g)return a.item(i,c==null?void 0:c.id)},[g]);let _=kfe(i,o,[t.value,t.children,o],t.keywords),j=pq(),N=ux(K=>K.value&&K.value===_.current),C=ux(K=>g||a.filter()===!1?!0:K.search?K.filtered.items.get(i)>0:!0);D.useEffect(()=>{let K=o.current;if(!(!K||t.disabled))return K.addEventListener(O$,P),()=>K.removeEventListener(O$,P)},[C,t.onSelect,t.disabled]);function P(){var K,Q;A(),(Q=(K=m.current).onSelect)==null||Q.call(K,_.current)}function A(){j.setState("value",_.current,!0)}if(!C)return null;let{disabled:I,value:O,onSelect:R,forceMount:z,keywords:W,...V}=t;return D.createElement(yn.div,{ref:qm(o,e),...V,id:i,"cmdk-item":"",role:"option","aria-disabled":!!I,"aria-selected":!!N,"data-disabled":!!I,"data-selected":!!N,onPointerMove:I||a.getDisablePointerSelection()?void 0:A,onClick:I?void 0:P},t.children)}),fze=D.forwardRef((t,e)=>{let{heading:r,children:n,forceMount:i,...o}=t,c=Al(),a=D.useRef(null),m=D.useRef(null),g=Al(),_=IT(),j=ux(C=>i||_.filter()===!1?!0:C.search?C.filtered.groups.has(c):!0);B_(()=>_.group(c),[]),kfe(c,a,[t.value,t.heading,m]);let N=D.useMemo(()=>({id:c,forceMount:i}),[i]);return D.createElement(yn.div,{ref:qm(a,e),...o,"cmdk-group":"",role:"presentation",hidden:j?void 0:!0},r&&D.createElement("div",{ref:m,"cmdk-group-heading":"","aria-hidden":!0,id:g},r),DD(t,C=>D.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":r?g:void 0},D.createElement(Sfe.Provider,{value:N},C))))}),pze=D.forwardRef((t,e)=>{let{alwaysRender:r,...n}=t,i=D.useRef(null),o=ux(c=>!c.search);return!r&&!o?null:D.createElement(yn.div,{ref:qm(i,e),...n,"cmdk-separator":"",role:"separator"})}),mze=D.forwardRef((t,e)=>{let{onValueChange:r,...n}=t,i=t.value!=null,o=pq(),c=ux(g=>g.search),a=ux(g=>g.selectedItemId),m=IT();return D.useEffect(()=>{t.value!=null&&o.setState("search",t.value)},[t.value]),D.createElement(yn.input,{ref:e,...n,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":m.listId,"aria-labelledby":m.labelId,"aria-activedescendant":a,id:m.inputId,type:"text",value:i?t.value:c,onChange:g=>{i||o.setState("search",g.target.value),r==null||r(g.target.value)}})}),gze=D.forwardRef((t,e)=>{let{children:r,label:n="Suggestions",...i}=t,o=D.useRef(null),c=D.useRef(null),a=ux(g=>g.selectedItemId),m=IT();return D.useEffect(()=>{if(c.current&&o.current){let g=c.current,_=o.current,j,N=new ResizeObserver(()=>{j=requestAnimationFrame(()=>{let C=g.offsetHeight;_.style.setProperty("--cmdk-list-height",C.toFixed(1)+"px")})});return N.observe(g),()=>{cancelAnimationFrame(j),N.unobserve(g)}}},[]),D.createElement(yn.div,{ref:qm(o,e),...i,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":a,"aria-label":n,id:m.listId},DD(t,g=>D.createElement("div",{ref:qm(c,m.listInnerRef),"cmdk-list-sizer":""},g)))}),yze=D.forwardRef((t,e)=>{let{open:r,onOpenChange:n,overlayClassName:i,contentClassName:o,container:c,...a}=t;return D.createElement(vD,{open:r,onOpenChange:n},D.createElement(_D,{container:c},D.createElement(Bj,{"cmdk-overlay":"",className:i}),D.createElement($j,{"aria-label":t.label,"cmdk-dialog":"",className:o},D.createElement(Nfe,{ref:e,...a}))))}),xze=D.forwardRef((t,e)=>ux(r=>r.filtered.count===0)?D.createElement(yn.div,{ref:e,...t,"cmdk-empty":"",role:"presentation"}):null),vze=D.forwardRef((t,e)=>{let{progress:r,children:n,label:i="Loading...",...o}=t;return D.createElement(yn.div,{ref:e,...o,"cmdk-loading":"",role:"progressbar","aria-valuenow":r,"aria-valuemin":0,"aria-valuemax":100,"aria-label":i},DD(t,c=>D.createElement("div",{"aria-hidden":!0},c)))}),Hu=Object.assign(Nfe,{List:gze,Item:hze,Input:mze,Group:fze,Separator:pze,Dialog:yze,Empty:xze,Loading:vze});function _ze(t,e){let r=t.nextElementSibling;for(;r;){if(r.matches(e))return r;r=r.nextElementSibling}}function bze(t,e){let r=t.previousElementSibling;for(;r;){if(r.matches(e))return r;r=r.previousElementSibling}}function Cfe(t){let e=D.useRef(t);return B_(()=>{e.current=t}),e}var B_=typeof window>"u"?D.useEffect:D.useLayoutEffect;function jw(t){let e=D.useRef();return e.current===void 0&&(e.current=t()),e}function ux(t){let e=pq(),r=()=>t(e.snapshot());return D.useSyncExternalStore(e.subscribe,r,r)}function kfe(t,e,r,n=[]){let i=D.useRef(),o=IT();return B_(()=>{var c;let a=(()=>{var g;for(let _ of r){if(typeof _=="string")return _.trim();if(typeof _=="object"&&"current"in _)return _.current?(g=_.current.textContent)==null?void 0:g.trim():i.current}})(),m=n.map(g=>g.trim());o.value(t,a,m),(c=e.current)==null||c.setAttribute(ww,a),i.current=a}),i}var wze=()=>{let[t,e]=D.useState(),r=jw(()=>new Map);return B_(()=>{r.current.forEach(n=>n()),r.current=new Map},[t]),(n,i)=>{r.current.set(n,i),e({})}};function jze(t){let e=t.type;return typeof e=="function"?e(t.props):"render"in e?e.render(t.props):t}function DD({asChild:t,children:e},r){return t&&D.isValidElement(e)?D.cloneElement(jze(e),{ref:e.ref},r(e.props.children)):r(e)}var Sze={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};const mq=D.forwardRef(({className:t,...e},r)=>s.jsx(Hu,{ref:r,className:ar("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",t),...e}));mq.displayName=Hu.displayName;const Nze=({children:t,...e})=>s.jsx(mn,{...e,children:s.jsx(pn,{className:"overflow-hidden p-0 shadow-lg",children:s.jsx(mq,{className:"[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5",children:t})})}),gq=D.forwardRef(({className:t,...e},r)=>s.jsxs("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:[s.jsx(ba,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),s.jsx(Hu.Input,{ref:r,className:ar("flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",t),...e})]}));gq.displayName=Hu.Input.displayName;const yq=D.forwardRef(({className:t,...e},r)=>s.jsx(Hu.List,{ref:r,className:ar("max-h-[300px] overflow-y-auto overflow-x-hidden",t),...e}));yq.displayName=Hu.List.displayName;const xq=D.forwardRef((t,e)=>s.jsx(Hu.Empty,{ref:e,className:"py-6 text-center text-sm",...t}));xq.displayName=Hu.Empty.displayName;const vq=D.forwardRef(({className:t,...e},r)=>s.jsx(Hu.Group,{ref:r,className:ar("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",t),...e}));vq.displayName=Hu.Group.displayName;const Cze=D.forwardRef(({className:t,...e},r)=>s.jsx(Hu.Separator,{ref:r,className:ar("-mx-1 h-px bg-border",t),...e}));Cze.displayName=Hu.Separator.displayName;const _q=D.forwardRef(({className:t,...e},r)=>s.jsx(Hu.Item,{ref:r,className:ar("group relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected='true']:bg-primary/80 data-[selected=true]:text-primary-foreground data-[disabled=true]:opacity-50",t),...e}));_q.displayName=Hu.Item.displayName;const kze={event:{label:"Events",icon:H2,color:"bg-blue-500/10 text-blue-600"},template:{label:"Templates",icon:A_,color:"bg-purple-500/10 text-purple-600"},academy:{label:"Academy",icon:eD,color:"bg-amber-500/10 text-amber-600"},toolbox:{label:"Toolbox",icon:xT,color:"bg-green-500/10 text-green-600"},"social-swag":{label:"Social Swag",icon:cu,color:"bg-fuchsia-500/10 text-fuchsia-600"}},iQ=()=>{const[t,e]=D.useState(!1),[r,n]=D.useState(""),[i,o]=D.useState([]),[c,a]=D.useState(!1),m=Bs();D.useEffect(()=>{const N=C=>{C.key==="k"&&(C.metaKey||C.ctrlKey)&&(C.preventDefault(),e(P=>!P))};return document.addEventListener("keydown",N),()=>document.removeEventListener("keydown",N)},[]);const g=D.useCallback(async N=>{if(!N.trim()){o([]);return}a(!0);const C=`%${N}%`;try{const[P,A,I,O,R]=await Promise.all([ae.from("events").select("id, title, description, event_date").eq("is_published",!0).or(`title.ilike.${C},description.ilike.${C}`).limit(5),ae.from("canva_templates").select("id, name, description, publish_date").or(`name.ilike.${C},description.ilike.${C}`).limit(5),ae.from("academy_videos").select("id, title, description, publish_date").eq("is_published",!0).or(`title.ilike.${C},description.ilike.${C}`).limit(5),ae.from("resource_kits").select("id, name, description, publish_date").eq("is_published",!0).or(`name.ilike.${C},description.ilike.${C}`).limit(5),ae.from("social_swag").select("id, title, description, publish_date").eq("is_published",!0).or(`title.ilike.${C},description.ilike.${C}`).limit(5)]),z=[];P.data&&P.data.forEach(W=>{z.push({id:W.id,title:W.title,description:W.description,type:"event",date:W.event_date,path:`/event/${W.id}`})}),A.data&&A.data.forEach(W=>{z.push({id:W.id,title:W.name,description:W.description,type:"template",date:W.publish_date,path:`/templates/${W.id}`})}),I.data&&I.data.forEach(W=>{z.push({id:W.id,title:W.title,description:W.description,type:"academy",date:W.publish_date,path:`/academy/${W.id}`})}),O.data&&O.data.forEach(W=>{z.push({id:W.id,title:W.name,description:W.description,type:"toolbox",date:W.publish_date,path:`/toolbox/${W.id}`})}),R.data&&R.data.forEach(W=>{z.push({id:W.id,title:W.title,description:W.description,type:"social-swag",date:W.publish_date,path:`/social-swag/${W.id}`})}),o(z)}catch(P){console.error("Search error:",P)}finally{a(!1)}},[]);D.useEffect(()=>{const N=setTimeout(()=>{g(r)},300);return()=>clearTimeout(N)},[r,g]);const _=N=>{e(!1),n(""),m(N)},j=i.reduce((N,C)=>(N[C.type]||(N[C.type]=[]),N[C.type].push(C),N),{});return s.jsxs(s.Fragment,{children:[s.jsxs(de,{variant:"outline",className:"relative h-9 w-9 p-0 xl:h-9 xl:w-60 xl:justify-start xl:px-3 xl:py-2",onClick:()=>e(!0),children:[s.jsx(ba,{className:"h-4 w-4 xl:mr-2"}),s.jsx("span",{className:"hidden xl:inline-flex text-muted-foreground text-sm",children:"Search..."}),s.jsxs("kbd",{className:"pointer-events-none absolute right-1.5 top-1.5 hidden h-6 select-none items-center gap-1 rounded border bg-muted px-1.5 font-mono text-[10px] font-medium opacity-100 xl:flex",children:[s.jsx("span",{className:"text-xs",children:"⌘"}),"K"]})]}),s.jsxs(Nze,{open:t,onOpenChange:e,children:[s.jsx(gq,{placeholder:"Search events, templates, academy, toolbox, social swag...",value:r,onValueChange:n}),s.jsxs(yq,{children:[c&&s.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"Searching..."}),!c&&r&&i.length===0&&s.jsxs(xq,{children:['No results found for "',r,'"']}),!c&&!r&&s.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"Start typing to search across all content..."}),Object.entries(j).map(([N,C])=>{const P=kze[N],A=P.icon;return s.jsx(vq,{heading:P.label,children:C.map(I=>s.jsxs(_q,{value:`${I.type}-${I.id}-${I.title}`,onSelect:()=>_(I.path),className:"flex items-start gap-3 py-3 cursor-pointer",children:[s.jsx("div",{className:`p-2 rounded-md ${P.color}`,children:s.jsx(A,{className:"h-4 w-4"})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("div",{className:"font-medium truncate",children:I.title}),I.description&&s.jsx("div",{className:"text-sm text-muted-foreground truncate group-data-[selected=true]:text-primary-foreground/80",children:I.description})]}),s.jsxs("div",{className:"flex flex-col items-end gap-1 shrink-0",children:[s.jsx(ir,{variant:"secondary",className:"text-xs",children:P.label}),s.jsx("span",{className:"text-xs text-muted-foreground",children:Bu(new Date(I.date),{addSuffix:!0})})]})]},`${I.type}-${I.id}`))},N)})]})]})]})},Tze=({expiresAt:t,className:e})=>{const[r,n]=D.useState(null);if(D.useEffect(()=>{const a=()=>{const g=new Date().getTime(),j=new Date(t).getTime()-g;if(j<=0){n({days:0,hours:0,minutes:0});return}const N=Math.floor(j/(1e3*60*60*24)),C=Math.floor(j%(1e3*60*60*24)/(1e3*60*60)),P=Math.floor(j%(1e3*60*60)/(1e3*60));n({days:N,hours:C,minutes:P})};a();const m=setInterval(a,6e4);return()=>clearInterval(m)},[t]),!r)return null;const i=r.days===0&&r.hours===0&&r.minutes===0,o=r.days<=1,c=r.days<=3&&!o;return i?s.jsxs("div",{className:ar("flex items-center gap-2 px-4 py-2 rounded-lg bg-destructive/10 border border-destructive/20",e),children:[s.jsx(yT,{className:"h-4 w-4 text-destructive"}),s.jsx("span",{className:"text-sm font-medium text-destructive",children:"Your free trial has expired"})]}):s.jsxs("div",{className:ar("flex items-center gap-3 px-4 py-2 rounded-lg border transition-colors",o?"bg-destructive/10 border-destructive/20":c?"bg-amber-500/10 border-amber-500/20":"bg-primary/10 border-primary/20",e),children:[s.jsx(No,{className:ar("h-4 w-4",o?"text-destructive":c?"text-amber-500":"text-primary")}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:ar("text-sm font-medium",o?"text-destructive":c?"text-amber-600":"text-primary"),children:"Free Trial:"}),s.jsxs("div",{className:"flex items-center gap-1",children:[r.days>0&&s.jsxs("span",{className:ar("text-sm font-bold",o?"text-destructive":c?"text-amber-600":"text-primary"),children:[r.days,"d"]}),s.jsxs("span",{className:ar("text-sm font-bold",o?"text-destructive":c?"text-amber-600":"text-primary"),children:[r.hours,"h"]}),s.jsxs("span",{className:ar("text-sm font-bold",o?"text-destructive":c?"text-amber-600":"text-primary"),children:[r.minutes,"m"]}),s.jsx("span",{className:ar("text-xs",o?"text-destructive/70":c?"text-amber-600/70":"text-primary/70"),children:"remaining"})]})]})]})},Eze=()=>s.jsx("div",{className:"fixed inset-0 bg-background/95 backdrop-blur-sm z-50 flex items-center justify-center p-4",children:s.jsxs(at,{className:"w-full max-w-lg shadow-2xl border-destructive/20",children:[s.jsxs(xr,{className:"text-center pb-2",children:[s.jsx("div",{className:"mx-auto mb-4 h-16 w-16 rounded-full bg-destructive/10 flex items-center justify-center",children:s.jsx(yT,{className:"h-8 w-8 text-destructive"})}),s.jsx(wr,{className:"text-2xl",children:"Your Free Trial Has Ended"}),s.jsx(us,{className:"text-base",children:"Your 7-day free trial has expired. Upgrade now to continue accessing all the powerful tools and resources LevelUp has to offer!"})]}),s.jsxs(ct,{className:"space-y-6",children:[s.jsxs("div",{className:"bg-muted/50 rounded-lg p-4 space-y-3",children:[s.jsx("p",{className:"text-sm font-medium text-center",children:"Ready to upgrade? Contact us:"}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 justify-center",children:[s.jsxs("a",{href:"tel:1-866-527-8668",className:"flex items-center justify-center gap-2 text-primary hover:underline",children:[s.jsx(Yl,{className:"h-4 w-4"}),s.jsx("span",{children:"1-866-527-8668"})]}),s.jsxs("a",{href:"mailto:support@relevelup.com",className:"flex items-center justify-center gap-2 text-primary hover:underline",children:[s.jsx(Fo,{className:"h-4 w-4"}),s.jsx("span",{children:"support@relevelup.com"})]})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx("p",{className:"text-sm text-muted-foreground text-center",children:"With a full membership, you'll get:"}),s.jsxs("ul",{className:"text-sm space-y-1 text-muted-foreground",children:[s.jsxs("li",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-primary",children:"✓"})," Unlimited access to all marketing templates"]}),s.jsxs("li",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-primary",children:"✓"})," Complete Academy training library"]}),s.jsxs("li",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-primary",children:"✓"})," AI-powered tools and resources"]}),s.jsxs("li",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-primary",children:"✓"})," Community forums and support"]}),s.jsxs("li",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-primary",children:"✓"})," Exclusive member events and workshops"]})]})]}),s.jsx("div",{className:"pt-2",children:s.jsxs(de,{className:"w-full",size:"lg",onClick:()=>window.open("tel:1-866-527-8668"),children:[s.jsx(Yl,{className:"h-4 w-4 mr-2"}),"Call to Upgrade Now"]})})]})]})}),Aze=({hasUnseenBrief:t,onClick:e,className:r})=>s.jsxs(ple,{children:[s.jsx(mle,{asChild:!0,children:s.jsxs(de,{variant:"ghost",size:"icon",onClick:e,className:ar("relative transition-colors",t&&"text-primary hover:text-primary",r),children:[s.jsx(mT,{className:"h-5 w-5"}),t&&s.jsx("span",{className:"absolute top-1 right-1 h-2 w-2 rounded-full bg-primary animate-pulse"})]})}),s.jsx(l8,{children:s.jsx("p",{children:"The LevelUp Brief"})})]});var LD="Checkbox",[Pze]=Yo(LD),[Ize,bq]=Pze(LD);function Mze(t){const{__scopeCheckbox:e,checked:r,children:n,defaultChecked:i,disabled:o,form:c,name:a,onCheckedChange:m,required:g,value:_="on",internal_do_not_use_render:j}=t,[N,C]=Uu({prop:r,defaultProp:i??!1,onChange:m,caller:LD}),[P,A]=D.useState(null),[I,O]=D.useState(null),R=D.useRef(!1),z=P?!!c||!!P.closest("form"):!0,W={checked:N,disabled:o,setChecked:C,control:P,setControl:A,name:a,form:c,value:_,hasConsumerStoppedPropagationRef:R,required:g,defaultChecked:Ky(i)?!1:i,isFormControl:z,bubbleInput:I,setBubbleInput:O};return s.jsx(Ize,{scope:e,...W,children:Oze(j)?j(W):n})}var Tfe="CheckboxTrigger",Efe=D.forwardRef(({__scopeCheckbox:t,onKeyDown:e,onClick:r,...n},i)=>{const{control:o,value:c,disabled:a,checked:m,required:g,setControl:_,setChecked:j,hasConsumerStoppedPropagationRef:N,isFormControl:C,bubbleInput:P}=bq(Tfe,t),A=vs(i,_),I=D.useRef(m);return D.useEffect(()=>{const O=o==null?void 0:o.form;if(O){const R=()=>j(I.current);return O.addEventListener("reset",R),()=>O.removeEventListener("reset",R)}},[o,j]),s.jsx(yn.button,{type:"button",role:"checkbox","aria-checked":Ky(m)?"mixed":m,"aria-required":g,"data-state":Ofe(m),"data-disabled":a?"":void 0,disabled:a,value:c,...n,ref:A,onKeyDown:Yr(e,O=>{O.key==="Enter"&&O.preventDefault()}),onClick:Yr(r,O=>{j(R=>Ky(R)?!0:!R),P&&C&&(N.current=O.isPropagationStopped(),N.current||O.stopPropagation())})})});Efe.displayName=Tfe;var wq=D.forwardRef((t,e)=>{const{__scopeCheckbox:r,name:n,checked:i,defaultChecked:o,required:c,disabled:a,value:m,onCheckedChange:g,form:_,...j}=t;return s.jsx(Mze,{__scopeCheckbox:r,checked:i,defaultChecked:o,disabled:a,required:c,onCheckedChange:g,name:n,form:_,value:m,internal_do_not_use_render:({isFormControl:N})=>s.jsxs(s.Fragment,{children:[s.jsx(Efe,{...j,ref:e,__scopeCheckbox:r}),N&&s.jsx(Mfe,{__scopeCheckbox:r})]})})});wq.displayName=LD;var Afe="CheckboxIndicator",Pfe=D.forwardRef((t,e)=>{const{__scopeCheckbox:r,forceMount:n,...i}=t,o=bq(Afe,r);return s.jsx(gl,{present:n||Ky(o.checked)||o.checked===!0,children:s.jsx(yn.span,{"data-state":Ofe(o.checked),"data-disabled":o.disabled?"":void 0,...i,ref:e,style:{pointerEvents:"none",...t.style}})})});Pfe.displayName=Afe;var Ife="CheckboxBubbleInput",Mfe=D.forwardRef(({__scopeCheckbox:t,...e},r)=>{const{control:n,hasConsumerStoppedPropagationRef:i,checked:o,defaultChecked:c,required:a,disabled:m,name:g,value:_,form:j,bubbleInput:N,setBubbleInput:C}=bq(Ife,t),P=vs(r,C),A=PT(o),I=_T(n);D.useEffect(()=>{const R=N;if(!R)return;const z=window.HTMLInputElement.prototype,V=Object.getOwnPropertyDescriptor(z,"checked").set,K=!i.current;if(A!==o&&V){const Q=new Event("click",{bubbles:K});R.indeterminate=Ky(o),V.call(R,Ky(o)?!1:o),R.dispatchEvent(Q)}},[N,A,o,i]);const O=D.useRef(Ky(o)?!1:o);return s.jsx(yn.input,{type:"checkbox","aria-hidden":!0,defaultChecked:c??O.current,required:a,disabled:m,name:g,value:_,form:j,...e,tabIndex:-1,ref:P,style:{...e.style,...I,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})});Mfe.displayName=Ife;function Oze(t){return typeof t=="function"}function Ky(t){return t==="indeterminate"}function Ofe(t){return Ky(t)?"indeterminate":t?"checked":"unchecked"}const dx=D.forwardRef(({className:t,...e},r)=>s.jsx(wq,{ref:r,className:ar("peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",t),...e,children:s.jsx(Pfe,{className:ar("flex items-center justify-center text-current"),children:s.jsx(ru,{className:"h-4 w-4"})})}));dx.displayName=wq.displayName;var jq="Radio",[Rze,Rfe]=Yo(jq),[Dze,Lze]=Rze(jq),Dfe=D.forwardRef((t,e)=>{const{__scopeRadio:r,name:n,checked:i=!1,required:o,disabled:c,value:a="on",onCheck:m,form:g,..._}=t,[j,N]=D.useState(null),C=vs(e,I=>N(I)),P=D.useRef(!1),A=j?g||!!j.closest("form"):!0;return s.jsxs(Dze,{scope:r,checked:i,disabled:c,children:[s.jsx(yn.button,{type:"button",role:"radio","aria-checked":i,"data-state":Bfe(i),"data-disabled":c?"":void 0,disabled:c,value:a,..._,ref:C,onClick:Yr(t.onClick,I=>{i||m==null||m(),A&&(P.current=I.isPropagationStopped(),P.current||I.stopPropagation())})}),A&&s.jsx(zfe,{control:j,bubbles:!P.current,name:n,value:a,checked:i,required:o,disabled:c,form:g,style:{transform:"translateX(-100%)"}})]})});Dfe.displayName=jq;var Lfe="RadioIndicator",Ffe=D.forwardRef((t,e)=>{const{__scopeRadio:r,forceMount:n,...i}=t,o=Lze(Lfe,r);return s.jsx(gl,{present:n||o.checked,children:s.jsx(yn.span,{"data-state":Bfe(o.checked),"data-disabled":o.disabled?"":void 0,...i,ref:e})})});Ffe.displayName=Lfe;var Fze="RadioBubbleInput",zfe=D.forwardRef(({__scopeRadio:t,control:e,checked:r,bubbles:n=!0,...i},o)=>{const c=D.useRef(null),a=vs(c,o),m=PT(r),g=_T(e);return D.useEffect(()=>{const _=c.current;if(!_)return;const j=window.HTMLInputElement.prototype,C=Object.getOwnPropertyDescriptor(j,"checked").set;if(m!==r&&C){const P=new Event("click",{bubbles:n});C.call(_,r),_.dispatchEvent(P)}},[m,r,n]),s.jsx(yn.input,{type:"radio","aria-hidden":!0,defaultChecked:r,...i,tabIndex:-1,ref:a,style:{...i.style,...g,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});zfe.displayName=Fze;function Bfe(t){return t?"checked":"unchecked"}var zze=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],FD="RadioGroup",[Bze]=Yo(FD,[Uj,Rfe]),$fe=Uj(),Ufe=Rfe(),[$ze,Uze]=Bze(FD),Vfe=D.forwardRef((t,e)=>{const{__scopeRadioGroup:r,name:n,defaultValue:i,value:o,required:c=!1,disabled:a=!1,orientation:m,dir:g,loop:_=!0,onValueChange:j,...N}=t,C=$fe(r),P=i0(g),[A,I]=Uu({prop:o,defaultProp:i??null,onChange:j,caller:FD});return s.jsx($ze,{scope:r,name:n,required:c,disabled:a,value:A,onValueChange:I,children:s.jsx(R8,{asChild:!0,...C,orientation:m,dir:P,loop:_,children:s.jsx(yn.div,{role:"radiogroup","aria-required":c,"aria-orientation":m,"data-disabled":a?"":void 0,dir:P,...N,ref:e})})})});Vfe.displayName=FD;var qfe="RadioGroupItem",Hfe=D.forwardRef((t,e)=>{const{__scopeRadioGroup:r,disabled:n,...i}=t,o=Uze(qfe,r),c=o.disabled||n,a=$fe(r),m=Ufe(r),g=D.useRef(null),_=vs(e,g),j=o.value===i.value,N=D.useRef(!1);return D.useEffect(()=>{const C=A=>{zze.includes(A.key)&&(N.current=!0)},P=()=>N.current=!1;return document.addEventListener("keydown",C),document.addEventListener("keyup",P),()=>{document.removeEventListener("keydown",C),document.removeEventListener("keyup",P)}},[]),s.jsx(D8,{asChild:!0,...a,focusable:!c,active:j,children:s.jsx(Dfe,{disabled:c,required:o.required,checked:j,...m,...i,name:o.name,ref:_,onCheck:()=>o.onValueChange(i.value),onKeyDown:Yr(C=>{C.key==="Enter"&&C.preventDefault()}),onFocus:Yr(i.onFocus,()=>{var C;N.current&&((C=g.current)==null||C.click())})})})});Hfe.displayName=qfe;var Vze="RadioGroupIndicator",Wfe=D.forwardRef((t,e)=>{const{__scopeRadioGroup:r,...n}=t,i=Ufe(r);return s.jsx(Ffe,{...i,...n,ref:e})});Wfe.displayName=Vze;var Gfe=Vfe,Kfe=Hfe,qze=Wfe;const Zfe=D.forwardRef(({className:t,...e},r)=>s.jsx(Gfe,{className:ar("grid gap-2",t),...e,ref:r}));Zfe.displayName=Gfe.displayName;const Yfe=D.forwardRef(({className:t,...e},r)=>s.jsx(Kfe,{ref:r,className:ar("aspect-square h-4 w-4 rounded-full border border-primary text-primary ring-offset-background focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",t),...e,children:s.jsx(qze,{className:"flex items-center justify-center",children:s.jsx(hM,{className:"h-2.5 w-2.5 fill-current text-current"})})}));Yfe.displayName=Kfe.displayName;const Hze=({brief:t,open:e,onClose:r,onDismiss:n})=>{const{user:i}=rn(),[o,c]=D.useState({}),[a,m]=D.useState({}),[g,_]=D.useState([]);D.useEffect(()=>{e&&i&&t.polls.length>0&&j()},[e,i,t.polls]);const j=async()=>{if(!i)return;const I=t.polls.map(R=>R.id),{data:O}=await ae.from("levelup_brief_poll_responses").select("poll_id, option_id").eq("user_id",i.id).in("poll_id",I);if(O){const R={};O.forEach(z=>{R[z.poll_id]||(R[z.poll_id]=[]),R[z.poll_id].push(z.option_id)}),m(R)}},N=(I,O)=>{c(R=>({...R,[I]:O}))},C=(I,O,R)=>{c(z=>{const W=z[I]||[];return R?{...z,[I]:[...W,O]}:{...z,[I]:W.filter(V=>V!==O)}})},P=async I=>{if(!i)return;const O=o[I];if(!O||Array.isArray(O)&&O.length===0){Dt.error("Please select an option");return}_(R=>[...R,I]);try{await ae.from("levelup_brief_poll_responses").delete().eq("poll_id",I).eq("user_id",i.id);const R=Array.isArray(O)?O:[O],z=R.map(V=>({poll_id:I,option_id:V,user_id:i.id})),{error:W}=await ae.from("levelup_brief_poll_responses").insert(z);if(W)throw W;m(V=>({...V,[I]:R})),Dt.success("Response submitted!")}catch(R){console.error("Error submitting poll response:",R),Dt.error("Failed to submit response")}finally{_(R=>R.filter(z=>z!==I))}},A=I=>(I.includes("mediadelivery.net")||I.includes("bunny"),I);return s.jsx(mn,{open:e,onOpenChange:I=>!I&&r(),children:s.jsxs(pn,{className:"max-w-2xl max-h-[90vh] p-0 overflow-hidden",children:[s.jsx("div",{className:"bg-gradient-to-r from-primary to-primary/80 p-4 text-primary-foreground",children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"p-2 bg-white/20 rounded-lg",children:s.jsx(mT,{className:"h-6 w-6"})}),s.jsxs("div",{children:[s.jsx(ir,{variant:"secondary",className:"mb-1 bg-white/20 text-white border-0",children:"The LevelUp Brief"}),s.jsx(gn,{className:"text-xl font-bold text-white",children:t.brief.title})]})]})}),s.jsx(qu,{className:"max-h-[calc(90vh-180px)]",children:s.jsxs("div",{className:"p-6 space-y-6",children:[t.brief.description&&s.jsx("p",{className:"text-muted-foreground",children:t.brief.description}),t.brief.video_url&&s.jsx("div",{className:"relative w-full aspect-video rounded-lg overflow-hidden bg-muted",children:s.jsx("iframe",{src:A(t.brief.video_url),className:"absolute inset-0 w-full h-full",allow:"autoplay; fullscreen; picture-in-picture",allowFullScreen:!0})}),t.links.length>0&&s.jsxs("div",{className:"space-y-3",children:[s.jsx("h4",{className:"font-semibold text-foreground",children:"Quick Links"}),s.jsx("div",{className:"flex flex-wrap gap-2",children:t.links.map(I=>s.jsxs(de,{variant:"outline",size:"sm",onClick:()=>window.open(I.url,"_blank"),className:"gap-2",children:[s.jsx(oa,{className:"h-4 w-4"}),I.title]},I.id))})]}),t.polls.map(I=>{var z,W;const O=((z=a[I.id])==null?void 0:z.length)>0,R=g.includes(I.id);return s.jsxs("div",{className:"space-y-3 p-4 bg-muted/50 rounded-lg border",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("h4",{className:"font-semibold text-foreground",children:I.question}),O&&s.jsxs(ir,{variant:"secondary",className:"gap-1",children:[s.jsx(E_,{className:"h-3 w-3"}),"Responded"]})]}),I.poll_type==="single"?s.jsx(Zfe,{value:o[I.id]||((W=a[I.id])==null?void 0:W[0])||"",onValueChange:V=>N(I.id,V),className:"space-y-2",children:I.options.map(V=>s.jsxs("div",{className:"flex items-center space-x-2",children:[s.jsx(Yfe,{value:V.id,id:V.id}),s.jsx(mt,{htmlFor:V.id,className:"cursor-pointer",children:V.option_text})]},V.id))}):s.jsx("div",{className:"space-y-2",children:I.options.map(V=>{const Q=(o[I.id]||a[I.id]||[]).includes(V.id);return s.jsxs("div",{className:"flex items-center space-x-2",children:[s.jsx(dx,{id:V.id,checked:Q,onCheckedChange:te=>C(I.id,V.id,te)}),s.jsx(mt,{htmlFor:V.id,className:"cursor-pointer",children:V.option_text})]},V.id)})}),s.jsx(de,{size:"sm",onClick:()=>P(I.id),disabled:R,children:R?"Submitting...":O?"Update Response":"Submit"})]},I.id)})]})}),s.jsxs("div",{className:"p-4 border-t bg-muted/30 flex justify-between items-center",children:[s.jsx(de,{variant:"ghost",size:"sm",onClick:n,children:"Don't show again"}),s.jsx(de,{onClick:r,children:"Got it!"})]})]})})},Wze=()=>{const{user:t}=rn(),[e,r]=D.useState(null),[n,i]=D.useState(!1),[o,c]=D.useState(!0),[a,m]=D.useState(!1),g=D.useCallback(async()=>{if(!t){c(!1);return}try{const{data:P,error:A}=await ae.from("levelup_briefs").select("*").eq("is_published",!0).lte("publish_date",new Date().toISOString()).order("publish_date",{ascending:!1}).limit(1).single();if(A||!P){c(!1);return}const{data:I}=await ae.from("levelup_brief_views").select("*").eq("brief_id",P.id).eq("user_id",t.id).maybeSingle(),[O,R]=await Promise.all([ae.from("levelup_brief_links").select("*").eq("brief_id",P.id).order("sort_order"),ae.from("levelup_brief_polls").select("*").eq("brief_id",P.id).order("sort_order")]),z=[];if(R.data)for(const Q of R.data){const{data:te}=await ae.from("levelup_brief_poll_options").select("*").eq("poll_id",Q.id).order("sort_order");z.push({...Q,options:te||[]})}const W={brief:P,links:O.data||[],polls:z};r(W);const V=!!I,K=(I==null?void 0:I.dismissed_at)!==null;if(!V)i(!0),m(!0);else if(P.show_frequency==="every_login"&&!K)i(!0),m(!0);else if(P.show_frequency==="daily"){const Q=new Date(I.viewed_at);(new Date().getTime()-Q.getTime())/(1e3*60*60)>=24&&!K&&(i(!0),m(!0))}else m(!K)}catch(P){console.error("Error fetching brief:",P)}finally{c(!1)}},[t]);D.useEffect(()=>{g()},[g]);const _=async()=>{if(!(!t||!e))try{const{data:P}=await ae.from("levelup_brief_views").select("id").eq("brief_id",e.brief.id).eq("user_id",t.id).maybeSingle();P?await ae.from("levelup_brief_views").update({viewed_at:new Date().toISOString()}).eq("id",P.id):await ae.from("levelup_brief_views").insert({brief_id:e.brief.id,user_id:t.id})}catch(P){console.error("Error marking brief as viewed:",P)}};return{currentBrief:e,shouldShowPopup:n,hasUnseenBrief:a,loading:o,openBrief:()=>{i(!0)},closeBrief:()=>{i(!1),_()},dismissBrief:async()=>{if(!(!t||!e))try{const{data:P}=await ae.from("levelup_brief_views").select("id").eq("brief_id",e.brief.id).eq("user_id",t.id).maybeSingle();P?await ae.from("levelup_brief_views").update({dismissed_at:new Date().toISOString()}).eq("id",P.id):await ae.from("levelup_brief_views").insert({brief_id:e.brief.id,user_id:t.id,dismissed_at:new Date().toISOString()}),i(!1),m(!1)}catch(P){console.error("Error dismissing brief:",P)}},refetch:g}};function Gze(){const[t,e]=D.useState(!1),[r,n]=D.useState(!1),[i,o]=D.useState(null);D.useEffect(()=>{if(localStorage.getItem("install-banner-dismissed")||window.matchMedia("(display-mode: standalone)").matches||!/iPhone|iPad|iPod|Android/i.test(navigator.userAgent))return;const j=/iPhone|iPad|iPod/i.test(navigator.userAgent);n(j),e(!0);const N=C=>{C.preventDefault(),o(C)};return window.addEventListener("beforeinstallprompt",N),()=>{window.removeEventListener("beforeinstallprompt",N)}},[]);const c=()=>{localStorage.setItem("install-banner-dismissed","true"),e(!1)},a=async()=>{if(i){await i.prompt();const{outcome:m}=await i.userChoice;m==="accepted"&&c(),o(null)}};return t?s.jsx("div",{className:"fixed bottom-0 left-0 right-0 z-50 p-4 bg-primary text-primary-foreground shadow-lg animate-in slide-in-from-bottom duration-300",children:s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[s.jsx("div",{className:"flex-shrink-0 p-2 bg-primary-foreground/10 rounded-full",children:s.jsx(Pp,{className:"h-5 w-5"})}),s.jsxs("div",{className:"min-w-0",children:[s.jsx("p",{className:"font-medium text-sm",children:"Add LevelUp to your home screen"}),r?s.jsxs("p",{className:"text-xs opacity-80 flex items-center gap-1",children:["Tap ",s.jsx($2e,{className:"h-3 w-3 inline"}),' then "Add to Home Screen"']}):s.jsx("p",{className:"text-xs opacity-80",children:"Quick access anytime"})]})]}),s.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[!r&&i&&s.jsx(de,{size:"sm",variant:"secondary",onClick:a,className:"text-xs",children:"Install"}),s.jsx("button",{onClick:c,className:"p-1.5 hover:bg-primary-foreground/10 rounded-full transition-colors","aria-label":"Dismiss",children:s.jsx(Ni,{className:"h-4 w-4"})})]})]})}):null}const Kze=({children:t,onRefresh:e})=>{const[r,n]=D.useState(!1),[i,o]=D.useState(0),[c,a]=D.useState(!1),m=D.useRef(null),g=D.useRef(0),_=Wn(),j=80,N=120,C=D.useCallback(R=>{const z=m.current;z&&z.scrollTop<=0&&(g.current=R.touches[0].clientY,n(!0))},[]),P=D.useCallback(R=>{if(!r||c)return;const z=m.current;if(!z||z.scrollTop>0){n(!1),o(0);return}const V=R.touches[0].clientY-g.current;if(V>0){const Q=Math.min(V*.5,N);o(Q),Q>10&&R.preventDefault()}},[r,c]),A=D.useCallback(async()=>{if(r)if(n(!1),i>=j&&!c){a(!0),o(j);try{e?await e():await _.invalidateQueries()}catch(R){console.error("Refresh failed:",R)}finally{a(!1),o(0)}}else o(0)},[r,i,c,e,_]),I=Math.min(i/j,1),O=I*180;return s.jsxs("div",{ref:m,className:"h-full overflow-auto",onTouchStart:C,onTouchMove:P,onTouchEnd:A,children:[s.jsx("div",{className:"flex justify-center items-center overflow-hidden transition-all duration-200 ease-out",style:{height:i>0?i:0,opacity:I},children:s.jsx("div",{className:`p-2 rounded-full bg-primary/10 ${c?"animate-spin":""}`,style:{transform:c?void 0:`rotate(${O}deg)`,transition:c?void 0:"transform 0.1s ease-out"},children:s.jsx(R1,{className:"h-5 w-5 text-primary"})})}),s.jsx("div",{style:{transform:i>0?`translateY(${Math.max(0,i-60)}px)`:void 0,transition:r?void 0:"transform 0.2s ease-out"},children:t})]})},Zze=()=>{const{user:t}=rn(),[e,r]=D.useState(!1),[n,i]=D.useState(!1),[o,c]=D.useState(0),[a,m]=D.useState(!0);D.useEffect(()=>{(async()=>{if(!t){m(!1);return}try{const{data:C}=await ae.from("membership_reviews").select("id").eq("user_id",t.id).maybeSingle();if(C){i(!0),r(!1),m(!1);return}const{data:P}=await ae.from("profiles").select("login_count").eq("id",t.id).single(),A=(P==null?void 0:P.login_count)||0;c(A);const I=sessionStorage.getItem("review-prompt-dismissed");r(A>=4&&!I)}catch(C){console.error("Error checking review eligibility:",C)}finally{m(!1)}})()},[t]);const g=D.useCallback(()=>{sessionStorage.setItem("review-prompt-dismissed","true"),r(!1)},[]),_=D.useCallback(async(N,C)=>{if(!t)return{success:!1,error:"Not authenticated"};try{const{error:P}=await ae.from("membership_reviews").insert({user_id:t.id,rating:N,review_text:C});if(P)throw P;return i(!0),r(!1),{success:!0}}catch(P){return console.error("Error submitting review:",P),{success:!1,error:P.message}}},[t]),j=D.useCallback(async()=>{if(t)try{await ae.from("membership_reviews").update({posted_to_google:!0}).eq("user_id",t.id)}catch(N){console.error("Error updating Google review status:",N)}},[t]);return{shouldShowPrompt:e,hasSubmittedReview:n,loginCount:o,isLoading:a,dismissPrompt:g,submitReview:_,markPostedToGoogle:j}},Yze="https://search.google.com/local/writereview?placeid=ChIJM73ERQD1QogRPxupMFObuck&source=g.page.m.ia._&laa=nmx-review-solicitation-ia2",Xze=()=>{const{shouldShowPrompt:t,isLoading:e,dismissPrompt:r,submitReview:n,markPostedToGoogle:i}=Zze(),[o,c]=D.useState(!1),[a,m]=D.useState("review"),[g,_]=D.useState(0),[j,N]=D.useState(0),[C,P]=D.useState(""),[A,I]=D.useState(!1),[O,R]=D.useState(!1);if(e||!t&&!O)return null;const z=async()=>{if(g===0){na({title:"Please select a rating",variant:"destructive"});return}I(!0);const K=await n(g,C);I(!1),K.success?(R(!0),na({title:"Thank you for your feedback!",description:"Your review helps us improve."}),m("google")):na({title:"Error submitting review",description:K.error,variant:"destructive"})},W=async K=>{K&&(await navigator.clipboard.writeText(C||`${g} star rating for LevelUp!`),na({title:"Review copied!",description:"Paste it on Google Reviews."}),await i(),window.open(Yze,"_blank")),c(!1),r()},V=()=>{c(!1),r()};return s.jsxs(s.Fragment,{children:[s.jsxs("button",{onClick:()=>c(!0),className:"fixed bottom-20 right-4 z-40 flex items-center gap-2 rounded-full bg-primary/90 px-3 py-2 text-xs text-primary-foreground shadow-lg backdrop-blur-sm transition-all hover:bg-primary hover:scale-105 md:bottom-6",children:[s.jsx(mh,{className:"h-3.5 w-3.5 fill-current"}),s.jsx("span",{className:"hidden sm:inline",children:"Leave a Review"})]}),s.jsx(mn,{open:o,onOpenChange:V,children:s.jsx(pn,{className:"sm:max-w-md",children:a==="review"?s.jsxs(s.Fragment,{children:[s.jsxs(xn,{children:[s.jsx(gn,{className:"text-center",children:"How are you enjoying LevelUp?"}),s.jsx(fi,{className:"text-center",children:"Your feedback helps us improve the experience for all members."})]}),s.jsxs("div",{className:"space-y-6 py-4",children:[s.jsx("div",{className:"flex justify-center gap-1",children:[1,2,3,4,5].map(K=>s.jsx("button",{type:"button",onClick:()=>_(K),onMouseEnter:()=>N(K),onMouseLeave:()=>N(0),className:"p-1 transition-transform hover:scale-110",children:s.jsx(mh,{className:ar("h-8 w-8 transition-colors",(j||g)>=K?"fill-yellow-400 text-yellow-400":"text-muted-foreground")})},K))}),s.jsx(mi,{placeholder:"Tell us about your experience (optional)",value:C,onChange:K=>P(K.target.value),rows:4,className:"resize-none"}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(de,{variant:"outline",onClick:V,className:"flex-1",children:"Maybe Later"}),s.jsx(de,{onClick:z,disabled:A||g===0,className:"flex-1",children:A?"Submitting...":"Submit Review"})]})]})]}):s.jsxs(s.Fragment,{children:[s.jsxs(xn,{children:[s.jsx(gn,{className:"text-center",children:"🎉 Thank you!"}),s.jsx(fi,{className:"text-center",children:"Would you mind sharing your review on Google? It really helps other agents discover LevelUp!"})]}),s.jsxs("div",{className:"space-y-4 py-4",children:[s.jsx("p",{className:"text-center text-sm text-muted-foreground",children:"We'll copy your review so you can easily paste it."}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(de,{variant:"outline",onClick:()=>W(!1),className:"flex-1",children:"No Thanks"}),s.jsx(de,{onClick:()=>W(!0),className:"flex-1",children:"Yes, Open Google"})]})]})]})})})]})},Jr=({children:t,title:e})=>{var he,xe,pe;const{user:r,signOut:n,isAdmin:i,isBrokerageManager:o}=rn(),{avatarUrl:c}=Bue(r==null?void 0:r.id),{isTrial:a,isExpired:m,expiresAt:g}=FDe(r==null?void 0:r.id);$ue();const{currentBrief:_,shouldShowPopup:j,hasUnseenBrief:N,openBrief:C,closeBrief:P,dismissBrief:A}=Wze(),I=Bs(),O=xx(),[R,z]=D.useState({agentos:!0,tools:!0,marketing:!0,learning:!0,community:!0,help:!1}),W=ve=>{z(ge=>({...ge,[ve]:!ge[ve]}))},V=ve=>ve.split(" ").map(ge=>ge[0]).join("").toUpperCase().slice(0,2),K=ve=>O.pathname===ve,Q=ve=>ve.some(ge=>O.pathname===ge),te=({path:ve,icon:ge,label:ke})=>s.jsxs(de,{variant:"ghost",size:"sm",className:ar("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",K(ve)&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>I(ve),children:[s.jsx(ge,{className:"h-4 w-4"}),ke]}),X=({id:ve,label:ge,icon:ke,children:Ce,activePaths:Se,showBetaBadge:je})=>s.jsxs(y4e,{open:R[ve],onOpenChange:()=>W(ve),children:[s.jsx(x4e,{asChild:!0,children:s.jsxs(de,{variant:"ghost",size:"sm",className:ar("w-full justify-between gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Q(Se)&&"text-primary"),children:[s.jsxs("span",{className:"flex items-center gap-2",children:[s.jsx(ke,{className:"h-4 w-4"}),ge,je&&s.jsx("span",{className:"text-[9px] font-bold uppercase tracking-wide px-1 py-0.5 rounded border border-amber-500 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),s.jsx(pT,{className:ar("h-4 w-4 transition-transform duration-200",R[ve]&&"rotate-180")})]})}),s.jsx(v4e,{className:"pl-4 space-y-1 mt-1",children:Ce})]}),ie=()=>s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsx("div",{className:"p-3 border-b border-sidebar-border",children:s.jsx("img",{src:RX,alt:"LevelUp",className:"h-8 w-auto"})}),s.jsxs("nav",{className:"flex-1 p-3 space-y-1 overflow-y-auto",children:[s.jsx(te,{path:"/dashboard",icon:moe,label:"Dashboard"}),s.jsx(te,{path:"/events",icon:H2,label:"Events"}),s.jsxs(X,{id:"agentos",label:"Agent OS",icon:N5,activePaths:["/innercircle","/innercircle/contacts","/innercircle/plans","/innercircle/popbys","/innercircle/scorecard","/innercircle/listings"],showBetaBadge:!0,children:[s.jsx(te,{path:"/innercircle",icon:bp,label:"InnerCircle"}),s.jsx(te,{path:"/innercircle/contacts",icon:_i,label:"Contacts"}),s.jsx(te,{path:"/innercircle/plans",icon:H2,label:"Plans"}),s.jsx(te,{path:"/innercircle/popbys",icon:yd,label:"Popbys"}),s.jsx(te,{path:"/innercircle/scorecard",icon:_p,label:"Scorecard"}),s.jsx(te,{path:"/innercircle/listings",icon:yc,label:"Listing Exchange"})]}),s.jsxs(X,{id:"tools",label:"Tools",icon:C5,activePaths:["/apps","/ai-toolkit"],children:[s.jsx(te,{path:"/apps",icon:C5,label:"Apps & Tools"}),s.jsx(te,{path:"/ai-toolkit",icon:N5,label:"AI Toolkit"})]}),s.jsxs(X,{id:"marketing",label:"Marketing",icon:mT,activePaths:["/templates","/social-swag","/newsletters"],children:[s.jsx(te,{path:"/templates",icon:A_,label:"Templates"}),s.jsx(te,{path:"/social-swag",icon:A_,label:"Social Swag"}),s.jsx(te,{path:"/newsletters",icon:gT,label:"Newsletters"})]}),s.jsxs(X,{id:"learning",label:"Learning",icon:j2e,activePaths:["/academy","/toolbox"],children:[s.jsx(te,{path:"/academy",icon:eD,label:"Academy"}),s.jsx(te,{path:"/toolbox",icon:xT,label:"Toolbox"})]}),s.jsxs(X,{id:"community",label:"Community",icon:Tf,activePaths:["/community","/wishlist"],children:[s.jsx(te,{path:"/community",icon:_i,label:"Community"}),s.jsx(te,{path:"/wishlist",icon:pM,label:"Wishlist"}),s.jsxs(de,{variant:"ghost",size:"sm",className:"w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",onClick:()=>window.open("https://www.facebook.com/groups/3044917615684135","_blank"),children:[s.jsx(oa,{className:"h-4 w-4"}),"Facebook Group"]})]}),s.jsxs(X,{id:"help",label:"Help & Services",icon:ooe,activePaths:["/support","/additional-services"],children:[s.jsx(te,{path:"/support",icon:goe,label:"Support"}),s.jsx(te,{path:"/additional-services",icon:cu,label:"Additional Services"})]}),i&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"pt-3 pb-1",children:s.jsx("p",{className:"px-2 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:"Admin"})}),s.jsxs(de,{variant:"ghost",size:"sm",className:ar("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",O.pathname.startsWith("/admin")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>I("/admin"),children:[s.jsx(mM,{className:"h-4 w-4"}),"Admin Dashboard"]})]}),o&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"pt-3 pb-1",children:s.jsx("p",{className:"px-2 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:"Brokerage"})}),s.jsxs(de,{variant:"ghost",size:"sm",className:ar("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",K("/brokerage/dashboard")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>I("/brokerage/dashboard"),children:[s.jsx(eg,{className:"h-4 w-4"}),"My Brokerage"]}),s.jsxs(de,{variant:"ghost",size:"sm",className:ar("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",K("/brokerage-resources")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>I("/brokerage-resources"),children:[s.jsx(Hm,{className:"h-4 w-4"}),"Brokerage Resources"]})]})]}),s.jsxs("div",{className:"p-3 border-t border-sidebar-border md:hidden",children:[s.jsxs(de,{variant:"ghost",size:"sm",className:ar("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",K("/profile")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>I("/profile"),children:[s.jsx(bf,{className:"h-4 w-4"}),"Profile"]}),s.jsxs(de,{variant:"ghost",size:"sm",className:"w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",onClick:n,children:[s.jsx(GZ,{className:"h-4 w-4"}),"Sign Out"]})]})]});return s.jsxs("div",{className:"min-h-screen bg-background flex",children:[a&&m&&s.jsx(Eze,{}),s.jsx("aside",{className:"hidden md:flex w-52 flex-col bg-card border-r border-border fixed h-screen z-50",children:s.jsx(ie,{})}),s.jsxs("div",{className:"flex-1 md:ml-52 flex flex-col h-screen overflow-hidden",children:[s.jsx("header",{className:"sticky top-0 z-40 bg-card border-b border-border flex-shrink-0",children:s.jsxs("div",{className:"flex items-center justify-between px-6 py-3",children:[s.jsxs(Uue,{children:[s.jsx(Vue,{asChild:!0,children:s.jsx(de,{variant:"ghost",size:"icon",className:"md:hidden",children:s.jsx(O2e,{className:"h-5 w-5"})})}),s.jsx(O8,{side:"left",className:"w-52 p-0 bg-card",children:s.jsx(ie,{})})]}),s.jsx("div",{className:"flex-1 md:hidden",children:s.jsx("img",{src:RX,alt:"LevelUp",className:"h-8 w-auto"})}),s.jsx("div",{className:"hidden md:flex flex-1 justify-center",children:s.jsx(iQ,{})}),s.jsxs("div",{className:"flex items-center gap-3 ml-auto",children:[a&&!m&&g&&s.jsx(Tze,{expiresAt:g,className:"hidden lg:flex"}),s.jsx("div",{className:"md:hidden",children:s.jsx(iQ,{})}),_&&s.jsx(Aze,{hasUnseenBrief:N,onClick:C}),s.jsx(eze,{}),s.jsx(P$,{}),s.jsxs("span",{className:"hidden sm:block text-sm font-medium text-foreground",children:["Hello, ",((xe=(he=r==null?void 0:r.user_metadata)==null?void 0:he.name)==null?void 0:xe.split(" ")[0])||"User","!"]}),s.jsxs(rg,{children:[s.jsx(ng,{asChild:!0,children:s.jsx("button",{className:"focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 rounded-full",children:s.jsxs(ql,{className:"h-9 w-9 cursor-pointer hover:opacity-80 transition-opacity",children:[s.jsx(Iy,{src:c||void 0}),s.jsx(Hl,{className:"bg-primary text-primary-foreground font-medium text-sm",children:V(((pe=r==null?void 0:r.user_metadata)==null?void 0:pe.name)||(r==null?void 0:r.email)||"U")})]})})}),s.jsxs(Op,{align:"end",className:"w-48",children:[s.jsxs(Ro,{onClick:()=>I("/profile"),className:"cursor-pointer",children:[s.jsx(bf,{className:"h-4 w-4 mr-2"}),"Profile"]}),s.jsx(Hde,{}),s.jsxs(Ro,{onClick:n,className:"cursor-pointer text-destructive focus:text-destructive",children:[s.jsx(GZ,{className:"h-4 w-4 mr-2"}),"Sign Out"]})]})]})]})]})}),s.jsx(Kze,{children:s.jsx("main",{className:"p-4 sm:p-6 lg:p-8 overflow-x-hidden",children:t})}),_&&s.jsx(Hze,{brief:_,open:j,onClose:P,onDismiss:A}),s.jsx(Gze,{}),s.jsx(Xze,{})]})]})};function xC({banners:t,autoPlayInterval:e=5e3,className:r}){const[n,i]=D.useState(0),[o,c]=D.useState(!1),a=D.useCallback(()=>{i(j=>(j+1)%t.length)},[t.length]),m=D.useCallback(()=>{i(j=>(j-1+t.length)%t.length)},[t.length]),g=D.useCallback(j=>{i(j)},[]);if(D.useEffect(()=>{if(t.length<=1||o)return;const j=setInterval(a,e);return()=>clearInterval(j)},[t.length,o,e,a]),!t||t.length===0)return null;const _=t[n];return s.jsxs("div",{className:ar("relative w-full overflow-hidden rounded-xl",r),onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),children:[s.jsxs("div",{className:"relative aspect-[21/9] md:aspect-[3/1] w-full",children:[s.jsxs("div",{className:"absolute inset-0 transition-opacity duration-500",children:[s.jsx("img",{src:_.image_url,alt:_.title,className:"w-full h-full object-cover"}),s.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/70 via-black/20 to-transparent"})]}),s.jsxs("div",{className:"absolute bottom-0 left-0 right-0 p-6 md:p-8 text-white",children:[s.jsx("h2",{className:"text-xl md:text-3xl font-bold mb-2 drop-shadow-lg",children:_.title}),_.description&&s.jsx("p",{className:"text-sm md:text-base text-white/90 mb-4 max-w-2xl drop-shadow",children:_.description}),_.link_url&&s.jsx("a",{href:_.link_url,target:"_blank",rel:"noopener noreferrer",className:"inline-block",children:s.jsx(de,{variant:"secondary",className:"bg-white/90 hover:bg-white text-foreground font-semibold",children:_.link_text||"Learn More"})})]}),t.length>1&&s.jsxs(s.Fragment,{children:[s.jsx(de,{variant:"ghost",size:"icon",className:ar("absolute left-2 top-1/2 -translate-y-1/2 bg-black/30 hover:bg-black/50 text-white rounded-full","opacity-0 transition-opacity",o&&"opacity-100"),onClick:m,children:s.jsx(I1,{className:"h-6 w-6"})}),s.jsx(de,{variant:"ghost",size:"icon",className:ar("absolute right-2 top-1/2 -translate-y-1/2 bg-black/30 hover:bg-black/50 text-white rounded-full","opacity-0 transition-opacity",o&&"opacity-100"),onClick:a,children:s.jsx(wd,{className:"h-6 w-6"})})]})]}),t.length>1&&s.jsx("div",{className:"absolute bottom-3 left-1/2 -translate-x-1/2 flex gap-2",children:t.map((j,N)=>s.jsx("button",{onClick:()=>g(N),className:ar("w-2 h-2 rounded-full transition-all duration-300",N===n?"bg-white w-6":"bg-white/50 hover:bg-white/70"),"aria-label":`Go to slide ${N+1}`},N))})]})}const R$=t=>{const e=new Date,r=new Date(t),n=Xhe(r,-15),i=Zhe(r,1);return ife(e,{start:n,end:i})},Qze=({events:t,registrations:e,onNavigateToEvents:r})=>{const[n,i]=D.useState(new Date);D.useEffect(()=>{const _=setInterval(()=>{i(new Date)},6e4);return()=>clearInterval(_)},[]);const o=t.filter(_=>R$(_.event_date));if(o.length===0)return null;const c=o[0],a=e.find(_=>_.event_id===c.id),m=(a==null?void 0:a.zoom_join_url)||c.zoom_link,g=!!a;return s.jsxs("div",{className:"relative mb-8 overflow-hidden rounded-xl bg-gradient-to-r from-red-500/10 via-red-500/5 to-primary/10 border border-red-500/30",children:[s.jsx("div",{className:"absolute inset-0 bg-gradient-to-r from-red-500/5 to-transparent animate-pulse"}),s.jsx("div",{className:"relative p-4 sm:p-6",children:s.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-4",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsxs("div",{className:"relative flex items-center justify-center",children:[s.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-red-500 opacity-75"}),s.jsx("span",{className:"relative flex h-3 w-3 rounded-full bg-red-500"})]}),s.jsxs("div",{className:"flex items-center gap-2 text-red-500 font-bold text-sm uppercase tracking-wider",children:[s.jsx(Y6,{className:"h-4 w-4"}),"Live Now"]})]}),s.jsxs("div",{className:"flex-1",children:[s.jsx("h3",{className:"font-semibold text-lg text-foreground line-clamp-1",children:c.title}),s.jsxs("p",{className:"text-sm text-muted-foreground",children:["Started at ",Vn(new Date(c.event_date),"h:mm a")]})]}),s.jsx("div",{className:"flex items-center gap-2",children:g?s.jsxs(de,{onClick:()=>window.open(m,"_blank"),className:"bg-red-500 hover:bg-red-600 text-white gap-2",children:[s.jsx(oa,{className:"h-4 w-4"}),"Join Now"]}):s.jsxs(de,{variant:"outline",onClick:r,className:"border-red-500/50 text-red-500 hover:bg-red-500/10 gap-2",children:[s.jsx(_i,{className:"h-4 w-4"}),"Register & Join"]})})]})})]})};var Sq="Progress",Nq=100,[Jze]=Yo(Sq),[eBe,tBe]=Jze(Sq),Xfe=D.forwardRef((t,e)=>{const{__scopeProgress:r,value:n=null,max:i,getValueLabel:o=rBe,...c}=t;(i||i===0)&&!aQ(i)&&console.error(nBe(`${i}`,"Progress"));const a=aQ(i)?i:Nq;n!==null&&!oQ(n,a)&&console.error(sBe(`${n}`,"Progress"));const m=oQ(n,a)?n:null,g=WM(m)?o(m,a):void 0;return s.jsx(eBe,{scope:r,value:m,max:a,children:s.jsx(yn.div,{"aria-valuemax":a,"aria-valuemin":0,"aria-valuenow":WM(m)?m:void 0,"aria-valuetext":g,role:"progressbar","data-state":epe(m,a),"data-value":m??void 0,"data-max":a,...c,ref:e})})});Xfe.displayName=Sq;var Qfe="ProgressIndicator",Jfe=D.forwardRef((t,e)=>{const{__scopeProgress:r,...n}=t,i=tBe(Qfe,r);return s.jsx(yn.div,{"data-state":epe(i.value,i.max),"data-value":i.value??void 0,"data-max":i.max,...n,ref:e})});Jfe.displayName=Qfe;function rBe(t,e){return`${Math.round(t/e*100)}%`}function epe(t,e){return t==null?"indeterminate":t===e?"complete":"loading"}function WM(t){return typeof t=="number"}function aQ(t){return WM(t)&&!isNaN(t)&&t>0}function oQ(t,e){return WM(t)&&!isNaN(t)&&t<=e&&t>=0}function nBe(t,e){return`Invalid prop \`max\` of value \`${t}\` supplied to \`${e}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${Nq}\`.`}function sBe(t,e){return`Invalid prop \`value\` of value \`${t}\` supplied to \`${e}\`. The \`value\` prop must be: - a positive number - less than the value passed to \`max\` (or ${Nq} if no \`max\` prop is set) - \`null\` or \`undefined\` if the progress is indeterminate. Defaulting to \`null\`.`}var tpe=Xfe,iBe=Jfe;const vc=D.forwardRef(({className:t,value:e,...r},n)=>s.jsx(tpe,{ref:n,className:ar("relative h-4 w-full overflow-hidden rounded-full bg-secondary",t),...r,children:s.jsx(iBe,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(e||0)}%)`}})}));vc.displayName=tpe.displayName;function aBe(){const{user:t,isBrokerageManager:e}=rn(),[r,n]=D.useState([]),[i,o]=D.useState([]),[c,a]=D.useState(!1),[m,g]=D.useState(!0),_=e?"brokerage_manager":"agent";D.useEffect(()=>{if(!(t!=null&&t.id)){g(!1);return}j()},[t==null?void 0:t.id,_]);const j=async()=>{if(t!=null&&t.id)try{const{data:W,error:V}=await ae.from("onboarding_checklist_items").select("*").eq("target_role",_).eq("is_active",!0).order("sort_order");if(V)throw V;const{data:K,error:Q}=await ae.from("onboarding_checklist_progress").select("item_id, completed_at").eq("user_id",t.id);if(Q)throw Q;const{data:te,error:X}=await ae.from("onboarding_checklist_dismissed").select("id").eq("user_id",t.id).maybeSingle();if(X)throw X;n(W||[]),o(K||[]),a(!!te),W&&W.length>0&&await N(W,K||[])}catch(W){console.error("Error fetching checklist data:",W)}finally{g(!1)}},N=async(W,V)=>{if(!(t!=null&&t.id))return;const K=V.map(je=>je.item_id),Q=W.filter(je=>!K.includes(je.id));if(Q.length===0)return;const te={},{data:X}=await ae.from("profiles").select("brokerage_id").eq("id",t.id).maybeSingle(),ie=X==null?void 0:X.brokerage_id;if(ie){const{data:je,error:et}=await ae.from("profiles").select("id").eq("brokerage_id",ie).neq("id",t.id);!et&&je&&(te.add_agent=je.length>0)}const{count:he}=await ae.from("resource_shares").select("id",{count:"exact",head:!0}).eq("sender_id",t.id);te.share_resource=(he||0)>0;const{count:xe}=await ae.from("community_posts").select("id",{count:"exact",head:!0}).eq("user_id",t.id);te.post_community=(xe||0)>0;const{count:pe}=await ae.from("event_registrations").select("id",{count:"exact",head:!0}).eq("user_id",t.id);te.register_event=(pe||0)>0;const{count:ve}=await ae.from("content_engagement_logs").select("id",{count:"exact",head:!0}).eq("user_id",t.id).eq("resource_type","template");te.view_template=(ve||0)>0;const{count:ge}=await ae.from("content_engagement_logs").select("id",{count:"exact",head:!0}).eq("user_id",t.id).eq("resource_type","academy_video");te.watch_academy=(ge||0)>0;const{count:ke}=await ae.from("content_engagement_logs").select("id",{count:"exact",head:!0}).eq("user_id",t.id).eq("resource_type","toolbox");te.use_toolbox=(ke||0)>0;const{count:Ce}=await ae.from("activity_logs").select("id",{count:"exact",head:!0}).eq("user_id",t.id);te.launch_app=(Ce||0)>0;const Se=[];for(const je of Q)if(te[je.action_type])try{const{error:et}=await ae.from("onboarding_checklist_progress").insert({user_id:t.id,item_id:je.id});et||Se.push({item_id:je.id,completed_at:new Date().toISOString()})}catch(et){console.error("Error auto-completing item:",et)}Se.length>0&&o(je=>[...je,...Se])},C=async W=>{if(t!=null&&t.id)try{const{error:V}=await ae.from("onboarding_checklist_progress").insert({user_id:t.id,item_id:W});if(V)throw V;o(K=>[...K,{item_id:W,completed_at:new Date().toISOString()}])}catch(V){console.error("Error marking item complete:",V)}},P=async()=>{if(t!=null&&t.id)try{const{error:W}=await ae.from("onboarding_checklist_dismissed").insert({user_id:t.id});if(W)throw W;a(!0)}catch(W){console.error("Error dismissing checklist:",W)}},A=i.length,I=r.length,O=I>0&&A>=I,R=I>0?A/I*100:0;return{items:r,progress:i,isDismissed:c,loading:m,completedCount:A,totalCount:I,isComplete:O,progressPercentage:R,isItemComplete:W=>i.some(V=>V.item_id===W),markComplete:C,dismiss:P,refetch:j}}const oBe={add_agent:s.jsx(_i,{className:"h-4 w-4"}),share_resource:s.jsx(ph,{className:"h-4 w-4"}),post_community:s.jsx(Tf,{className:"h-4 w-4"}),register_event:s.jsx(ko,{className:"h-4 w-4"}),view_template:s.jsx(F2e,{className:"h-4 w-4"}),watch_academy:s.jsx(eD,{className:"h-4 w-4"}),use_toolbox:s.jsx(xT,{className:"h-4 w-4"}),launch_app:s.jsx(w2e,{className:"h-4 w-4"})};function lBe(){const{items:t,isDismissed:e,loading:r,completedCount:n,totalCount:i,isComplete:o,progressPercentage:c,isItemComplete:a,markComplete:m,dismiss:g}=aBe(),[_,j]=D.useState(!0);return r||e||i===0||o?null:s.jsxs(at,{className:"mb-6 border-primary/20 bg-gradient-to-r from-primary/5 to-transparent",children:[s.jsxs(xr,{className:"pb-3",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:s.jsx(G2,{className:"h-5 w-5 text-primary"})}),s.jsxs("div",{children:[s.jsx(wr,{className:"text-lg",children:"Get Started with LevelUp"}),s.jsx("p",{className:"text-sm text-muted-foreground mt-0.5",children:"Complete these steps to make the most of your membership"})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(de,{variant:"ghost",size:"sm",onClick:()=>j(!_),className:"h-8 w-8 p-0",children:_?s.jsx(W6,{className:"h-4 w-4"}):s.jsx(pT,{className:"h-4 w-4"})}),s.jsx(de,{variant:"ghost",size:"sm",onClick:g,className:"h-8 w-8 p-0 text-muted-foreground hover:text-foreground",children:s.jsx(Ni,{className:"h-4 w-4"})})]})]}),s.jsxs("div",{className:"mt-4",children:[s.jsxs("div",{className:"flex items-center justify-between text-sm mb-2",children:[s.jsx("span",{className:"text-muted-foreground",children:"Progress"}),s.jsxs("span",{className:"font-medium",children:[n," of ",i," complete"]})]}),s.jsx(vc,{value:c,className:"h-2"})]})]}),_&&s.jsx(ct,{className:"pt-0",children:s.jsx("div",{className:"space-y-3",children:t.map(N=>{const C=a(N.id);return s.jsxs("div",{className:ar("flex items-start gap-3 p-3 rounded-lg transition-colors",C?"bg-muted/50":"bg-background hover:bg-muted/30 cursor-pointer"),onClick:()=>!C&&m(N.id),children:[s.jsx("div",{className:"mt-0.5",children:C?s.jsx(E_,{className:"h-5 w-5 text-primary"}):s.jsx(hM,{className:"h-5 w-5 text-muted-foreground"})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-muted-foreground",children:oBe[N.action_type]||s.jsx(hM,{className:"h-4 w-4"})}),s.jsx("span",{className:ar("font-medium",C&&"line-through text-muted-foreground"),children:N.title})]}),N.description&&s.jsx("p",{className:ar("text-sm text-muted-foreground mt-1",C&&"line-through"),children:N.description})]})]},N.id)})})})]})}const sg=()=>Sr({queryKey:["relationship-types"],queryFn:async()=>{const{data:t,error:e}=await ae.from("relationship_types").select("*").order("sort_order");if(e)throw e;return t}}),ig=t=>{const{user:e}=rn();return Sr({queryKey:["innercircle-contacts",e==null?void 0:e.id,t],queryFn:async()=>{let r=ae.from("innercircle_contacts").select(` *, tags:innercircle_contact_tags( id, contact_id, relationship_type_id, relationship_type:relationship_types(*) ) `).order("first_name");const{data:n,error:i}=await r;if(i)throw i;return n},enabled:!!e})},cBe=t=>Sr({queryKey:["innercircle-contact",t],queryFn:async()=>{const{data:e,error:r}=await ae.from("innercircle_contacts").select(` *, tags:innercircle_contact_tags( id, contact_id, relationship_type_id, relationship_type:relationship_types(*) ) `).eq("id",t).maybeSingle();if(r)throw r;return e},enabled:!!t}),rpe=()=>{const{user:t}=rn();return Sr({queryKey:["innercircle-contact-counts",t==null?void 0:t.id],queryFn:async()=>{const{data:e,error:r}=await ae.from("innercircle_contacts").select(` id, tags:innercircle_contact_tags(relationship_type_id) `);if(r)throw r;const n={};return e==null||e.forEach(i=>{var o;(o=i.tags)==null||o.forEach(c=>{n[c.relationship_type_id]=(n[c.relationship_type_id]||0)+1})}),n},enabled:!!t})},npe=()=>{const t=Wn(),{user:e}=rn();return zr({mutationFn:async r=>{const{tagIds:n,...i}=r,o={...i,birthday:i.birthday||null,home_anniversary:i.home_anniversary||null,owner_user_id:e.id},{data:c,error:a}=await ae.from("innercircle_contacts").insert(o).select().single();if(a)throw a;if(n&&n.length>0){const{error:m}=await ae.from("innercircle_contact_tags").insert(n.map(g=>({contact_id:c.id,relationship_type_id:g})));if(m)throw m}return c},onSuccess:()=>{t.invalidateQueries({queryKey:["innercircle-contacts"]}),t.invalidateQueries({queryKey:["innercircle-contact-counts"]}),na({title:"Contact created successfully"})},onError:r=>{na({title:"Error creating contact",description:r.message,variant:"destructive"})}})},spe=()=>{const t=Wn();return zr({mutationFn:async({id:e,...r})=>{const{tagIds:n,tags:i,...o}=r,c={...o,birthday:o.birthday||null,home_anniversary:o.home_anniversary||null},{data:a,error:m}=await ae.from("innercircle_contacts").update(c).eq("id",e).select().single();if(m)throw m;if(n!==void 0&&(await ae.from("innercircle_contact_tags").delete().eq("contact_id",e),n.length>0)){const{error:g}=await ae.from("innercircle_contact_tags").insert(n.map(_=>({contact_id:e,relationship_type_id:_})));if(g)throw g}return a},onSuccess:()=>{t.invalidateQueries({queryKey:["innercircle-contacts"]}),t.invalidateQueries({queryKey:["innercircle-contact"]}),t.invalidateQueries({queryKey:["innercircle-contact-counts"]}),na({title:"Contact updated successfully"})},onError:e=>{na({title:"Error updating contact",description:e.message,variant:"destructive"})}})},ipe=()=>{const t=Wn();return zr({mutationFn:async e=>{const{error:r}=await ae.from("innercircle_contacts").delete().eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["innercircle-contacts"]}),t.invalidateQueries({queryKey:["innercircle-contact-counts"]}),na({title:"Contact deleted successfully"})},onError:e=>{na({title:"Error deleting contact",description:e.message,variant:"destructive"})}})},Cq=()=>Sr({queryKey:["action-types"],queryFn:async()=>{const{data:t,error:e}=await ae.from("action_types").select("*").order("sort_order");if(e)throw e;return t}}),uBe=t=>Sr({queryKey:["action-scripts",t],queryFn:async()=>{let e=ae.from("action_scripts").select("*, action_type:action_types(*)");const{data:r,error:n}=await e;if(n)throw n;return r}}),dBe=()=>Sr({queryKey:["touchpoint-plans"],queryFn:async()=>{const{data:t,error:e}=await ae.from("touchpoint_plans").select(` *, items:touchpoint_plan_items( *, action_type:action_types(*), default_script:action_scripts(*) ) `).order("name");if(e)throw e;return t}}),hBe=()=>{const t=Wn(),{user:e}=rn();return zr({mutationFn:async({name:r,description:n})=>{const{data:i,error:o}=await ae.from("touchpoint_plans").insert({name:r,description:n,owner_user_id:e.id,active:!0,is_template:!1}).select().single();if(o)throw o;return i},onSuccess:()=>{t.invalidateQueries({queryKey:["touchpoint-plans"]}),na({title:"Plan created successfully"})},onError:r=>{na({title:"Error creating plan",description:r.message,variant:"destructive"})}})},fBe=()=>{const t=Wn();return zr({mutationFn:async({id:e,name:r,description:n})=>{const{data:i,error:o}=await ae.from("touchpoint_plans").update({name:r,description:n}).eq("id",e).select().single();if(o)throw o;return i},onSuccess:()=>{t.invalidateQueries({queryKey:["touchpoint-plans"]}),na({title:"Plan updated successfully"})}})},pBe=()=>{const t=Wn();return zr({mutationFn:async e=>{const{error:r}=await ae.from("touchpoint_plans").delete().eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["touchpoint-plans"]}),na({title:"Plan deleted successfully"})}})},mBe=()=>{const t=Wn();return zr({mutationFn:async({planId:e,items:r})=>{if(await ae.from("touchpoint_plan_items").delete().eq("plan_id",e),r.length>0){const{error:n}=await ae.from("touchpoint_plan_items").insert(r.map(i=>({plan_id:e,month_number:i.month_number,action_type_id:i.action_type_id,default_script_id:i.default_script_id||null,notes:i.notes})));if(n)throw n}},onSuccess:()=>{t.invalidateQueries({queryKey:["touchpoint-plans"]}),na({title:"Plan schedule updated"})}})},gBe=()=>{const t=Wn();return zr({mutationFn:async({actionTypeId:e,title:r,scriptBody:n,emailSubject:i,tone:o})=>{const{data:c,error:a}=await ae.from("action_scripts").insert({action_type_id:e,title:r,script_body:n,email_subject:i||null,tone:o||null,active:!0}).select().single();if(a)throw a;return c},onSuccess:()=>{t.invalidateQueries({queryKey:["action-scripts"]}),na({title:"Script created successfully"})},onError:e=>{na({title:"Error creating script",description:e.message,variant:"destructive"})}})},yBe=()=>{const{user:t}=rn();return Sr({queryKey:["user-plan-enrollments",t==null?void 0:t.id],queryFn:async()=>{const{data:e,error:r}=await ae.from("user_plan_enrollments").select(` *, plan:touchpoint_plans(*), relationship_type:relationship_types(*) `);if(r)throw r;return e},enabled:!!t})},xBe=()=>{const t=Wn(),{user:e}=rn();return zr({mutationFn:async({planId:r,relationshipTypeId:n,active:i})=>{const{data:o}=await ae.from("user_plan_enrollments").select("id").eq("plan_id",r).eq("relationship_type_id",n).maybeSingle();if(o){const{error:c}=await ae.from("user_plan_enrollments").update({active:i}).eq("id",o.id);if(c)throw c}else if(i){const{error:c}=await ae.from("user_plan_enrollments").insert({owner_user_id:e.id,plan_id:r,relationship_type_id:n,active:!0,start_date:new Date().toISOString().split("T")[0]});if(c)throw c}},onSuccess:()=>{t.invalidateQueries({queryKey:["user-plan-enrollments"]}),na({title:"Plan enrollment updated"})}})},zD=(t=7)=>{const{user:e}=rn();return Sr({queryKey:["contact-touch-logs",e==null?void 0:e.id,t],queryFn:async()=>{const r=new Date;r.setDate(r.getDate()-t);const{data:n,error:i}=await ae.from("contact_touch_logs").select(` *, contact:innercircle_contacts(*), action_type:action_types(*) `).gte("completed_at",r.toISOString()).order("completed_at",{ascending:!1});if(i)throw i;return n},enabled:!!e})},ape=()=>{const{user:t}=rn();return Sr({queryKey:["contacts-last-touch",t==null?void 0:t.id],queryFn:async()=>{const{data:e,error:r}=await ae.from("contact_touch_logs").select("contact_id, completed_at").order("completed_at",{ascending:!1});if(r)throw r;const n={};return e==null||e.forEach(i=>{n[i.contact_id]||(n[i.contact_id]=i.completed_at)}),n},enabled:!!t})},vBe=(t=90)=>{const{data:e}=ig(),{data:r}=ape();if(!e||!r)return{contacts:[],count:0};const n=new Date;n.setDate(n.getDate()-t);const i=e.filter(o=>{const c=r[o.id];return c?new Date(c){const t=Wn(),{user:e}=rn();return zr({mutationFn:async({contactId:r,actionTypeId:n,scriptUsedId:i,notes:o})=>{const{data:c,error:a}=await ae.from("contact_touch_logs").insert({owner_user_id:e.id,contact_id:r,action_type_id:n,script_used_id:i,notes:o,completed_at:new Date().toISOString()}).select().single();if(a)throw a;return c},onSuccess:()=>{t.invalidateQueries({queryKey:["contact-touch-logs"]}),t.invalidateQueries({queryKey:["contacts-last-touch"]}),t.invalidateQueries({queryKey:["today-actions"]}),na({title:"Action completed!"})}})},lpe="agentos_weekly_touch_goal",lQ=20,GM=()=>{if(typeof window>"u")return lQ;const t=localStorage.getItem(lpe);if(t){const e=parseInt(t,10);if(!isNaN(e)&&e>0)return e}return lQ},cpe=t=>{localStorage.setItem(lpe,t.toString())},upe=()=>{const{data:t}=zD(7),e=new Date;e.setHours(0,0,0,0);const r=new Date(e);r.setDate(e.getDate()-e.getDay());const n=(t==null?void 0:t.filter(c=>new Date(c.completed_at)>=r).length)||0;let i=0;if(t&&t.length>0){const c=new Set(t.map(m=>new Date(m.completed_at).toDateString()));let a=new Date(e);for(;c.has(a.toDateString());)i++,a.setDate(a.getDate()-1)}const o=GM();return{actionsThisWeek:n,weeklyGoal:o,streak:i,progress:Math.min(n/o*100,100)}},_Be=()=>{const{user:t}=rn();return Sr({queryKey:["contact-plan-cycles",t==null?void 0:t.id],queryFn:async()=>{const{data:e,error:r}=await ae.from("contact_plan_cycles").select(` *, contact:innercircle_contacts(*), plan:touchpoint_plans( *, items:touchpoint_plan_items( *, action_type:action_types(*), default_script:action_scripts(*) ) ) `);if(r)throw r;return e},enabled:!!t})},bBe=()=>{const t=Wn(),{user:e}=rn();return zr({mutationFn:async()=>{const{data:r}=await ae.from("user_plan_enrollments").select("*").eq("active",!0);if(!r||r.length===0)return;const{data:n}=await ae.from("innercircle_contacts").select(` id, tags:innercircle_contact_tags(relationship_type_id) `);if(!n)return;const{data:i}=await ae.from("contact_plan_cycles").select("contact_id, plan_id"),o=new Set((i==null?void 0:i.map(a=>`${a.contact_id}-${a.plan_id}`))||[]),c=[];for(const a of n)for(const m of a.tags||[]){const g=r.find(_=>_.relationship_type_id===m.relationship_type_id);g&&!o.has(`${a.id}-${g.plan_id}`)&&c.push({contact_id:a.id,plan_id:g.plan_id,relationship_type_id:m.relationship_type_id})}if(c.length>0){const{error:a}=await ae.from("contact_plan_cycles").insert(c);if(a)throw a}return c.length},onSuccess:r=>{t.invalidateQueries({queryKey:["contact-plan-cycles"]}),r&&r>0&&na({title:`${r} contact(s) enrolled in plans`})}})},dpe=()=>{const{user:t}=rn(),{data:e}=_Be(),{data:r}=zD(30);return Sr({queryKey:["today-actions",t==null?void 0:t.id,e==null?void 0:e.length,r==null?void 0:r.length],queryFn:async()=>{var N;if(!e||e.length===0)return[];const n=new Date,i=[],o=new Date(n.getFullYear(),n.getMonth(),1),c=new Set((r==null?void 0:r.filter(C=>new Date(C.completed_at)>=o).map(C=>`${C.contact_id}-${C.action_type_id}`))||[]);for(const C of e){if(!((N=C.plan)!=null&&N.items)||C.plan.items.length===0||!C.contact)continue;const P=new Date(C.cycle_start_date),I=Math.floor((n.getTime()-P.getTime())/(30.44*24*60*60*1e3))%12+1,O=C.plan.items.find(R=>R.month_number===I);if(O&&O.action_type){const R=`${C.contact_id}-${O.action_type_id}`;if(!c.has(R)){const{data:z}=await ae.from("relationship_types").select("name").eq("id",C.relationship_type_id).single();i.push({contact:C.contact,actionType:O.action_type,script:O.default_script||void 0,planName:C.plan.name,relationshipTypeName:(z==null?void 0:z.name)||"",monthNumber:I})}}}const a=5,m=n.getDate(),g=i.sort((C,P)=>C.contact.first_name.localeCompare(P.contact.first_name)),_=(m-1)%Math.max(1,g.length);return[...g.slice(_),...g.slice(0,_)].slice(0,a)},enabled:!!t&&!!e})};function wBe(){const t=Bs(),{data:e,isLoading:r}=dpe(),{data:n}=ig(),i=upe(),[o,c]=D.useState(GM()),[a,m]=D.useState(""),[g,_]=D.useState(!1);D.useEffect(()=>{c(GM())},[]);const j=()=>{const K=parseInt(a,10);if(isNaN(K)||K<1){na({title:"Invalid goal",description:"Please enter a number greater than 0",variant:"destructive"});return}c(K),cpe(K),_(!1),na({title:"Goal updated",description:`Weekly touch goal set to ${K}`})},N=()=>{m(o.toString()),_(!0)},C=Cp(new Date),P=hc(C,7),A=K=>{if(!K)return null;const Q=new Date(K);return new Date(C.getFullYear(),Q.getMonth(),Q.getDate())},I=(n==null?void 0:n.map(K=>{const Q=A(K.birthday),te=A(K.home_anniversary),X=[];return Q&&Q>=C&&Q<=P&&X.push({contact:K,type:"birthday",date:Q,isToday:Wo(Q,C)}),te&&te>=C&&te<=P&&X.push({contact:K,type:"anniversary",date:te,isToday:Wo(te,C)}),X}).flat().sort((K,Q)=>K.date.getTime()-Q.date.getTime()).slice(0,3))||[],O=(n==null?void 0:n.filter(K=>{const Q=A(K.birthday),te=A(K.home_anniversary);return Q&&Wo(Q,C)||te&&Wo(te,C)}).length)||0,R=(e==null?void 0:e.length)||0,z=O+R,W=(i==null?void 0:i.actionsThisWeek)||0,V=(i==null?void 0:i.streak)||0;return r?s.jsx(at,{className:"bg-gradient-to-br from-primary/5 via-primary/10 to-primary/5 border-primary/20",children:s.jsx(ct,{className:"p-4",children:s.jsxs("div",{className:"animate-pulse flex items-center gap-4",children:[s.jsx("div",{className:"h-12 w-12 bg-primary/20 rounded-lg"}),s.jsxs("div",{className:"flex-1 space-y-2",children:[s.jsx("div",{className:"h-4 bg-primary/20 rounded w-1/3"}),s.jsx("div",{className:"h-3 bg-primary/10 rounded w-1/2"})]})]})})}):s.jsxs(at,{className:"bg-gradient-to-br from-primary/5 via-primary/10 to-primary/5 border-primary/20",children:[s.jsxs(xr,{className:"pb-2",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs(wr,{className:"text-lg flex items-center gap-2",children:[s.jsx(_i,{className:"h-5 w-5 text-primary"}),"Agent OS"]}),s.jsx("div",{className:"flex items-center gap-2",children:V>0&&s.jsxs(ir,{variant:"secondary",className:"gap-1 bg-orange-500/10 text-orange-600 border-orange-200",children:[s.jsx(doe,{className:"h-3 w-3"}),V," day streak"]})})]}),s.jsxs("p",{className:"text-sm text-muted-foreground",children:[z>0?s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"text-primary font-medium",children:[z," tasks"]})," for today"]}):"No tasks for today",W>0&&s.jsxs("span",{className:"ml-2",children:["• ",s.jsx("span",{className:"text-emerald-600 font-medium",children:W})," touches this week"]})]})]}),s.jsxs(ct,{className:"space-y-4",children:[s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsxs(de,{size:"sm",variant:"outline",className:"gap-1.5",onClick:K=>{K.stopPropagation(),t("/innercircle/contacts?new=true")},children:[s.jsx(yM,{className:"h-3.5 w-3.5"}),"Add Contact"]}),s.jsxs(de,{size:"sm",variant:"outline",className:"gap-1.5",onClick:K=>{K.stopPropagation(),t("/innercircle")},children:[s.jsx(Yl,{className:"h-3.5 w-3.5"}),"Log Touch"]}),s.jsxs(de,{size:"sm",variant:"outline",className:"gap-1.5 border-emerald-200 text-emerald-700 hover:bg-emerald-50 hover:text-emerald-800",onClick:K=>{K.stopPropagation(),t("/innercircle/video/record")},children:[s.jsx(Ia,{className:"h-3.5 w-3.5"}),"Quick Video"]}),s.jsxs(de,{size:"sm",variant:"outline",className:"gap-1.5",onClick:K=>{K.stopPropagation(),t("/innercircle/popbys")},children:[s.jsx(wp,{className:"h-3.5 w-3.5"}),"Pop-by Map"]})]}),s.jsxs("div",{className:"pt-3 border-t border-border/50",children:[s.jsxs("div",{className:"flex items-center justify-between mb-2",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(rD,{className:"h-4 w-4 text-primary"}),s.jsx("span",{className:"text-sm font-medium",children:"Weekly Goal"}),s.jsxs(mn,{open:g,onOpenChange:_,children:[s.jsx(Do,{asChild:!0,children:s.jsx("button",{onClick:N,className:"p-0.5 rounded hover:bg-muted transition-colors","aria-label":"Edit weekly goal",children:s.jsx(eg,{className:"h-3.5 w-3.5 text-muted-foreground hover:text-primary"})})}),s.jsxs(pn,{className:"sm:max-w-[360px]",children:[s.jsxs(xn,{children:[s.jsx(gn,{children:"Set Weekly Goal"}),s.jsx(fi,{children:"How many touches do you want to complete each week?"})]}),s.jsxs("div",{className:"space-y-4 pt-2",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"weekly-goal",children:"Weekly touch goal"}),s.jsx(Et,{id:"weekly-goal",type:"number",min:"1",value:a,onChange:K=>m(K.target.value),placeholder:"20",onKeyDown:K=>{K.key==="Enter"&&j()}})]}),s.jsx(de,{onClick:j,className:"w-full",children:"Save Goal"})]})]})]})]}),s.jsxs("span",{className:"text-sm",children:[s.jsx("span",{className:"font-medium text-primary",children:W}),s.jsxs("span",{className:"text-muted-foreground",children:[" / ",o," touches"]})]})]}),s.jsx(vc,{value:Math.min(W/o*100,100),className:"h-2 bg-muted [&>div]:bg-primary"}),W>=o&&s.jsxs("p",{className:"text-xs text-emerald-600 mt-1.5 flex items-center gap-1",children:[s.jsx("span",{children:"🎉"})," Goal achieved! Keep the momentum going."]}),W0&&s.jsxs("p",{className:"text-xs text-muted-foreground mt-1.5",children:[o-W," more to hit your weekly goal"]})]}),I.length>0&&s.jsxs("div",{className:"pt-3 border-t border-border/50",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[s.jsx(uM,{className:"h-4 w-4 text-pink-500"}),s.jsx("span",{className:"text-sm font-medium",children:"Upcoming Milestones"})]}),s.jsx("div",{className:"space-y-2",children:I.map((K,Q)=>s.jsxs("div",{className:`flex items-center justify-between p-2 rounded-lg cursor-pointer transition-colors ${K.isToday?"bg-pink-500/10 hover:bg-pink-500/15":"bg-muted/50 hover:bg-muted"}`,onClick:te=>{te.stopPropagation(),t(`/innercircle/contacts/${K.contact.id}`)},children:[s.jsxs("div",{className:"flex items-center gap-2",children:[K.type==="birthday"?s.jsx(uM,{className:"h-3.5 w-3.5 text-pink-500"}):s.jsx(ou,{className:"h-3.5 w-3.5 text-blue-500"}),s.jsxs("span",{className:"text-sm",children:[K.contact.first_name," ",K.contact.last_name]}),K.isToday&&s.jsx(ir,{variant:"secondary",className:"text-[10px] px-1.5 py-0 bg-pink-500/20 text-pink-600",children:"Today!"})]}),s.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[s.jsx("span",{children:K.isToday?K.type==="birthday"?"🎂":"🏠":Vn(K.date,"EEE, MMM d")}),s.jsx(wd,{className:"h-3 w-3"})]})]},`${K.contact.id}-${K.type}-${Q}`))})]}),s.jsxs(de,{variant:"ghost",size:"sm",className:"w-full gap-1 text-muted-foreground hover:text-primary",onClick:()=>t("/innercircle"),children:["Open Agent OS",s.jsx(cd,{className:"h-4 w-4"})]})]})]})}const hpe=()=>Sr({queryKey:["listing-exchange-enabled"],queryFn:async()=>{const{data:t,error:e}=await ae.from("feature_flags").select("enabled").eq("key","listing_exchange_enabled").maybeSingle();if(e)throw e;return(t==null?void 0:t.enabled)??!1}}),fpe=t=>Sr({queryKey:["listings",t],queryFn:async()=>{let e=ae.from("listings").select(` *, photos:listing_photos(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id, brokerage:brokerages(name)) `).eq("is_approved",!0).eq("is_public",!0);switch(t!=null&&t.status&&(e=e.eq("status",t.status)),t!=null&&t.propertyType&&(e=e.eq("property_type",t.propertyType)),t!=null&&t.city&&(e=e.ilike("city",`%${t.city}%`)),t!=null&&t.minPrice&&(e=e.gte("price",t.minPrice)),t!=null&&t.maxPrice&&(e=e.lte("price",t.maxPrice)),t!=null&&t.openToReferrals&&(e=e.eq("open_to_referrals",!0)),t==null?void 0:t.sortBy){case"updated":e=e.order("updated_at",{ascending:!1});break;case"price_asc":e=e.order("price",{ascending:!0});break;case"price_desc":e=e.order("price",{ascending:!1});break;default:e=e.order("created_at",{ascending:!1})}const{data:r,error:n}=await e;if(n)throw n;return r}}),jBe=()=>{const{user:t}=rn();return Sr({queryKey:["my-listings",t==null?void 0:t.id],queryFn:async()=>{if(!t)return[];const{data:e,error:r}=await ae.from("listings").select(` *, photos:listing_photos(*) `).eq("agent_id",t.id).order("created_at",{ascending:!1});if(r)throw r;return e},enabled:!!t})},ppe=t=>{const{user:e}=rn();return Sr({queryKey:["listing",t],queryFn:async()=>{const{data:r,error:n}=await ae.from("listings").select(` *, photos:listing_photos(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id, brokerage:brokerages(name)) `).eq("id",t).single();if(n)throw n;return e&&await ae.from("listing_views").insert({listing_id:t,viewer_id:e.id}),r},enabled:!!t})},SBe=()=>{const t=Wn(),{user:e}=rn();return zr({mutationFn:async r=>{if(!e)throw new Error("Not authenticated");const{data:n,error:i}=await ae.from("listings").insert({...r,agent_id:e.id}).select().single();if(i)throw i;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["listings"]}),t.invalidateQueries({queryKey:["my-listings"]})}})},NBe=()=>{const t=Wn();return zr({mutationFn:async({id:e,...r})=>{const{data:n,error:i}=await ae.from("listings").update(r).eq("id",e).select().single();if(i)throw i;return n},onSuccess:e=>{t.invalidateQueries({queryKey:["listings"]}),t.invalidateQueries({queryKey:["my-listings"]}),t.invalidateQueries({queryKey:["listing",e.id]})}})},CBe=()=>{const t=Wn();return zr({mutationFn:async e=>{const{error:r}=await ae.from("listings").delete().eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["listings"]}),t.invalidateQueries({queryKey:["my-listings"]})}})},kBe=()=>{const t=Wn();return zr({mutationFn:async({listingId:e,photoUrl:r,isPrimary:n=!1})=>{const{data:i,error:o}=await ae.from("listing_photos").insert({listing_id:e,photo_url:r,is_primary:n}).select().single();if(o)throw o;return i},onSuccess:e=>{t.invalidateQueries({queryKey:["listing",e.listing_id]}),t.invalidateQueries({queryKey:["my-listings"]})}})},TBe=()=>{const t=Wn();return zr({mutationFn:async({photoId:e,listingId:r})=>{const{error:n}=await ae.from("listing_photos").delete().eq("id",e);if(n)throw n;return r},onSuccess:e=>{t.invalidateQueries({queryKey:["listing",e]}),t.invalidateQueries({queryKey:["my-listings"]})}})},EBe=()=>{const{user:t}=rn();return Sr({queryKey:["saved-listings",t==null?void 0:t.id],queryFn:async()=>{if(!t)return[];const{data:e,error:r}=await ae.from("listing_saves").select(` *, listing:listings( *, photos:listing_photos(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id) ) `).eq("agent_id",t.id);if(r)throw r;return e},enabled:!!t})},mpe=()=>{const t=Wn(),{user:e}=rn();return zr({mutationFn:async r=>{if(!e)throw new Error("Not authenticated");const{data:n}=await ae.from("listing_saves").select("id").eq("listing_id",r).eq("agent_id",e.id).maybeSingle();return n?(await ae.from("listing_saves").delete().eq("id",n.id),{saved:!1}):(await ae.from("listing_saves").insert({listing_id:r,agent_id:e.id}),{saved:!0})},onSuccess:()=>{t.invalidateQueries({queryKey:["saved-listings"]}),t.invalidateQueries({queryKey:["listings"]})}})},gpe=t=>{const{user:e}=rn();return Sr({queryKey:["listing-saved",t,e==null?void 0:e.id],queryFn:async()=>{if(!e)return!1;const{data:r}=await ae.from("listing_saves").select("id").eq("listing_id",t).eq("agent_id",e.id).maybeSingle();return!!r},enabled:!!e&&!!t})},ABe=()=>{const t=Wn(),{user:e}=rn();return zr({mutationFn:async r=>{if(!e)throw new Error("Not authenticated");const{data:n}=await ae.from("listing_follows").select("id").eq("listing_id",r).eq("agent_id",e.id).maybeSingle();return n?(await ae.from("listing_follows").delete().eq("id",n.id),{following:!1}):(await ae.from("listing_follows").insert({listing_id:r,agent_id:e.id}),{following:!0})},onSuccess:()=>{t.invalidateQueries({queryKey:["listing-following"]})}})},PBe=t=>{const{user:e}=rn();return Sr({queryKey:["listing-following",t,e==null?void 0:e.id],queryFn:async()=>{if(!e)return!1;const{data:r}=await ae.from("listing_follows").select("id").eq("listing_id",t).eq("agent_id",e.id).maybeSingle();return!!r},enabled:!!e&&!!t})},ype=()=>{const{user:t}=rn();return zr({mutationFn:async({listingId:e,shareType:r})=>{if(!t)throw new Error("Not authenticated");const{error:n}=await ae.from("listing_shares").insert({listing_id:e,agent_id:t.id,share_type:r});if(n)throw n}})},IBe=()=>{const{user:t}=rn();return Sr({queryKey:["my-referrals",t==null?void 0:t.id],queryFn:async()=>{if(!t)return{sent:[],received:[]};const[e,r]=await Promise.all([ae.from("listing_referrals").select(` *, listing:listings(*,photos:listing_photos(*)) `).eq("sender_agent_id",t.id).order("created_at",{ascending:!1}),ae.from("listing_referrals").select(` *, sender:profiles!listing_referrals_sender_agent_id_fkey(id, name, email), listing:listings(*,photos:listing_photos(*)) `).eq("listing_agent_id",t.id).order("created_at",{ascending:!1})]);return{sent:e.data||[],received:r.data||[]}},enabled:!!t})},MBe=()=>{const t=Wn(),{user:e}=rn();return zr({mutationFn:async({listingId:r,listingAgentId:n,buyerName:i,buyerType:o,notes:c})=>{if(!e)throw new Error("Not authenticated");const{data:a,error:m}=await ae.from("listing_referrals").insert({listing_id:r,sender_agent_id:e.id,listing_agent_id:n,buyer_name:i,buyer_type:o,notes:c}).select().single();if(m)throw m;return a},onSuccess:()=>{t.invalidateQueries({queryKey:["my-referrals"]})}})},OBe=()=>Sr({queryKey:["listing-leaderboard"],queryFn:async()=>{const{data:t}=await ae.from("listing_shares").select("agent_id, profiles!listing_shares_agent_id_fkey(name)").order("created_at",{ascending:!1}),e=new Map;t==null||t.forEach(c=>{var m;const a=e.get(c.agent_id);a?a.count++:e.set(c.agent_id,{name:((m=c.profiles)==null?void 0:m.name)||"Unknown",count:1})});const r=Array.from(e.entries()).map(([c,a])=>({agentId:c,...a})).sort((c,a)=>a.count-c.count).slice(0,10),{data:n}=await ae.from("listings").select("agent_id, agent:profiles!listings_agent_id_fkey(name)").eq("is_approved",!0),i=new Map;n==null||n.forEach(c=>{var m;const a=i.get(c.agent_id);a?a.count++:i.set(c.agent_id,{name:((m=c.agent)==null?void 0:m.name)||"Unknown",count:1})});const o=Array.from(i.entries()).map(([c,a])=>({agentId:c,...a})).sort((c,a)=>a.count-c.count).slice(0,10);return{topSharers:r,topListers:o}}}),RBe=({className:t,variant:e="default"})=>s.jsx(ir,{variant:"outline",className:ar("text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0 h-4",e==="default"?"border-amber-500 text-amber-600 dark:text-amber-400 bg-amber-500/10":"border-muted-foreground/30 text-muted-foreground",t),children:"Beta"}),DBe={coming_soon:"bg-amber-500/10 text-amber-600 border-amber-200",active:"bg-emerald-500/10 text-emerald-600 border-emerald-200",under_contract:"bg-blue-500/10 text-blue-600 border-blue-200",sold:"bg-purple-500/10 text-purple-600 border-purple-200",withdrawn:"bg-muted text-muted-foreground border-border"},LBe={coming_soon:"Coming Soon",active:"Active",under_contract:"Under Contract",sold:"Sold",withdrawn:"Withdrawn"};function FBe(t){return t>=1e6?`$${(t/1e6).toFixed(1)}M`:`$${(t/1e3).toFixed(0)}K`}function zBe(){const t=Bs(),{data:e,isLoading:r}=hpe(),{data:n,isLoading:i}=fpe({status:void 0,propertyType:void 0,sortBy:"newest"}),o=(n==null?void 0:n.filter(_=>_.is_approved&&_.is_public))||[],c=o.filter(_=>_.is_featured),a=o.filter(_=>!_.is_featured),m=[...c,...a].slice(0,6),g=r||i;return!g&&!e?null:g?s.jsx(at,{className:"bg-gradient-to-br from-emerald-500/5 via-emerald-500/10 to-emerald-500/5 border-emerald-500/20",children:s.jsx(ct,{className:"p-4",children:s.jsxs("div",{className:"animate-pulse flex items-center gap-4",children:[s.jsx("div",{className:"h-12 w-12 bg-emerald-500/20 rounded-lg"}),s.jsxs("div",{className:"flex-1 space-y-2",children:[s.jsx("div",{className:"h-4 bg-emerald-500/20 rounded w-1/3"}),s.jsx("div",{className:"h-3 bg-emerald-500/10 rounded w-1/2"})]})]})})}):s.jsxs("section",{className:"mb-10",children:[s.jsxs("div",{className:"flex items-center justify-between mb-4",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Listing Exchange"}),s.jsx(RBe,{})]}),s.jsxs(de,{variant:"ghost",size:"sm",onClick:()=>t("/innercircle/listings"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",s.jsx(cd,{className:"h-4 w-4"})]})]}),m.length===0?s.jsx(at,{className:"bg-muted/30 border-dashed",children:s.jsx(ct,{className:"flex items-center justify-center py-8",children:s.jsxs("div",{className:"text-center",children:[s.jsx(ou,{className:"h-8 w-8 text-muted-foreground/50 mx-auto mb-2"}),s.jsx("p",{className:"text-sm text-muted-foreground",children:"No listings available yet"}),s.jsx(de,{variant:"link",size:"sm",onClick:()=>t("/innercircle/listings/new"),className:"mt-2",children:"Add the first listing"})]})})}):s.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3",children:m.map(_=>{var N,C;const j=((N=_.photos)==null?void 0:N.find(P=>P.is_primary))||((C=_.photos)==null?void 0:C[0]);return s.jsxs("div",{onClick:()=>t(`/innercircle/listings/${_.id}`),className:"group cursor-pointer bg-card rounded-xl border border-border overflow-hidden transition-all duration-200 hover:shadow-lg hover:border-primary/30",children:[s.jsxs("div",{className:"aspect-[4/3] bg-muted/50 overflow-hidden relative",children:[j!=null&&j.photo_url?s.jsx("img",{src:j.photo_url,alt:`${_.city}, ${_.state}`,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):s.jsx("div",{className:"w-full h-full flex items-center justify-center",children:s.jsx(ou,{className:"h-8 w-8 text-muted-foreground/50"})}),_.is_featured&&s.jsx("div",{className:"absolute top-1.5 left-1.5",children:s.jsxs(ir,{className:"gap-1 bg-amber-500 text-white border-0 text-[10px] px-1.5 py-0.5",children:[s.jsx(mh,{className:"h-2.5 w-2.5 fill-current"}),"Featured"]})}),s.jsx("div",{className:"absolute top-1.5 right-1.5",children:s.jsx(ir,{className:`text-[10px] px-1.5 py-0.5 ${DBe[_.status]}`,children:LBe[_.status]})})]}),s.jsxs("div",{className:"p-2",children:[s.jsx("p",{className:"font-bold text-sm text-foreground",children:FBe(_.price)}),s.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[_.city,", ",_.state]}),(_.bedrooms||_.bathrooms)&&s.jsxs("p",{className:"text-[10px] text-muted-foreground mt-0.5",children:[_.bedrooms&&`${_.bedrooms} bed`,_.bedrooms&&_.bathrooms&&" · ",_.bathrooms&&`${_.bathrooms} bath`]})]})]},_.id)})})]})}function Dn({className:t,...e}){return s.jsx("div",{className:ar("animate-pulse rounded-md bg-muted",t),...e})}const kq=()=>Sr({queryKey:["lead-sources"],queryFn:async()=>{const{data:t,error:e}=await ae.from("lead_sources").select("*").eq("is_active",!0).order("sort_order");if(e)throw e;return t}}),BBe=()=>{const t=Wn(),{user:e}=rn();return zr({mutationFn:async r=>{const{data:n,error:i}=await ae.from("lead_sources").insert({name:r,owner_user_id:e==null?void 0:e.id,sort_order:100}).select().single();if(i)throw i;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["lead-sources"]}),Dt.success("Lead source added")},onError:r=>{Dt.error("Failed to add lead source"),console.error(r)}})},Tq=(t,e)=>{const{user:r,isAdmin:n}=rn(),i=n&&e?e:r==null?void 0:r.id;return Sr({queryKey:["scorecard-transactions",t,i],queryFn:async()=>{let o=ae.from("scorecard_transactions").select(` *, lead_source:lead_sources(id, name), client_type:relationship_types(id, name), contact:innercircle_contacts(id, first_name, last_name) `).eq("owner_user_id",i).order("close_date",{ascending:!1});t&&(o=o.gte("close_date",`${t}-01-01`).lte("close_date",`${t}-12-31`));const{data:c,error:a}=await o;if(a)throw a;return c},enabled:!!i})},xpe=t=>{const{user:e,isAdmin:r}=rn(),n=r&&t?t:e==null?void 0:e.id;return Sr({queryKey:["scorecard-transactions-all",n],queryFn:async()=>{const{data:i,error:o}=await ae.from("scorecard_transactions").select(` *, lead_source:lead_sources(id, name), client_type:relationship_types(id, name), contact:innercircle_contacts(id, first_name, last_name) `).eq("owner_user_id",n).order("close_date",{ascending:!1});if(o)throw o;return i},enabled:!!n})},Eq=()=>{const t=Wn(),{user:e}=rn();return zr({mutationFn:async r=>{const{data:n,error:i}=await ae.from("scorecard_transactions").insert({...r,owner_user_id:e.id}).select().single();if(i)throw i;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["scorecard-transactions"]}),t.invalidateQueries({queryKey:["scorecard-transactions-all"]}),Dt.success("Transaction added")},onError:r=>{Dt.error("Failed to add transaction"),console.error(r)}})},$Be=()=>{const t=Wn();return zr({mutationFn:async({id:e,...r})=>{const{data:n,error:i}=await ae.from("scorecard_transactions").update(r).eq("id",e).select().single();if(i)throw i;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["scorecard-transactions"]}),t.invalidateQueries({queryKey:["scorecard-transactions-all"]}),Dt.success("Transaction updated")},onError:e=>{Dt.error("Failed to update transaction"),console.error(e)}})},UBe=()=>{const t=Wn();return zr({mutationFn:async e=>{const{error:r}=await ae.from("scorecard_transactions").delete().eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["scorecard-transactions"]}),t.invalidateQueries({queryKey:["scorecard-transactions-all"]}),Dt.success("Transaction deleted")},onError:e=>{Dt.error("Failed to delete transaction"),console.error(e)}})},vpe=(t,e)=>{const{user:r,isAdmin:n}=rn(),i=n&&e?e:r==null?void 0:r.id;return Sr({queryKey:["scorecard-goals",t,i],queryFn:async()=>{const{data:o,error:c}=await ae.from("scorecard_goals").select("*").eq("owner_user_id",i).eq("year",t).maybeSingle();if(c)throw c;return o},enabled:!!i})},VBe=()=>{const t=Wn(),{user:e}=rn();return zr({mutationFn:async r=>{const{data:n,error:i}=await ae.from("scorecard_goals").upsert({...r,owner_user_id:e.id},{onConflict:"owner_user_id,year"}).select().single();if(i)throw i;return n},onSuccess:(r,n)=>{t.invalidateQueries({queryKey:["scorecard-goals",n.year]}),Dt.success("Goals saved")},onError:r=>{Dt.error("Failed to save goals"),console.error(r)}})},BD=()=>{const{user:t}=rn();return Sr({queryKey:["scorecard-settings",t==null?void 0:t.id],queryFn:async()=>{const{data:e,error:r}=await ae.from("scorecard_settings").select("*").eq("user_id",t.id).maybeSingle();if(r)throw r;return e},enabled:!!(t!=null&&t.id)})},qBe=()=>{const t=Wn(),{user:e}=rn();return zr({mutationFn:async r=>{const{data:n,error:i}=await ae.from("scorecard_settings").upsert({...r,user_id:e.id},{onConflict:"user_id"}).select().single();if(i)throw i;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["scorecard-settings"]}),Dt.success("Settings saved")},onError:r=>{Dt.error("Failed to save settings"),console.error(r)}})},_pe=(t,e)=>{const{data:r,isLoading:n}=Tq(t,e),{data:i,isLoading:o}=xpe(e),{data:c}=BD(),a=(c==null?void 0:c.show_commission)??!0,m=g=>{if(!g||g.length===0)return{totalTransactions:0,buyerCount:0,sellerCount:0,totalVolume:0,averagePrice:0,totalCommission:0,topLeadSource:null,transactionsByMonth:[],leadSourceBreakdown:[]};const _=g.filter(W=>W.transaction_type==="buyer").length,j=g.filter(W=>W.transaction_type==="seller").length,N=g.reduce((W,V)=>W+Number(V.sale_price),0),C=g.reduce((W,V)=>W+(Number(V.commission_amount)||0),0),P={};g.forEach(W=>{var K;const V=((K=W.lead_source)==null?void 0:K.name)||"Unknown";P[V]=(P[V]||0)+1});const A=Object.entries(P).map(([W,V])=>({name:W,count:V})).sort((W,V)=>V.count-W.count),I=A[0]||null,O={};g.forEach(W=>{const V=new Date(W.close_date).toLocaleString("default",{month:"short"});O[V]=(O[V]||0)+1});const z=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"].map(W=>({month:W,count:O[W]||0}));return{totalTransactions:g.length,buyerCount:_,sellerCount:j,totalVolume:N,averagePrice:g.length>0?N/g.length:0,totalCommission:a?C:0,topLeadSource:I,transactionsByMonth:z,leadSourceBreakdown:A}};return{yearStats:m(r),lifetimeStats:m(i),isLoading:n||o,showCommission:a}},HBe=()=>{const{isAdmin:t}=rn();return Sr({queryKey:["agents-with-transactions"],queryFn:async()=>{const{data:e,error:r}=await ae.from("scorecard_transactions").select("owner_user_id").order("owner_user_id");if(r)throw r;const n=[...new Set(e.map(c=>c.owner_user_id))],{data:i,error:o}=await ae.from("profiles").select("id, name, email").in("id",n);if(o)throw o;return i},enabled:t})},iy={recency:40,touchpoints:30,transactions:20},cQ={warm:70,cooling:40};function WBe(t){return t===null?0:t<=14?iy.recency:t<=30?iy.recency*.85:t<=60?iy.recency*.65:t<=90?iy.recency*.4:t<=180?iy.recency*.2:iy.recency*.05}function GBe(t){const e=Math.min(t/12,1);return Math.round(iy.touchpoints*e)}function KBe(t){return t?iy.transactions:0}function ZBe(){return 0}function YBe(t){return t>=cQ.warm?"warm":t>=cQ.cooling?"cooling":"at-risk"}function bpe(){const{data:t,isLoading:e}=ig(),{data:r}=ape(),{data:n}=zD(365),{data:i}=xpe(),o=D.useMemo(()=>{if(!t)return[];const a=new Date,m=BFe(a),g={};n==null||n.forEach(j=>{new Date(j.completed_at)>=m&&(g[j.contact_id]=(g[j.contact_id]||0)+1)});const _=new Set((i==null?void 0:i.filter(j=>j.contact_id).map(j=>j.contact_id))||[]);return t.map(j=>{const N=(r==null?void 0:r[j.id])||null,C=N?Qhe(a,new Date(N)):null,P=g[j.id]||0,A=_.has(j.id),I=WBe(C),O=GBe(P),R=KBe(A),z=ZBe(),W=Math.round(I+O+R+z),V={score:W,status:YBe(W),breakdown:{recency:Math.round(I),touchpoints:Math.round(O),transactions:Math.round(R),referrals:Math.round(z)},lastTouchDate:N,daysSinceTouch:C,touchCountLast12Months:P,hasTransaction:A};return{...j,relationshipScore:V}})},[t,r,n,i]),c=D.useMemo(()=>{const a=o.filter(N=>N.relationshipScore.status==="warm").length,m=o.filter(N=>N.relationshipScore.status==="cooling").length,g=o.filter(N=>N.relationshipScore.status==="at-risk").length,_=o.length,j=_>0?Math.round(o.reduce((N,C)=>N+C.relationshipScore.score,0)/_):0;return{warm:a,cooling:m,atRisk:g,total:_,averageScore:j}},[o]);return{contactsWithScores:o,stats:c,isLoading:e}}function wpe(){const t=Bs(),{stats:e,contactsWithScores:r,isLoading:n}=bpe();if(n)return s.jsxs(at,{children:[s.jsx(xr,{className:"pb-2",children:s.jsx(Dn,{className:"h-5 w-40"})}),s.jsxs(ct,{className:"space-y-4",children:[s.jsx(Dn,{className:"h-20 w-full"}),s.jsx(Dn,{className:"h-16 w-full"})]})]});if(e.total===0)return s.jsxs(at,{children:[s.jsx(xr,{className:"pb-2",children:s.jsxs(wr,{className:"text-lg flex items-center gap-2",children:[s.jsx(_i,{className:"h-5 w-5"}),"Relationship Health"]})}),s.jsxs(ct,{children:[s.jsx("p",{className:"text-sm text-muted-foreground",children:"Add contacts to see your relationship health scores."}),s.jsx(de,{variant:"outline",size:"sm",className:"mt-3",onClick:()=>t("/innercircle/contacts?new=true"),children:"Add Your First Contact"})]})]});const i=Math.round(e.warm/e.total*100),o=Math.round(e.cooling/e.total*100),c=Math.round(e.atRisk/e.total*100),a=r.filter(m=>m.relationshipScore.status==="at-risk").sort((m,g)=>m.relationshipScore.score-g.relationshipScore.score).slice(0,3);return s.jsxs(at,{children:[s.jsxs(xr,{className:"pb-2",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs(wr,{className:"text-lg flex items-center gap-2",children:[s.jsx(r0,{className:"h-5 w-5 text-emerald-500"}),"Relationship Health"]}),s.jsx("span",{className:"text-2xl font-bold",children:e.averageScore})]}),s.jsxs("p",{className:"text-xs text-muted-foreground",children:["Average score across ",e.total," contacts"]})]}),s.jsxs(ct,{className:"space-y-4",children:[s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"flex items-center justify-between text-sm",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-emerald-500"}),s.jsx("span",{children:"Warm"})]}),s.jsxs("span",{className:"font-medium",children:[e.warm," (",i,"%)"]})]}),s.jsx(vc,{value:i,className:"h-2 bg-muted [&>div]:bg-emerald-500"})]}),s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"flex items-center justify-between text-sm",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-amber-500"}),s.jsx("span",{children:"Cooling Off"})]}),s.jsxs("span",{className:"font-medium",children:[e.cooling," (",o,"%)"]})]}),s.jsx(vc,{value:o,className:"h-2 bg-muted [&>div]:bg-amber-500"})]}),s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"flex items-center justify-between text-sm",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-red-500"}),s.jsx("span",{children:"At Risk"})]}),s.jsxs("span",{className:"font-medium",children:[e.atRisk," (",c,"%)"]})]}),s.jsx(vc,{value:c,className:"h-2 bg-muted [&>div]:bg-red-500"})]})]}),a.length>0&&s.jsxs("div",{className:"pt-3 border-t",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[s.jsx(Soe,{className:"h-4 w-4 text-red-500"}),s.jsx("span",{className:"text-sm font-medium",children:"Needs Attention"})]}),s.jsx("div",{className:"space-y-2",children:a.map(m=>s.jsxs("div",{className:"flex items-center justify-between p-2 rounded-lg bg-red-500/5 hover:bg-red-500/10 cursor-pointer transition-colors",onClick:()=>t(`/innercircle/contacts/${m.id}`),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"h-2 w-2 rounded-full bg-red-500"}),s.jsxs("span",{className:"text-sm",children:[m.first_name," ",m.last_name]})]}),s.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[s.jsx("span",{children:m.relationshipScore.daysSinceTouch===null?"Never":`${m.relationshipScore.daysSinceTouch}d`}),s.jsx(wd,{className:"h-3 w-3"})]})]},m.id))})]}),s.jsxs(de,{variant:"outline",size:"sm",className:"w-full",onClick:()=>t("/innercircle/contacts?filter=at-risk"),children:["View All At-Risk Contacts",s.jsx(wd,{className:"h-4 w-4 ml-1"})]})]})]})}const XBe=()=>{var pe,ve;const{user:t}=rn(),e=Bs(),[r,n]=D.useState([]),[i,o]=D.useState([]),[c,a]=D.useState([]),[m,g]=D.useState([]),[_,j]=D.useState([]),[N,C]=D.useState([]),[P,A]=D.useState(new Set),[I,O]=D.useState([]),[R,z]=D.useState([]),[W,V]=D.useState([]),[K,Q]=D.useState(!0);D.useEffect(()=>{te()},[t]);const te=async()=>{try{const{data:ge}=await ae.from("user_tags").select("tag").eq("user_id",t==null?void 0:t.id),ke=(ge==null?void 0:ge.map(Be=>Be.tag))||[],{data:Ce}=await ae.from("app_tiles").select("*").order("name"),{data:Se}=await ae.from("user_favorites").select("app_id").eq("user_id",t==null?void 0:t.id),je=new Set((Se==null?void 0:Se.map(Be=>Be.app_id))||[]);A(je);const bt=((Ce==null?void 0:Ce.filter(Be=>!Be.required_tags||Be.required_tags.length===0?!0:Be.required_tags.some(Pe=>ke.includes(Pe))))||[]).sort((Be,Pe)=>Be.name==="LevelUp Members Portal"?-1:Pe.name==="LevelUp Members Portal"?1:0);n(bt.slice(0,6));const{data:_e}=await ae.from("events").select("*").order("event_date",{ascending:!0}),Ye=(_e==null?void 0:_e.filter(Be=>!VM(new Date(Be.event_date))))||[];o(Ye.slice(0,4));const{data:pt}=await ae.from("event_registrations").select("event_id, zoom_join_url").eq("user_id",t==null?void 0:t.id);O(pt||[]);const{data:nt}=await ae.from("canva_templates").select("id, name, preview_image_url, publish_date").order("publish_date",{ascending:!1}).limit(4);a(nt||[]);const{data:Qt}=await ae.from("resource_kits").select("id, name, description, featured_image_url, publish_date").eq("is_published",!0).order("publish_date",{ascending:!1}).limit(4);g(Qt||[]);const{data:gt}=await ae.from("academy_videos").select("id, title, description, thumbnail_url, duration, publish_date").eq("is_published",!0).order("publish_date",{ascending:!1}).limit(4);j(gt||[]);const{data:Me}=await ae.from("additional_services").select("id, name, description, preview_image_url, signup_link_url, publish_date").eq("is_published",!0).order("publish_date",{ascending:!1}).limit(4);C(Me||[]);const{data:Oe}=await ae.from("dashboard_banners").select("id, title, description, image_url, link_url, link_text, placement, section_after").eq("is_active",!0).order("sort_order"),Ie=Oe||[];z(Ie.filter(Be=>Be.placement==="top")),V(Ie.filter(Be=>Be.placement==="between"))}catch(ge){console.error("Error loading dashboard:",ge),Dt.error("Failed to load dashboard data")}finally{Q(!1)}},X=async ge=>{var Ce;const ke=window.open("about:blank","_blank");try{await ae.from("activity_logs").insert({user_id:t==null?void 0:t.id,app_id:ge.app_id,app_name:ge.name,user_agent:navigator.userAgent});const{data:Se,error:je}=await ae.functions.invoke("sso-launch",{body:{app_id:ge.app_id}});if(je)throw je;Se!=null&&Se.redirect_url?ke&&!ke.closed?(ke.location.href=Se.redirect_url,(Ce=ke.focus)==null||Ce.call(ke)):window.location.assign(Se.redirect_url):(ke==null||ke.close(),Dt.error("Launch link unavailable"))}catch(Se){ke==null||ke.close(),console.error("Error launching app:",Se),Dt.error("Failed to launch app")}},ie=ge=>I==null?void 0:I.some(ke=>ke.event_id===ge),he=ge=>{const ke=I==null?void 0:I.find(Ce=>Ce.event_id===ge);return ke==null?void 0:ke.zoom_join_url};if(K)return s.jsx(Jr,{title:"Dashboard",children:s.jsx("div",{className:"flex items-center justify-center py-16",children:s.jsxs("div",{className:"text-center",children:[s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent mx-auto mb-4"}),s.jsx("p",{className:"text-muted-foreground",children:"Loading your dashboard..."})]})})});const xe=ge=>W.filter(ke=>ke.section_after===ge);return s.jsxs(Jr,{title:"Dashboard",children:[s.jsx(Qze,{events:i,registrations:I,onNavigateToEvents:()=>e("/events")}),R.length>0&&s.jsx("div",{className:"mb-8",children:s.jsx(xC,{banners:R})}),s.jsx(lBe,{}),s.jsxs("div",{className:"mb-6",children:[s.jsxs("h2",{className:"text-2xl font-bold text-foreground",children:["Welcome back, ",((ve=(pe=t==null?void 0:t.user_metadata)==null?void 0:pe.name)==null?void 0:ve.split(" ")[0])||"there","!"]}),s.jsx("p",{className:"text-muted-foreground mt-1",children:"Are you ready to LevelUp today?"})]}),s.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4 mb-8",children:[s.jsx(wBe,{}),s.jsx(wpe,{})]}),s.jsxs("section",{className:"mb-10",children:[s.jsxs("div",{className:"flex items-center justify-between mb-4",children:[s.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Upcoming Events"}),s.jsxs(de,{variant:"ghost",size:"sm",onClick:()=>e("/events"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",s.jsx(cd,{className:"h-4 w-4"})]})]}),i.length===0?s.jsx(at,{className:"bg-muted/30 border-dashed",children:s.jsx(ct,{className:"flex items-center justify-center py-8",children:s.jsxs("div",{className:"text-center",children:[s.jsx(ko,{className:"h-8 w-8 text-muted-foreground/50 mx-auto mb-2"}),s.jsx("p",{className:"text-sm text-muted-foreground",children:"No upcoming events"})]})})}):s.jsx("div",{className:"bg-card rounded-xl border border-border overflow-hidden divide-y divide-border max-w-full",children:i.map(ge=>{const ke=ie(ge.id),Ce=he(ge.id)||ge.zoom_link;return s.jsxs("div",{className:`flex items-start gap-3 sm:gap-4 p-3 sm:p-4 hover:bg-muted/50 transition-colors cursor-pointer group ${R$(ge.event_date)?"bg-red-500/5 border-l-2 border-l-red-500":""}`,onClick:()=>e("/events"),children:[R$(ge.event_date)?s.jsxs("div",{className:"flex-shrink-0 w-12 h-12 sm:w-14 sm:h-14 rounded-lg bg-red-500/10 flex flex-col items-center justify-center relative",children:[s.jsx("span",{className:"absolute inline-flex h-3 w-3 top-1 right-1 animate-ping rounded-full bg-red-500 opacity-75"}),s.jsx(Y6,{className:"h-5 w-5 text-red-500"}),s.jsx("span",{className:"text-[10px] font-bold text-red-500 uppercase mt-0.5",children:"Live"})]}):s.jsxs("div",{className:"flex-shrink-0 w-12 h-12 sm:w-14 sm:h-14 rounded-lg bg-primary/10 flex flex-col items-center justify-center",children:[s.jsx("span",{className:"text-[10px] sm:text-xs font-medium text-primary uppercase",children:Vn(new Date(ge.event_date),"MMM")}),s.jsx("span",{className:"text-lg sm:text-xl font-bold text-primary",children:Vn(new Date(ge.event_date),"d")})]}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("h4",{className:"font-medium text-sm sm:text-base text-foreground group-hover:text-primary transition-colors line-clamp-2 sm:truncate",children:ge.title}),s.jsxs("p",{className:"text-xs sm:text-sm text-muted-foreground mt-0.5",children:[Vn(new Date(ge.event_date),"EEEE")," at ",Vn(new Date(ge.event_date),"h:mm a")]})]}),s.jsx("div",{className:"hidden sm:flex flex-shrink-0",children:ke?s.jsxs(de,{size:"sm",variant:"default",className:"gap-1",onClick:Se=>{Se.stopPropagation(),window.open(Ce,"_blank")},children:[s.jsx(oa,{className:"h-3.5 w-3.5"}),"Join"]}):s.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground group-hover:text-primary transition-colors",children:[s.jsx("span",{className:"text-sm",children:"Register"}),s.jsx(wd,{className:"h-4 w-4"})]})})]},ge.id)})})]}),xe("events").length>0&&s.jsx("div",{className:"mb-10",children:s.jsx(xC,{banners:xe("events")})}),s.jsxs("section",{className:"mb-10",children:[s.jsxs("div",{className:"flex items-center justify-between mb-4",children:[s.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Academy Videos"}),s.jsxs(de,{variant:"ghost",size:"sm",onClick:()=>e("/academy"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",s.jsx(cd,{className:"h-4 w-4"})]})]}),_.length===0?s.jsx(at,{className:"bg-muted/30 border-dashed",children:s.jsx(ct,{className:"flex items-center justify-center py-8",children:s.jsxs("div",{className:"text-center",children:[s.jsx(dM,{className:"h-8 w-8 text-muted-foreground/50 mx-auto mb-2"}),s.jsx("p",{className:"text-sm text-muted-foreground",children:"No academy videos available"})]})})}):s.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:_.map(ge=>s.jsxs("div",{onClick:()=>e(`/academy/${ge.id}`),className:"group cursor-pointer bg-card rounded-xl border border-border overflow-hidden transition-all duration-200 hover:shadow-lg hover:border-primary/30",children:[s.jsxs("div",{className:"aspect-video bg-muted/50 overflow-hidden relative",children:[ge.thumbnail_url?s.jsx("img",{src:ge.thumbnail_url,alt:ge.title,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):s.jsx("div",{className:"w-full h-full flex items-center justify-center",children:s.jsx(dM,{className:"h-8 w-8 text-muted-foreground/50"})}),ge.duration&&s.jsx("span",{className:"absolute bottom-2 right-2 bg-black/70 text-white text-xs px-1.5 py-0.5 rounded",children:ge.duration})]}),s.jsx("div",{className:"p-3",children:s.jsx("h4",{className:"font-medium text-sm text-foreground line-clamp-2 group-hover:text-primary transition-colors",children:ge.title})})]},ge.id))})]}),xe("academy").length>0&&s.jsx("div",{className:"mb-10",children:s.jsx(xC,{banners:xe("academy")})}),s.jsxs("section",{className:"mb-10",children:[s.jsxs("div",{className:"flex items-center justify-between mb-4",children:[s.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Resource Kits"}),s.jsxs(de,{variant:"ghost",size:"sm",onClick:()=>e("/toolbox"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",s.jsx(cd,{className:"h-4 w-4"})]})]}),m.length===0?s.jsx(at,{className:"bg-muted/30 border-dashed",children:s.jsx(ct,{className:"flex items-center justify-center py-8",children:s.jsxs("div",{className:"text-center",children:[s.jsx(WZ,{className:"h-8 w-8 text-muted-foreground/50 mx-auto mb-2"}),s.jsx("p",{className:"text-sm text-muted-foreground",children:"No resource kits available"})]})})}):s.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:m.map(ge=>s.jsxs("div",{onClick:()=>e(`/toolbox/${ge.id}`),className:"group cursor-pointer bg-card rounded-xl border border-border overflow-hidden transition-all duration-200 hover:shadow-lg hover:border-primary/30",children:[s.jsx("div",{className:"aspect-[4/3] bg-muted/50 overflow-hidden",children:ge.featured_image_url?s.jsx("img",{src:ge.featured_image_url,alt:ge.name,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):s.jsx("div",{className:"w-full h-full flex items-center justify-center",children:s.jsx(WZ,{className:"h-8 w-8 text-muted-foreground/50"})})}),s.jsx("div",{className:"p-3",children:s.jsx("h4",{className:"font-medium text-sm text-foreground truncate group-hover:text-primary transition-colors",children:ge.name})})]},ge.id))})]}),xe("toolbox").length>0&&s.jsx("div",{className:"mb-10",children:s.jsx(xC,{banners:xe("toolbox")})}),s.jsxs("section",{className:"mb-10",children:[s.jsxs("div",{className:"flex items-center justify-between mb-4",children:[s.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"New Templates"}),s.jsxs(de,{variant:"ghost",size:"sm",onClick:()=>e("/templates"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",s.jsx(cd,{className:"h-4 w-4"})]})]}),c.length===0?s.jsx(at,{className:"bg-muted/30 border-dashed",children:s.jsx(ct,{className:"flex items-center justify-center py-8",children:s.jsxs("div",{className:"text-center",children:[s.jsx(HZ,{className:"h-8 w-8 text-muted-foreground/50 mx-auto mb-2"}),s.jsx("p",{className:"text-sm text-muted-foreground",children:"No templates available"})]})})}):s.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:c.map(ge=>s.jsxs("div",{onClick:()=>e("/templates"),className:"group cursor-pointer bg-card rounded-xl border border-border overflow-hidden transition-all duration-200 hover:shadow-lg hover:border-primary/30",children:[s.jsx("div",{className:"aspect-[4/3] bg-muted/50 overflow-hidden",children:ge.preview_image_url?s.jsx("img",{src:ge.preview_image_url,alt:ge.name,className:"w-full h-full object-contain group-hover:scale-105 transition-transform duration-300"}):s.jsx("div",{className:"w-full h-full flex items-center justify-center",children:s.jsx(HZ,{className:"h-8 w-8 text-muted-foreground/50"})})}),s.jsx("div",{className:"p-3",children:s.jsx("h4",{className:"font-medium text-sm text-foreground truncate group-hover:text-primary transition-colors",children:ge.name})})]},ge.id))})]}),xe("templates").length>0&&s.jsx("div",{className:"mb-10",children:s.jsx(xC,{banners:xe("templates")})}),s.jsx("div",{className:"mb-10",children:s.jsx(zBe,{})}),s.jsxs("section",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-4",children:[s.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Your Apps"}),s.jsxs(de,{variant:"ghost",size:"sm",onClick:()=>e("/apps"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",s.jsx(cd,{className:"h-4 w-4"})]})]}),r.length===0?s.jsx(at,{className:"bg-muted/30 border-dashed",children:s.jsx(ct,{className:"flex items-center justify-center py-12",children:s.jsxs("div",{className:"text-center",children:[s.jsx(g_,{className:"h-8 w-8 text-muted-foreground/50 mx-auto mb-2"}),s.jsx("p",{className:"text-sm text-muted-foreground",children:"No apps available"})]})})}):s.jsx("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-3",children:r.map(ge=>{const ke=P.has(ge.id);return s.jsxs("div",{onClick:()=>X(ge),className:"group flex items-start gap-4 p-5 bg-card rounded-xl border border-border cursor-pointer transition-all duration-200 hover:shadow-lg hover:border-primary/30",children:[s.jsx("div",{className:"flex-shrink-0 w-14 h-14 rounded-xl bg-primary/10 flex items-center justify-center text-3xl",children:ge.icon}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("h3",{className:"font-semibold text-foreground group-hover:text-primary transition-colors truncate",children:ge.name}),s.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:ge.description})]}),ke&&s.jsx(g_,{className:"h-5 w-5 text-primary fill-current flex-shrink-0"})]},ge.id)})})]}),s.jsxs("section",{className:"mt-10",children:[s.jsxs("div",{className:"flex items-center justify-between mb-4",children:[s.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Additional Services"}),s.jsxs(de,{variant:"ghost",size:"sm",onClick:()=>e("/additional-services"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",s.jsx(cd,{className:"h-4 w-4"})]})]}),N.length===0?s.jsx(at,{className:"bg-muted/30 border-dashed",children:s.jsx(ct,{className:"flex items-center justify-center py-8",children:s.jsxs("div",{className:"text-center",children:[s.jsx(cu,{className:"h-8 w-8 text-muted-foreground/50 mx-auto mb-2"}),s.jsx("p",{className:"text-sm text-muted-foreground",children:"No additional services available"})]})})}):s.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:N.map(ge=>s.jsxs("div",{onClick:()=>window.open(ge.signup_link_url,"_blank"),className:"group cursor-pointer bg-card rounded-xl border border-border overflow-hidden transition-all duration-200 hover:shadow-lg hover:border-primary/30",children:[s.jsx("div",{className:"aspect-[4/3] bg-muted/50 overflow-hidden",children:ge.preview_image_url?s.jsx("img",{src:ge.preview_image_url,alt:ge.name,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):s.jsx("div",{className:"w-full h-full flex items-center justify-center",children:s.jsx(cu,{className:"h-8 w-8 text-muted-foreground/50"})})}),s.jsxs("div",{className:"p-3",children:[s.jsx("h4",{className:"font-medium text-sm text-foreground truncate group-hover:text-primary transition-colors",children:ge.name}),ge.description&&s.jsx("p",{className:"text-xs text-muted-foreground mt-1 line-clamp-2",children:ge.description})]})]},ge.id))})]})]})};var $D="Switch",[QBe]=Yo($D),[JBe,e5e]=QBe($D),jpe=D.forwardRef((t,e)=>{const{__scopeSwitch:r,name:n,checked:i,defaultChecked:o,required:c,disabled:a,value:m="on",onCheckedChange:g,form:_,...j}=t,[N,C]=D.useState(null),P=vs(e,z=>C(z)),A=D.useRef(!1),I=N?_||!!N.closest("form"):!0,[O,R]=Uu({prop:i,defaultProp:o??!1,onChange:g,caller:$D});return s.jsxs(JBe,{scope:r,checked:O,disabled:a,children:[s.jsx(yn.button,{type:"button",role:"switch","aria-checked":O,"aria-required":c,"data-state":kpe(O),"data-disabled":a?"":void 0,disabled:a,value:m,...j,ref:P,onClick:Yr(t.onClick,z=>{R(W=>!W),I&&(A.current=z.isPropagationStopped(),A.current||z.stopPropagation())})}),I&&s.jsx(Cpe,{control:N,bubbles:!A.current,name:n,value:m,checked:O,required:c,disabled:a,form:_,style:{transform:"translateX(-100%)"}})]})});jpe.displayName=$D;var Spe="SwitchThumb",Npe=D.forwardRef((t,e)=>{const{__scopeSwitch:r,...n}=t,i=e5e(Spe,r);return s.jsx(yn.span,{"data-state":kpe(i.checked),"data-disabled":i.disabled?"":void 0,...n,ref:e})});Npe.displayName=Spe;var t5e="SwitchBubbleInput",Cpe=D.forwardRef(({__scopeSwitch:t,control:e,checked:r,bubbles:n=!0,...i},o)=>{const c=D.useRef(null),a=vs(c,o),m=PT(r),g=_T(e);return D.useEffect(()=>{const _=c.current;if(!_)return;const j=window.HTMLInputElement.prototype,C=Object.getOwnPropertyDescriptor(j,"checked").set;if(m!==r&&C){const P=new Event("click",{bubbles:n});C.call(_,r),_.dispatchEvent(P)}},[m,r,n]),s.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:r,...i,tabIndex:-1,ref:a,style:{...i.style,...g,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});Cpe.displayName=t5e;function kpe(t){return t?"checked":"unchecked"}var Tpe=jpe,r5e=Npe;const ri=D.forwardRef(({className:t,...e},r)=>s.jsx(Tpe,{className:ar("peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors data-[state=checked]:bg-primary data-[state=unchecked]:bg-input focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50",t),...e,ref:r,children:s.jsx(r5e,{className:ar("pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0")})}));ri.displayName=Tpe.displayName;const n5e="BDZ4EGR_f2HSi1ey80lIv56fFsKw5ESwNT_JcW5SNl1uZJesu2RNPKD7u-zKrNEEHaq5V-3GlKp2O_Ajupt30vQ";function s5e(t){const e="=".repeat((4-t.length%4)%4),r=(t+e).replace(/-/g,"+").replace(/_/g,"/"),n=window.atob(r),i=new Uint8Array(n.length);for(let o=0;o{if(!g){c(!1);return}(async()=>{try{const C=await navigator.serviceWorker.register("/sw.js");m(C),r(Notification.permission);const P=await C.pushManager.getSubscription();i(!!P)}catch(C){console.error("Error initializing push notifications:",C)}finally{c(!1)}})()},[g]);const _=D.useCallback(async()=>{if(!g||!a||!t)return console.error("Push notifications not supported or user not logged in"),!1;try{if(c(!0),Notification.permission!=="granted"){const I=await Notification.requestPermission();if(r(I),I!=="granted")return Dt.error("Notification permission denied"),!1}const N=s5e(n5e),P=(await a.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:N})).toJSON(),{error:A}=await ae.from("push_subscriptions").upsert({user_id:t.id,endpoint:P.endpoint,p256dh_key:P.keys.p256dh,auth_key:P.keys.auth},{onConflict:"user_id,endpoint"});if(A)throw console.error("Error saving subscription:",A),A;return i(!0),Dt.success("Push notifications enabled"),!0}catch(N){return console.error("Error subscribing to push notifications:",N),Dt.error("Failed to enable push notifications"),!1}finally{c(!1)}},[g,a,t]),j=D.useCallback(async()=>{if(!a||!t)return!1;try{c(!0);const N=await a.pushManager.getSubscription();return N&&(await N.unsubscribe(),await ae.from("push_subscriptions").delete().eq("user_id",t.id).eq("endpoint",N.endpoint)),i(!1),Dt.success("Push notifications disabled"),!0}catch(N){return console.error("Error unsubscribing:",N),Dt.error("Failed to disable push notifications"),!1}finally{c(!1)}},[a,t]);return{isSupported:g,permission:e,isSubscribed:n,isLoading:o,subscribe:_,unsubscribe:j}}var a5e=Object.defineProperty,o5e=(t,e,r)=>e in t?a5e(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,fo=(t,e,r)=>o5e(t,typeof e!="symbol"?e+"":e,r);const KM={x:0,y:0,width:0,height:0,unit:"px"},dw=(t,e,r)=>Math.min(Math.max(t,e),r),l5e=(...t)=>t.filter(e=>e&&typeof e=="string").join(" "),uQ=(t,e)=>t===e||t.width===e.width&&t.height===e.height&&t.x===e.x&&t.y===e.y&&t.unit===e.unit;function c5e(t,e,r,n){const i=rp(t,r,n);return t.width&&(i.height=i.width/e),t.height&&(i.width=i.height*e),i.y+i.height>n&&(i.height=n-i.y,i.width=i.height*e),i.x+i.width>r&&(i.width=r-i.x,i.height=i.width/e),t.unit==="%"?ay(i,r,n):i}function u5e(t,e,r){const n=rp(t,e,r);return n.x=(e-n.width)/2,n.y=(r-n.height)/2,t.unit==="%"?ay(n,e,r):n}function ay(t,e,r){return t.unit==="%"?{...KM,...t,unit:"%"}:{unit:"%",x:t.x?t.x/e*100:0,y:t.y?t.y/r*100:0,width:t.width?t.width/e*100:0,height:t.height?t.height/r*100:0}}function rp(t,e,r){return t.unit?t.unit==="px"?{...KM,...t,unit:"px"}:{unit:"px",x:t.x?t.x*e/100:0,y:t.y?t.y*r/100:0,width:t.width?t.width*e/100:0,height:t.height?t.height*r/100:0}:{...KM,...t,unit:"px"}}function dQ(t,e,r,n,i,o=0,c=0,a=n,m=i){const g={...t};let _=Math.min(o,n),j=Math.min(c,i),N=Math.min(a,n),C=Math.min(m,i);e&&(e>1?(_=c?c*e:_,j=_/e,N=a*e):(j=o?o/e:j,_=j*e,C=m/e)),g.y<0&&(g.height=Math.max(g.height+g.y,j),g.y=0),g.x<0&&(g.width=Math.max(g.width+g.x,_),g.x=0);const P=n-(g.x+g.width);P<0&&(g.x=Math.min(g.x,n-_),g.width+=P);const A=i-(g.y+g.height);if(A<0&&(g.y=Math.min(g.y,i-j),g.height+=A),g.width<_&&((r==="sw"||r=="nw")&&(g.x-=_-g.width),g.width=_),g.heightN&&((r==="sw"||r=="nw")&&(g.x-=N-g.width),g.width=N),g.height>C&&((r==="nw"||r=="ne")&&(g.y-=C-g.height),g.height=C),e){const I=g.width/g.height;if(Ie){const O=Math.max(g.height*e,_);(r==="sw"||r=="nw")&&(g.x-=O-g.width),g.width=O}}return g}function d5e(t,e,r,n){const i={...t};return e==="ArrowLeft"?n==="nw"?(i.x-=r,i.y-=r,i.width+=r,i.height+=r):n==="w"?(i.x-=r,i.width+=r):n==="sw"?(i.x-=r,i.width+=r,i.height+=r):n==="ne"?(i.y+=r,i.width-=r,i.height-=r):n==="e"?i.width-=r:n==="se"&&(i.width-=r,i.height-=r):e==="ArrowRight"&&(n==="nw"?(i.x+=r,i.y+=r,i.width-=r,i.height-=r):n==="w"?(i.x+=r,i.width-=r):n==="sw"?(i.x+=r,i.width-=r,i.height-=r):n==="ne"?(i.y-=r,i.width+=r,i.height+=r):n==="e"?i.width+=r:n==="se"&&(i.width+=r,i.height+=r)),e==="ArrowUp"?n==="nw"?(i.x-=r,i.y-=r,i.width+=r,i.height+=r):n==="n"?(i.y-=r,i.height+=r):n==="ne"?(i.y-=r,i.width+=r,i.height+=r):n==="sw"?(i.x+=r,i.width-=r,i.height-=r):n==="s"?i.height-=r:n==="se"&&(i.width-=r,i.height-=r):e==="ArrowDown"&&(n==="nw"?(i.x+=r,i.y+=r,i.width-=r,i.height-=r):n==="n"?(i.y+=r,i.height-=r):n==="ne"?(i.y+=r,i.width-=r,i.height-=r):n==="sw"?(i.x-=r,i.width+=r,i.height+=r):n==="s"?i.height+=r:n==="se"&&(i.width+=r,i.height+=r)),i}const hw={capture:!0,passive:!1};let h5e=0;const ey=class Jh extends D.PureComponent{constructor(){super(...arguments),fo(this,"docMoveBound",!1),fo(this,"mouseDownOnCrop",!1),fo(this,"dragStarted",!1),fo(this,"evData",{startClientX:0,startClientY:0,startCropX:0,startCropY:0,clientX:0,clientY:0,isResize:!0}),fo(this,"componentRef",D.createRef()),fo(this,"mediaRef",D.createRef()),fo(this,"resizeObserver"),fo(this,"initChangeCalled",!1),fo(this,"instanceId",`rc-${h5e++}`),fo(this,"state",{cropIsActive:!1,newCropIsBeingDrawn:!1}),fo(this,"onCropPointerDown",e=>{const{crop:r,disabled:n}=this.props,i=this.getBox();if(!r)return;const o=rp(r,i.width,i.height);if(n)return;e.cancelable&&e.preventDefault(),this.bindDocMove(),this.componentRef.current.focus({preventScroll:!0});const c=e.target.dataset.ord,a=!!c;let m=e.clientX,g=e.clientY,_=o.x,j=o.y;if(c){const N=e.clientX-i.x,C=e.clientY-i.y;let P=0,A=0;c==="ne"||c=="e"?(P=N-(o.x+o.width),A=C-o.y,_=o.x,j=o.y+o.height):c==="se"||c==="s"?(P=N-(o.x+o.width),A=C-(o.y+o.height),_=o.x,j=o.y):c==="sw"||c=="w"?(P=N-o.x,A=C-(o.y+o.height),_=o.x+o.width,j=o.y):(c==="nw"||c=="n")&&(P=N-o.x,A=C-o.y,_=o.x+o.width,j=o.y+o.height),m=_+i.x+P,g=j+i.y+A}this.evData={startClientX:m,startClientY:g,startCropX:_,startCropY:j,clientX:e.clientX,clientY:e.clientY,isResize:a,ord:c},this.mouseDownOnCrop=!0,this.setState({cropIsActive:!0})}),fo(this,"onComponentPointerDown",e=>{const{crop:r,disabled:n,locked:i,keepSelection:o,onChange:c}=this.props,a=this.getBox();if(n||i||o&&r)return;e.cancelable&&e.preventDefault(),this.bindDocMove(),this.componentRef.current.focus({preventScroll:!0});const m=e.clientX-a.x,g=e.clientY-a.y,_={unit:"px",x:m,y:g,width:0,height:0};this.evData={startClientX:e.clientX,startClientY:e.clientY,startCropX:m,startCropY:g,clientX:e.clientX,clientY:e.clientY,isResize:!0},this.mouseDownOnCrop=!0,c(rp(_,a.width,a.height),ay(_,a.width,a.height)),this.setState({cropIsActive:!0,newCropIsBeingDrawn:!0})}),fo(this,"onDocPointerMove",e=>{const{crop:r,disabled:n,onChange:i,onDragStart:o}=this.props,c=this.getBox();if(n||!r||!this.mouseDownOnCrop)return;e.cancelable&&e.preventDefault(),this.dragStarted||(this.dragStarted=!0,o&&o(e));const{evData:a}=this;a.clientX=e.clientX,a.clientY=e.clientY;let m;a.isResize?m=this.resizeCrop():m=this.dragCrop(),uQ(r,m)||i(rp(m,c.width,c.height),ay(m,c.width,c.height))}),fo(this,"onComponentKeyDown",e=>{const{crop:r,disabled:n,onChange:i,onComplete:o}=this.props;if(n)return;const c=e.key;let a=!1;if(!r)return;const m=this.getBox(),g=this.makePixelCrop(m),_=(navigator.platform.match("Mac")?e.metaKey:e.ctrlKey)?Jh.nudgeStepLarge:e.shiftKey?Jh.nudgeStepMedium:Jh.nudgeStep;if(c==="ArrowLeft"?(g.x-=_,a=!0):c==="ArrowRight"?(g.x+=_,a=!0):c==="ArrowUp"?(g.y-=_,a=!0):c==="ArrowDown"&&(g.y+=_,a=!0),a){e.cancelable&&e.preventDefault(),g.x=dw(g.x,0,m.width-g.width),g.y=dw(g.y,0,m.height-g.height);const j=rp(g,m.width,m.height),N=ay(g,m.width,m.height);i(j,N),o&&o(j,N)}}),fo(this,"onHandlerKeyDown",(e,r)=>{const{aspect:n=0,crop:i,disabled:o,minWidth:c=0,minHeight:a=0,maxWidth:m,maxHeight:g,onChange:_,onComplete:j}=this.props,N=this.getBox();if(o||!i)return;if(e.key==="ArrowUp"||e.key==="ArrowDown"||e.key==="ArrowLeft"||e.key==="ArrowRight")e.stopPropagation(),e.preventDefault();else return;const C=(navigator.platform.match("Mac")?e.metaKey:e.ctrlKey)?Jh.nudgeStepLarge:e.shiftKey?Jh.nudgeStepMedium:Jh.nudgeStep,P=rp(i,N.width,N.height),A=d5e(P,e.key,C,r),I=dQ(A,n,r,N.width,N.height,c,a,m,g);if(!uQ(i,I)){const O=ay(I,N.width,N.height);_(I,O),j&&j(I,O)}}),fo(this,"onDocPointerDone",e=>{const{crop:r,disabled:n,onComplete:i,onDragEnd:o}=this.props,c=this.getBox();this.unbindDocMove(),!(n||!r)&&this.mouseDownOnCrop&&(this.mouseDownOnCrop=!1,this.dragStarted=!1,o&&o(e),i&&i(rp(r,c.width,c.height),ay(r,c.width,c.height)),this.setState({cropIsActive:!1,newCropIsBeingDrawn:!1}))}),fo(this,"onDragFocus",()=>{var e;(e=this.componentRef.current)==null||e.scrollTo(0,0)})}get document(){return document}getBox(){const e=this.mediaRef.current;if(!e)return{x:0,y:0,width:0,height:0};const{x:r,y:n,width:i,height:o}=e.getBoundingClientRect();return{x:r,y:n,width:i,height:o}}componentDidUpdate(e){const{crop:r,onComplete:n}=this.props;if(n&&!e.crop&&r){const{width:i,height:o}=this.getBox();i&&o&&n(rp(r,i,o),ay(r,i,o))}}componentWillUnmount(){this.resizeObserver&&this.resizeObserver.disconnect(),this.unbindDocMove()}bindDocMove(){this.docMoveBound||(this.document.addEventListener("pointermove",this.onDocPointerMove,hw),this.document.addEventListener("pointerup",this.onDocPointerDone,hw),this.document.addEventListener("pointercancel",this.onDocPointerDone,hw),this.docMoveBound=!0)}unbindDocMove(){this.docMoveBound&&(this.document.removeEventListener("pointermove",this.onDocPointerMove,hw),this.document.removeEventListener("pointerup",this.onDocPointerDone,hw),this.document.removeEventListener("pointercancel",this.onDocPointerDone,hw),this.docMoveBound=!1)}getCropStyle(){const{crop:e}=this.props;if(e)return{top:`${e.y}${e.unit}`,left:`${e.x}${e.unit}`,width:`${e.width}${e.unit}`,height:`${e.height}${e.unit}`}}dragCrop(){const{evData:e}=this,r=this.getBox(),n=this.makePixelCrop(r),i=e.clientX-e.startClientX,o=e.clientY-e.startClientY;return n.x=dw(e.startCropX+i,0,r.width-n.width),n.y=dw(e.startCropY+o,0,r.height-n.height),n}getPointRegion(e,r,n,i){const{evData:o}=this,c=o.clientX-e.x,a=o.clientY-e.y;let m;i&&r?m=r==="nw"||r==="n"||r==="ne":m=a1?o?[o,o/r]:[c*r,c]:c?[c*r,c]:[o,o/r]}resizeCrop(){const{evData:e}=this,{aspect:r=0,maxWidth:n,maxHeight:i}=this.props,o=this.getBox(),[c,a]=this.resolveMinDimensions(o,r,this.props.minWidth,this.props.minHeight);let m=this.makePixelCrop(o);const g=this.getPointRegion(o,e.ord,c,a),_=e.ord||g;let j=e.clientX-e.startClientX,N=e.clientY-e.startClientY;(c&&_==="nw"||_==="w"||_==="sw")&&(j=Math.min(j,-c)),(a&&_==="nw"||_==="n"||_==="ne")&&(N=Math.min(N,-a));const C={unit:"px",x:0,y:0,width:0,height:0};g==="ne"?(C.x=e.startCropX,C.width=j,r?(C.height=C.width/r,C.y=e.startCropY-C.height):(C.height=Math.abs(N),C.y=e.startCropY-C.height)):g==="se"?(C.x=e.startCropX,C.y=e.startCropY,C.width=j,r?C.height=C.width/r:C.height=N):g==="sw"?(C.x=e.startCropX+j,C.y=e.startCropY,C.width=Math.abs(j),r?C.height=C.width/r:C.height=N):g==="nw"&&(C.x=e.startCropX+j,C.width=Math.abs(j),r?(C.height=C.width/r,C.y=e.startCropY-C.height):(C.height=Math.abs(N),C.y=e.startCropY+N));const P=dQ(C,r,g,o.width,o.height,c,a,n,i);return r||Jh.xyOrds.indexOf(_)>-1?m=P:Jh.xOrds.indexOf(_)>-1?(m.x=P.x,m.width=P.width):Jh.yOrds.indexOf(_)>-1&&(m.y=P.y,m.height=P.height),m.x=dw(m.x,0,o.width-m.width),m.y=dw(m.y,0,o.height-m.height),m}renderCropSelection(){const{ariaLabels:e=Jh.defaultProps.ariaLabels,disabled:r,locked:n,renderSelectionAddon:i,ruleOfThirds:o,crop:c}=this.props,a=this.getCropStyle();if(c)return Ve.createElement("div",{style:a,className:"ReactCrop__crop-selection",onPointerDown:this.onCropPointerDown,"aria-label":e.cropArea,tabIndex:0,onKeyDown:this.onComponentKeyDown,role:"group"},!r&&!n&&Ve.createElement("div",{className:"ReactCrop__drag-elements",onFocus:this.onDragFocus},Ve.createElement("div",{className:"ReactCrop__drag-bar ord-n","data-ord":"n"}),Ve.createElement("div",{className:"ReactCrop__drag-bar ord-e","data-ord":"e"}),Ve.createElement("div",{className:"ReactCrop__drag-bar ord-s","data-ord":"s"}),Ve.createElement("div",{className:"ReactCrop__drag-bar ord-w","data-ord":"w"}),Ve.createElement("div",{className:"ReactCrop__drag-handle ord-nw","data-ord":"nw",tabIndex:0,"aria-label":e.nwDragHandle,onKeyDown:m=>this.onHandlerKeyDown(m,"nw"),role:"button"}),Ve.createElement("div",{className:"ReactCrop__drag-handle ord-n","data-ord":"n",tabIndex:0,"aria-label":e.nDragHandle,onKeyDown:m=>this.onHandlerKeyDown(m,"n"),role:"button"}),Ve.createElement("div",{className:"ReactCrop__drag-handle ord-ne","data-ord":"ne",tabIndex:0,"aria-label":e.neDragHandle,onKeyDown:m=>this.onHandlerKeyDown(m,"ne"),role:"button"}),Ve.createElement("div",{className:"ReactCrop__drag-handle ord-e","data-ord":"e",tabIndex:0,"aria-label":e.eDragHandle,onKeyDown:m=>this.onHandlerKeyDown(m,"e"),role:"button"}),Ve.createElement("div",{className:"ReactCrop__drag-handle ord-se","data-ord":"se",tabIndex:0,"aria-label":e.seDragHandle,onKeyDown:m=>this.onHandlerKeyDown(m,"se"),role:"button"}),Ve.createElement("div",{className:"ReactCrop__drag-handle ord-s","data-ord":"s",tabIndex:0,"aria-label":e.sDragHandle,onKeyDown:m=>this.onHandlerKeyDown(m,"s"),role:"button"}),Ve.createElement("div",{className:"ReactCrop__drag-handle ord-sw","data-ord":"sw",tabIndex:0,"aria-label":e.swDragHandle,onKeyDown:m=>this.onHandlerKeyDown(m,"sw"),role:"button"}),Ve.createElement("div",{className:"ReactCrop__drag-handle ord-w","data-ord":"w",tabIndex:0,"aria-label":e.wDragHandle,onKeyDown:m=>this.onHandlerKeyDown(m,"w"),role:"button"})),i&&Ve.createElement("div",{className:"ReactCrop__selection-addon",onPointerDown:m=>m.stopPropagation()},i(this.state)),o&&Ve.createElement(Ve.Fragment,null,Ve.createElement("div",{className:"ReactCrop__rule-of-thirds-hz"}),Ve.createElement("div",{className:"ReactCrop__rule-of-thirds-vt"})))}makePixelCrop(e){const r={...KM,...this.props.crop||{}};return rp(r,e.width,e.height)}render(){const{aspect:e,children:r,circularCrop:n,className:i,crop:o,disabled:c,locked:a,style:m,ruleOfThirds:g}=this.props,{cropIsActive:_,newCropIsBeingDrawn:j}=this.state,N=o?this.renderCropSelection():null,C=l5e("ReactCrop",i,_&&"ReactCrop--active",c&&"ReactCrop--disabled",a&&"ReactCrop--locked",j&&"ReactCrop--new-crop",o&&e&&"ReactCrop--fixed-aspect",o&&n&&"ReactCrop--circular-crop",o&&g&&"ReactCrop--rule-of-thirds",!this.dragStarted&&o&&!o.width&&!o.height&&"ReactCrop--invisible-crop",n&&"ReactCrop--no-animate");return Ve.createElement("div",{ref:this.componentRef,className:C,style:m},Ve.createElement("div",{ref:this.mediaRef,className:"ReactCrop__child-wrapper",onPointerDown:this.onComponentPointerDown},r),o?Ve.createElement("svg",{className:"ReactCrop__crop-mask",width:"100%",height:"100%"},Ve.createElement("defs",null,Ve.createElement("mask",{id:`hole-${this.instanceId}`},Ve.createElement("rect",{width:"100%",height:"100%",fill:"white"}),n?Ve.createElement("ellipse",{cx:`${o.x+o.width/2}${o.unit}`,cy:`${o.y+o.height/2}${o.unit}`,rx:`${o.width/2}${o.unit}`,ry:`${o.height/2}${o.unit}`,fill:"black"}):Ve.createElement("rect",{x:`${o.x}${o.unit}`,y:`${o.y}${o.unit}`,width:`${o.width}${o.unit}`,height:`${o.height}${o.unit}`,fill:"black"}))),Ve.createElement("rect",{fill:"black",fillOpacity:.5,width:"100%",height:"100%",mask:`url(#hole-${this.instanceId})`})):void 0,N)}};fo(ey,"xOrds",["e","w"]),fo(ey,"yOrds",["n","s"]),fo(ey,"xyOrds",["nw","ne","se","sw"]),fo(ey,"nudgeStep",1),fo(ey,"nudgeStepMedium",10),fo(ey,"nudgeStepLarge",100),fo(ey,"defaultProps",{ariaLabels:{cropArea:"Use the arrow keys to move the crop selection area",nwDragHandle:"Use the arrow keys to move the north west drag handle to change the crop selection area",nDragHandle:"Use the up and down arrow keys to move the north drag handle to change the crop selection area",neDragHandle:"Use the arrow keys to move the north east drag handle to change the crop selection area",eDragHandle:"Use the up and down arrow keys to move the east drag handle to change the crop selection area",seDragHandle:"Use the arrow keys to move the south east drag handle to change the crop selection area",sDragHandle:"Use the up and down arrow keys to move the south drag handle to change the crop selection area",swDragHandle:"Use the arrow keys to move the south west drag handle to change the crop selection area",wDragHandle:"Use the up and down arrow keys to move the west drag handle to change the crop selection area"}});let f5e=ey;var Epe=["PageUp","PageDown"],Ape=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Ppe={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},Hj="Slider",[D$,p5e,m5e]=hT(Hj),[Ipe]=Yo(Hj,[m5e]),[g5e,UD]=Ipe(Hj),Mpe=D.forwardRef((t,e)=>{const{name:r,min:n=0,max:i=100,step:o=1,orientation:c="horizontal",disabled:a=!1,minStepsBetweenThumbs:m=0,defaultValue:g=[n],value:_,onValueChange:j=()=>{},onValueCommit:N=()=>{},inverted:C=!1,form:P,...A}=t,I=D.useRef(new Set),O=D.useRef(0),z=c==="horizontal"?y5e:x5e,[W=[],V]=Uu({prop:_,defaultProp:g,onChange:he=>{var pe;(pe=[...I.current][O.current])==null||pe.focus(),j(he)}}),K=D.useRef(W);function Q(he){const xe=j5e(W,he);ie(he,xe)}function te(he){ie(he,O.current)}function X(){const he=K.current[O.current];W[O.current]!==he&&N(W)}function ie(he,xe,{commit:pe}={commit:!1}){const ve=k5e(o),ge=T5e(Math.round((he-n)/o)*o+n,ve),ke=ck(ge,[n,i]);V((Ce=[])=>{const Se=b5e(Ce,ke,xe);if(C5e(Se,m*o)){O.current=Se.indexOf(ke);const je=String(Se)!==String(Ce);return je&&pe&&N(Se),je?Se:Ce}else return Ce})}return s.jsx(g5e,{scope:t.__scopeSlider,name:r,disabled:a,min:n,max:i,valueIndexToChangeRef:O,thumbs:I.current,values:W,orientation:c,form:P,children:s.jsx(D$.Provider,{scope:t.__scopeSlider,children:s.jsx(D$.Slot,{scope:t.__scopeSlider,children:s.jsx(z,{"aria-disabled":a,"data-disabled":a?"":void 0,...A,ref:e,onPointerDown:Yr(A.onPointerDown,()=>{a||(K.current=W)}),min:n,max:i,inverted:C,onSlideStart:a?void 0:Q,onSlideMove:a?void 0:te,onSlideEnd:a?void 0:X,onHomeKeyDown:()=>!a&&ie(n,0,{commit:!0}),onEndKeyDown:()=>!a&&ie(i,W.length-1,{commit:!0}),onStepKeyDown:({event:he,direction:xe})=>{if(!a){const ge=Epe.includes(he.key)||he.shiftKey&&Ape.includes(he.key)?10:1,ke=O.current,Ce=W[ke],Se=o*ge*xe;ie(Ce+Se,ke,{commit:!0})}}})})})})});Mpe.displayName=Hj;var[Ope,Rpe]=Ipe(Hj,{startEdge:"left",endEdge:"right",size:"width",direction:1}),y5e=D.forwardRef((t,e)=>{const{min:r,max:n,dir:i,inverted:o,onSlideStart:c,onSlideMove:a,onSlideEnd:m,onStepKeyDown:g,..._}=t,[j,N]=D.useState(null),C=vs(e,z=>N(z)),P=D.useRef(void 0),A=i0(i),I=A==="ltr",O=I&&!o||!I&&o;function R(z){const W=P.current||j.getBoundingClientRect(),V=[0,W.width],Q=Aq(V,O?[r,n]:[n,r]);return P.current=W,Q(z-W.left)}return s.jsx(Ope,{scope:t.__scopeSlider,startEdge:O?"left":"right",endEdge:O?"right":"left",direction:O?1:-1,size:"width",children:s.jsx(Dpe,{dir:A,"data-orientation":"horizontal",..._,ref:C,style:{..._.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:z=>{const W=R(z.clientX);c==null||c(W)},onSlideMove:z=>{const W=R(z.clientX);a==null||a(W)},onSlideEnd:()=>{P.current=void 0,m==null||m()},onStepKeyDown:z=>{const V=Ppe[O?"from-left":"from-right"].includes(z.key);g==null||g({event:z,direction:V?-1:1})}})})}),x5e=D.forwardRef((t,e)=>{const{min:r,max:n,inverted:i,onSlideStart:o,onSlideMove:c,onSlideEnd:a,onStepKeyDown:m,...g}=t,_=D.useRef(null),j=vs(e,_),N=D.useRef(void 0),C=!i;function P(A){const I=N.current||_.current.getBoundingClientRect(),O=[0,I.height],z=Aq(O,C?[n,r]:[r,n]);return N.current=I,z(A-I.top)}return s.jsx(Ope,{scope:t.__scopeSlider,startEdge:C?"bottom":"top",endEdge:C?"top":"bottom",size:"height",direction:C?1:-1,children:s.jsx(Dpe,{"data-orientation":"vertical",...g,ref:j,style:{...g.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:A=>{const I=P(A.clientY);o==null||o(I)},onSlideMove:A=>{const I=P(A.clientY);c==null||c(I)},onSlideEnd:()=>{N.current=void 0,a==null||a()},onStepKeyDown:A=>{const O=Ppe[C?"from-bottom":"from-top"].includes(A.key);m==null||m({event:A,direction:O?-1:1})}})})}),Dpe=D.forwardRef((t,e)=>{const{__scopeSlider:r,onSlideStart:n,onSlideMove:i,onSlideEnd:o,onHomeKeyDown:c,onEndKeyDown:a,onStepKeyDown:m,...g}=t,_=UD(Hj,r);return s.jsx(yn.span,{...g,ref:e,onKeyDown:Yr(t.onKeyDown,j=>{j.key==="Home"?(c(j),j.preventDefault()):j.key==="End"?(a(j),j.preventDefault()):Epe.concat(Ape).includes(j.key)&&(m(j),j.preventDefault())}),onPointerDown:Yr(t.onPointerDown,j=>{const N=j.target;N.setPointerCapture(j.pointerId),j.preventDefault(),_.thumbs.has(N)?N.focus():n(j)}),onPointerMove:Yr(t.onPointerMove,j=>{j.target.hasPointerCapture(j.pointerId)&&i(j)}),onPointerUp:Yr(t.onPointerUp,j=>{const N=j.target;N.hasPointerCapture(j.pointerId)&&(N.releasePointerCapture(j.pointerId),o(j))})})}),Lpe="SliderTrack",Fpe=D.forwardRef((t,e)=>{const{__scopeSlider:r,...n}=t,i=UD(Lpe,r);return s.jsx(yn.span,{"data-disabled":i.disabled?"":void 0,"data-orientation":i.orientation,...n,ref:e})});Fpe.displayName=Lpe;var L$="SliderRange",zpe=D.forwardRef((t,e)=>{const{__scopeSlider:r,...n}=t,i=UD(L$,r),o=Rpe(L$,r),c=D.useRef(null),a=vs(e,c),m=i.values.length,g=i.values.map(N=>Upe(N,i.min,i.max)),_=m>1?Math.min(...g):0,j=100-Math.max(...g);return s.jsx(yn.span,{"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,...n,ref:a,style:{...t.style,[o.startEdge]:_+"%",[o.endEdge]:j+"%"}})});zpe.displayName=L$;var F$="SliderThumb",Bpe=D.forwardRef((t,e)=>{const r=p5e(t.__scopeSlider),[n,i]=D.useState(null),o=vs(e,a=>i(a)),c=D.useMemo(()=>n?r().findIndex(a=>a.ref.current===n):-1,[r,n]);return s.jsx(v5e,{...t,ref:o,index:c})}),v5e=D.forwardRef((t,e)=>{const{__scopeSlider:r,index:n,name:i,...o}=t,c=UD(F$,r),a=Rpe(F$,r),[m,g]=D.useState(null),_=vs(e,R=>g(R)),j=m?c.form||!!m.closest("form"):!0,N=_T(m),C=c.values[n],P=C===void 0?0:Upe(C,c.min,c.max),A=w5e(n,c.values.length),I=N==null?void 0:N[a.size],O=I?S5e(I,P,a.direction):0;return D.useEffect(()=>{if(m)return c.thumbs.add(m),()=>{c.thumbs.delete(m)}},[m,c.thumbs]),s.jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[a.startEdge]:`calc(${P}% + ${O}px)`},children:[s.jsx(D$.ItemSlot,{scope:t.__scopeSlider,children:s.jsx(yn.span,{role:"slider","aria-label":t["aria-label"]||A,"aria-valuemin":c.min,"aria-valuenow":C,"aria-valuemax":c.max,"aria-orientation":c.orientation,"data-orientation":c.orientation,"data-disabled":c.disabled?"":void 0,tabIndex:c.disabled?void 0:0,...o,ref:_,style:C===void 0?{display:"none"}:t.style,onFocus:Yr(t.onFocus,()=>{c.valueIndexToChangeRef.current=n})})}),j&&s.jsx($pe,{name:i??(c.name?c.name+(c.values.length>1?"[]":""):void 0),form:c.form,value:C},n)]})});Bpe.displayName=F$;var _5e="RadioBubbleInput",$pe=D.forwardRef(({__scopeSlider:t,value:e,...r},n)=>{const i=D.useRef(null),o=vs(i,n),c=PT(e);return D.useEffect(()=>{const a=i.current;if(!a)return;const m=window.HTMLInputElement.prototype,_=Object.getOwnPropertyDescriptor(m,"value").set;if(c!==e&&_){const j=new Event("input",{bubbles:!0});_.call(a,e),a.dispatchEvent(j)}},[c,e]),s.jsx(yn.input,{style:{display:"none"},...r,ref:o,defaultValue:e})});$pe.displayName=_5e;function b5e(t=[],e,r){const n=[...t];return n[r]=e,n.sort((i,o)=>i-o)}function Upe(t,e,r){const o=100/(r-e)*(t-e);return ck(o,[0,100])}function w5e(t,e){return e>2?`Value ${t+1} of ${e}`:e===2?["Minimum","Maximum"][t]:void 0}function j5e(t,e){if(t.length===1)return 0;const r=t.map(i=>Math.abs(i-e)),n=Math.min(...r);return r.indexOf(n)}function S5e(t,e,r){const n=t/2,o=Aq([0,50],[0,n]);return(n-o(e)*r)*r}function N5e(t){return t.slice(0,-1).map((e,r)=>t[r+1]-e)}function C5e(t,e){if(e>0){const r=N5e(t);return Math.min(...r)>=e}return!0}function Aq(t,e){return r=>{if(t[0]===t[1]||e[0]===e[1])return e[0];const n=(e[1]-e[0])/(t[1]-t[0]);return e[0]+n*(r-t[0])}}function k5e(t){return(String(t).split(".")[1]||"").length}function T5e(t,e){const r=Math.pow(10,e);return Math.round(t*r)/r}var Vpe=Mpe,E5e=Fpe,A5e=zpe,P5e=Bpe;const Zv=D.forwardRef(({className:t,...e},r)=>s.jsxs(Vpe,{ref:r,className:ar("relative flex w-full touch-none select-none items-center",t),...e,children:[s.jsx(E5e,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:s.jsx(A5e,{className:"absolute h-full bg-primary"})}),s.jsx(P5e,{className:"block h-5 w-5 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50"})]}));Zv.displayName=Vpe.displayName;function I5e(t,e,r){return u5e(c5e({unit:"%",width:90},r,t,e),t,e)}const M5e=({open:t,onClose:e,imageSrc:r,onCropComplete:n,aspectRatio:i=1})=>{const o=D.useRef(null),[c,a]=D.useState(),[m,g]=D.useState(),[_,j]=D.useState(1),[N,C]=D.useState(0),P=D.useCallback(O=>{const{width:R,height:z}=O.currentTarget;a(I5e(R,z,i))},[i]),A=D.useCallback(async()=>{const O=o.current;if(!O||!m)return;const R=document.createElement("canvas"),z=R.getContext("2d");if(!z)return;const W=O.naturalWidth/O.width,V=O.naturalHeight/O.height,K=400;R.width=K,R.height=K,z.imageSmoothingQuality="high";const Q=m.x*W,te=m.y*V,X=m.width*W,ie=m.height*V,he=N*Math.PI/180,xe=R.width/2,pe=R.height/2;return z.save(),z.translate(xe,pe),z.rotate(he),z.scale(_,_),z.translate(-xe,-pe),z.drawImage(O,Q,te,X,ie,0,0,K,K),z.restore(),new Promise((ve,ge)=>{R.toBlob(ke=>{ke?ve(ke):ge(new Error("Canvas is empty"))},"image/jpeg",.95)})},[m,_,N]),I=async()=>{try{const O=await A();O&&(n(O),e())}catch(O){console.error("Error cropping image:",O)}};return s.jsx(mn,{open:t,onOpenChange:e,children:s.jsxs(pn,{className:"max-w-lg",children:[s.jsx(xn,{children:s.jsx(gn,{children:"Crop Your Photo"})}),s.jsxs("div",{className:"space-y-4",children:[s.jsx("div",{className:"relative max-h-[400px] overflow-hidden rounded-lg bg-muted flex items-center justify-center",children:s.jsx(f5e,{crop:c,onChange:(O,R)=>a(R),onComplete:O=>g(O),aspect:i,circularCrop:!0,className:"max-h-[400px]",children:s.jsx("img",{ref:o,src:r,alt:"Crop preview",style:{transform:`scale(${_}) rotate(${N}deg)`,maxHeight:"400px",width:"auto"},onLoad:P})})}),s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(G2e,{className:"h-4 w-4 text-muted-foreground"}),s.jsx(Zv,{value:[_],min:.5,max:3,step:.1,onValueChange:([O])=>j(O),className:"flex-1"}),s.jsx(W2e,{className:"h-4 w-4 text-muted-foreground"})]}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(B2e,{className:"h-4 w-4 text-muted-foreground"}),s.jsx(Zv,{value:[N],min:-180,max:180,step:1,onValueChange:([O])=>C(O),className:"flex-1"}),s.jsxs("span",{className:"text-sm text-muted-foreground w-12",children:[N,"°"]})]})]})]}),s.jsxs(zi,{children:[s.jsx(de,{variant:"outline",onClick:e,children:"Cancel"}),s.jsx(de,{onClick:I,children:"Save Photo"})]})]})})},O5e=()=>{const{user:t}=rn(),{toast:e}=Ri(),[r,n]=D.useState(!1),[i,o]=D.useState(!1),[c,a]=D.useState(null);D.useEffect(()=>{t&&m()},[t]);const m=async()=>{n(!0);try{const{data:j}=await ae.from("profiles").select("subscription_status, subscription_product_id, subscription_end_date, is_grandfathered").eq("id",t==null?void 0:t.id).single();j&&a({status:j.subscription_status||"none",productId:j.subscription_product_id,endDate:j.subscription_end_date,isGrandfathered:j.is_grandfathered||!1})}catch(j){console.error("Error loading subscription:",j)}finally{n(!1)}},g=async()=>{o(!0);try{const{data:{session:j}}=await ae.auth.getSession();if(!j)throw new Error("Not authenticated");const{data:N,error:C}=await ae.functions.invoke("customer-portal",{headers:{Authorization:`Bearer ${j.access_token}`}});if(C)throw C;N!=null&&N.url&&window.open(N.url,"_blank")}catch(j){console.error("Error opening customer portal:",j),e({title:"Error",description:j.message||"Failed to open billing portal",variant:"destructive"})}finally{o(!1)}},_=()=>{if(c!=null&&c.isGrandfathered)return s.jsx(ir,{className:"bg-amber-500",children:"Grandfathered"});switch(c==null?void 0:c.status){case"active":return s.jsx(ir,{className:"bg-green-500",children:"Active"});case"trialing":return s.jsx(ir,{className:"bg-blue-500",children:"Trial"});case"past_due":return s.jsx(ir,{variant:"destructive",children:"Past Due"});case"canceled":return s.jsx(ir,{variant:"secondary",children:"Canceled"});default:return s.jsx(ir,{variant:"outline",children:"No Subscription"})}};return r?s.jsxs(at,{children:[s.jsx(xr,{children:s.jsxs(wr,{className:"flex items-center gap-2",children:[s.jsx(fM,{className:"h-5 w-5"}),"Subscription"]})}),s.jsx(ct,{children:s.jsx("div",{className:"flex items-center justify-center py-4",children:s.jsx(Ps,{className:"h-6 w-6 animate-spin text-muted-foreground"})})})]}):s.jsxs(at,{children:[s.jsxs(xr,{children:[s.jsxs(wr,{className:"flex items-center gap-2",children:[s.jsx(fM,{className:"h-5 w-5"}),"Subscription"]}),s.jsx(us,{children:"Manage your subscription and billing"})]}),s.jsxs(ct,{className:"space-y-4",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"font-medium",children:"Status"}),s.jsx("div",{className:"mt-1",children:_()})]}),(c==null?void 0:c.endDate)&&c.status==="active"&&s.jsxs("div",{className:"text-right",children:[s.jsx("p",{className:"text-sm text-muted-foreground",children:"Next billing date"}),s.jsx("p",{className:"font-medium",children:new Date(c.endDate).toLocaleDateString()})]})]}),c!=null&&c.isGrandfathered?s.jsx("p",{className:"text-sm text-muted-foreground",children:"Your account was upgraded from LevelUp 1.0. To update/manage your subscription please reach out to support."}):(c==null?void 0:c.status)==="active"||(c==null?void 0:c.status)==="trialing"?s.jsxs(s.Fragment,{children:[(c==null?void 0:c.status)==="trialing"&&(c==null?void 0:c.endDate)&&s.jsxs("p",{className:"text-sm text-muted-foreground mb-3",children:["Your trial ends on ",new Date(c.endDate).toLocaleDateString(),". After the trial, you'll be charged automatically."]}),s.jsxs(de,{onClick:g,variant:"outline",disabled:i,children:[i?s.jsx(Ps,{className:"mr-2 h-4 w-4 animate-spin"}):s.jsx(oa,{className:"mr-2 h-4 w-4"}),"Manage Billing"]})]}):s.jsx("p",{className:"text-sm text-muted-foreground",children:"You don't have an active subscription."})]})]})},R5e=()=>{const{user:t}=rn(),e=Bs(),{toast:r}=Ri(),[n]=n0(),i=n.get("setup")==="true",{isSupported:o,isSubscribed:c,isLoading:a,subscribe:m,unsubscribe:g}=i5e(),[_,j]=D.useState(!1),[N,C]=D.useState(""),[P,A]=D.useState(!1),[I,O]=D.useState(!1),[R,z]=D.useState(""),[W,V]=D.useState({name:"",email:""}),[K,Q]=D.useState(!1),[te,X]=D.useState(!1),[ie,he]=D.useState({newPassword:"",confirmPassword:""});D.useEffect(()=>{t&&xe()},[t]);const xe=async()=>{var Ce,Se;if(!(t!=null&&t.id)){console.log("No user ID available yet");return}try{console.log("Loading profile for user:",t.id);const{data:je,error:et}=await ae.from("profiles").select("name, email, digest_opt_out").eq("id",t.id).maybeSingle();if(et)throw console.error("Profile query error:",et),et;je?(console.log("Profile loaded successfully:",je),V({name:je.name||"",email:je.email||""}),Q(je.digest_opt_out||!1)):(console.warn("No profile found for user"),V({name:((Ce=t.user_metadata)==null?void 0:Ce.name)||((Se=t.email)==null?void 0:Se.split("@")[0])||"",email:t.email||""}));const{data:bt}=await ae.storage.from("avatars").list(`${t.id}`);if(bt&&bt.length>0){const{data:_e}=ae.storage.from("avatars").getPublicUrl(`${t.id}/${bt[0].name}`);C(_e.publicUrl)}}catch(je){console.error("Error loading profile:",je),r({title:"Error",description:je.message||"Failed to load profile",variant:"destructive"})}},pe=Ce=>{var et;const Se=(et=Ce.target.files)==null?void 0:et[0];if(!Se)return;const je=new FileReader;je.onloadend=()=>{z(je.result),O(!0)},je.readAsDataURL(Se),Ce.target.value=""},ve=async Ce=>{if(t){A(!0);try{const{data:Se}=await ae.storage.from("avatars").list(`${t.id}`);Se&&Se.length>0&&await ae.storage.from("avatars").remove(Se.map(Ye=>`${t.id}/${Ye.name}`));const et=`${t.id}/avatar.jpg`,{error:bt}=await ae.storage.from("avatars").upload(et,Ce,{upsert:!0,contentType:"image/jpeg"});if(bt)throw bt;const{data:_e}=ae.storage.from("avatars").getPublicUrl(et);C(`${_e.publicUrl}?t=${Date.now()}`),r({title:"Success",description:"Profile photo updated successfully"})}catch(Se){console.error("Error uploading avatar:",Se),r({title:"Error",description:Se.message||"Failed to upload photo",variant:"destructive"})}finally{A(!1)}}},ge=async()=>{if(!W.name.trim()||!W.email.trim()){r({title:"Error",description:"Name and email are required",variant:"destructive"});return}j(!0);try{const{error:Ce}=await ae.from("profiles").update({name:W.name.trim(),email:W.email.trim()}).eq("id",t==null?void 0:t.id);if(Ce)throw Ce;r({title:"Success",description:"Profile updated successfully"})}catch(Ce){console.error("Error updating profile:",Ce),r({title:"Error",description:Ce.message||"Failed to update profile",variant:"destructive"})}finally{j(!1)}},ke=async()=>{if(!ie.newPassword){r({title:"Error",description:"Please enter a new password",variant:"destructive"});return}if(ie.newPassword.length<6){r({title:"Error",description:"Password must be at least 6 characters",variant:"destructive"});return}if(ie.newPassword!==ie.confirmPassword){r({title:"Error",description:"Passwords do not match",variant:"destructive"});return}j(!0);try{const{error:Ce}=await ae.auth.updateUser({password:ie.newPassword});if(Ce)throw Ce;r({title:"Success",description:"Password updated successfully"}),he({newPassword:"",confirmPassword:""}),i&&setTimeout(()=>e("/dashboard"),1e3)}catch(Ce){console.error("Error updating password:",Ce),r({title:"Error",description:Ce.message||"Failed to update password",variant:"destructive"})}finally{j(!1)}};return s.jsx("div",{className:"min-h-screen bg-background p-8",children:s.jsxs("div",{className:"mx-auto max-w-4xl",children:[s.jsxs("div",{className:"mb-8 flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("h1",{className:"text-4xl font-bold",children:i?"Complete Your Profile":"Profile Settings"}),s.jsx("p",{className:"text-muted-foreground mt-2",children:i?"Welcome! Please complete your profile setup":"Manage your account information and password"})]}),!i&&s.jsxs(de,{variant:"outline",onClick:()=>e("/dashboard"),children:[s.jsx(Ka,{className:"mr-2 h-4 w-4"}),"Back"]})]}),s.jsxs("div",{className:"space-y-6",children:[s.jsxs(at,{children:[s.jsxs(xr,{children:[s.jsx(wr,{children:"Profile Photo"}),s.jsx(us,{children:"Upload a professional photo for your profile"})]}),s.jsxs(ct,{className:"flex items-center gap-6",children:[s.jsxs(ql,{className:"h-24 w-24",children:[s.jsx(Iy,{src:N}),s.jsx(Hl,{className:"text-2xl",children:W.name.split(" ").map(Ce=>Ce[0]).join("").toUpperCase()||"U"})]}),s.jsxs("div",{className:"flex-1",children:[s.jsx("input",{type:"file",id:"avatar-upload",accept:"image/*",className:"hidden",onChange:pe,disabled:P}),s.jsxs(de,{variant:"outline",onClick:()=>{var Ce;return(Ce=document.getElementById("avatar-upload"))==null?void 0:Ce.click()},disabled:P,children:[s.jsx(Vu,{className:"mr-2 h-4 w-4"}),P?"Uploading...":"Upload Photo"]}),s.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:"Upload an image and crop it to your liking."})]})]})]}),s.jsxs(at,{children:[s.jsxs(xr,{children:[s.jsx(wr,{children:"Personal Information"}),s.jsx(us,{children:"Update your profile details"})]}),s.jsxs(ct,{className:"space-y-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"name",children:"Name"}),s.jsx(Et,{id:"name",value:W.name,onChange:Ce=>V({...W,name:Ce.target.value}),maxLength:100})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"email",children:"Email"}),s.jsx(Et,{id:"email",type:"email",value:W.email,onChange:Ce=>V({...W,email:Ce.target.value}),maxLength:255})]}),s.jsxs(de,{onClick:ge,disabled:_,children:[s.jsx(K2,{className:"mr-2 h-4 w-4"}),"Save Changes"]})]})]}),s.jsxs(at,{children:[s.jsxs(xr,{children:[s.jsxs(wr,{className:"flex items-center gap-2",children:[c?s.jsx(QR,{className:"h-5 w-5"}):s.jsx(H6,{className:"h-5 w-5"}),"Push Notifications"]}),s.jsx(us,{children:"Receive browser notifications when new content is added"})]}),s.jsx(ct,{children:o?s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"font-medium",children:c?"Notifications enabled":"Notifications disabled"}),s.jsx("p",{className:"text-sm text-muted-foreground",children:c?"You'll receive notifications about new templates, videos, and events":"Enable to get notified about new content"})]}),s.jsx(ri,{checked:c,onCheckedChange:Ce=>{Ce?m():g()},disabled:a})]}):s.jsx("p",{className:"text-sm text-muted-foreground",children:"Push notifications are not supported in this browser. Please try using Chrome, Firefox, or Edge on a desktop device."})})]}),s.jsxs(at,{children:[s.jsxs(xr,{children:[s.jsxs(wr,{className:"flex items-center gap-2",children:[K?s.jsx(M2e,{className:"h-5 w-5"}):s.jsx(Fo,{className:"h-5 w-5"}),"Email Preferences"]}),s.jsx(us,{children:"Manage your email subscription settings"})]}),s.jsx(ct,{children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"font-medium",children:"Weekly Digest"}),s.jsx("p",{className:"text-sm text-muted-foreground",children:K?"You won't receive weekly digest emails":"Receive a weekly summary of new content, events, and your progress"})]}),s.jsx(ri,{checked:!K,onCheckedChange:async Ce=>{X(!0);try{const{error:Se}=await ae.from("profiles").update({digest_opt_out:!Ce}).eq("id",t==null?void 0:t.id);if(Se)throw Se;Q(!Ce),r({title:Ce?"Subscribed":"Unsubscribed",description:Ce?"You will now receive weekly digest emails":"You will no longer receive weekly digest emails"})}catch(Se){r({title:"Error",description:Se.message||"Failed to update preference",variant:"destructive"})}finally{X(!1)}},disabled:te})]})})]}),s.jsx(O5e,{}),s.jsxs(at,{children:[s.jsxs(xr,{children:[s.jsx(wr,{children:i?"Set Your Password":"Change Password"}),s.jsx(us,{children:i?"Create a secure password for your account":"Update your password to keep your account secure"})]}),s.jsxs(ct,{className:"space-y-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"newPassword",children:"New Password"}),s.jsx(Et,{id:"newPassword",type:"password",value:ie.newPassword,onChange:Ce=>he({...ie,newPassword:Ce.target.value}),placeholder:"Min 6 characters"})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"confirmPassword",children:"Confirm Password"}),s.jsx(Et,{id:"confirmPassword",type:"password",value:ie.confirmPassword,onChange:Ce=>he({...ie,confirmPassword:Ce.target.value}),placeholder:"Re-enter your new password"})]}),s.jsxs(de,{onClick:ke,disabled:_,children:[s.jsx(K2,{className:"mr-2 h-4 w-4"}),i?"Complete Setup":"Update Password"]}),i&&s.jsx(de,{variant:"outline",onClick:()=>e("/dashboard"),className:"ml-2",children:"Skip for Now"})]})]})]}),s.jsx(M5e,{open:I,onClose:()=>O(!1),imageSrc:R,onCropComplete:ve,aspectRatio:1})]})})},hQ=t=>{const e=new Date,r=new Date(t),n=Xhe(r,-15),i=Zhe(r,1);return ife(e,{start:n,end:i})};function D5e(){const t=Bs(),{user:e,isAdmin:r}=rn(),n=Wn(),{data:i,isLoading:o}=Sr({queryKey:["public-events"],queryFn:async()=>{const{data:A,error:I}=await ae.from("events").select("*").order("event_date",{ascending:!0});if(I)throw I;return A}}),{data:c}=Sr({queryKey:["my-registrations"],queryFn:async()=>{if(!e)return[];const{data:A,error:I}=await ae.from("event_registrations").select("event_id, zoom_join_url").eq("user_id",e.id);if(I)throw I;return A},enabled:!!e}),{data:a}=Sr({queryKey:["event-registration-counts"],queryFn:async()=>{const{data:A,error:I}=await ae.from("event_registrations").select("event_id");if(I)throw I;const O={};return A.forEach(R=>{O[R.event_id]=(O[R.event_id]||0)+1}),O}}),m=zr({mutationFn:async A=>{const{data:I,error:O}=await ae.functions.invoke("zoom-register",{body:{event_id:A}});if(O)throw O;if(I!=null&&I.error)throw new Error(I.error);return I},onSuccess:A=>{n.invalidateQueries({queryKey:["my-registrations"]}),n.invalidateQueries({queryKey:["event-registration-counts"]}),A!=null&&A.join_url?Dt.success("Successfully registered! You'll receive a Zoom confirmation email."):Dt.success("Successfully registered for the event!")},onError:A=>{Dt.error("Failed to register: "+A.message)}}),g=zr({mutationFn:async A=>{const{data:I,error:O}=await ae.functions.invoke("zoom-unregister",{body:{event_id:A}});if(O)throw O;if(I!=null&&I.error)throw new Error(I.error);return I},onSuccess:()=>{n.invalidateQueries({queryKey:["my-registrations"]}),n.invalidateQueries({queryKey:["event-registration-counts"]}),Dt.success("Registration cancelled and removed from Zoom")},onError:A=>{Dt.error("Failed to cancel: "+A.message)}}),_=A=>c==null?void 0:c.some(I=>I.event_id===A),j=A=>{const I=c==null?void 0:c.find(O=>O.event_id===A);return I==null?void 0:I.zoom_join_url},N=A=>A.capacity?((a==null?void 0:a[A.id])||0)>=A.capacity:!1,C=(i==null?void 0:i.filter(A=>!VM(new Date(A.event_date))))||[],P=(i==null?void 0:i.filter(A=>VM(new Date(A.event_date))))||[];return s.jsx(Jr,{title:"Events",children:s.jsxs("div",{className:"max-w-6xl mx-auto",children:[s.jsxs("div",{className:"flex items-center justify-between mb-6",children:[s.jsxs("div",{children:[s.jsx("h2",{className:"text-2xl font-bold text-foreground",children:"Events"}),s.jsx("p",{className:"text-muted-foreground",children:"Browse and register for upcoming events"})]}),r&&s.jsx(de,{variant:"outline",onClick:()=>t("/admin/events"),children:"Manage Events"})]}),o?s.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading events..."}):C.length===0?s.jsx(at,{className:"text-center py-12",children:s.jsx(ct,{children:s.jsx("p",{className:"text-muted-foreground",children:"No upcoming events at the moment. Check back soon!"})})}):s.jsx("div",{className:"grid gap-6 md:grid-cols-2 lg:grid-cols-3",children:C.map(A=>s.jsxs(at,{className:`flex flex-col overflow-hidden cursor-pointer hover:shadow-lg transition-all ${hQ(A.event_date)?"border-red-500 ring-2 ring-red-500/20":"hover:border-primary/50"}`,onClick:()=>t(`/events/${A.id}`),children:[hQ(A.event_date)&&s.jsxs("div",{className:"bg-red-500 text-white px-3 py-1.5 flex items-center gap-2 text-sm font-medium",children:[s.jsxs("span",{className:"relative flex h-2 w-2",children:[s.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-white opacity-75"}),s.jsx("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-white"})]}),s.jsx(Y6,{className:"h-3.5 w-3.5"}),"LIVE NOW"]}),A.image_url&&s.jsx("div",{className:"aspect-video overflow-hidden",children:s.jsx("img",{src:A.image_url,alt:A.title,className:"w-full h-full object-cover group-hover:scale-105 transition-transform"})}),s.jsxs(xr,{children:[s.jsx(wr,{className:"line-clamp-2",children:A.title}),A.description&&s.jsx(us,{className:"line-clamp-2",children:A.description})]}),s.jsxs(ct,{className:"flex-1 space-y-2",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[s.jsx(ko,{className:"h-4 w-4"}),Vn(new Date(A.event_date),"EEEE, MMMM d, yyyy")]}),s.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[s.jsx(No,{className:"h-4 w-4"}),Vn(new Date(A.event_date),"h:mm a")]}),s.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[s.jsx(_i,{className:"h-4 w-4"}),(a==null?void 0:a[A.id])||0," registered",A.capacity&&` / ${A.capacity} spots`]})]}),s.jsx(o2,{className:"flex gap-2",onClick:I=>I.stopPropagation(),children:_(A.id)?s.jsxs(s.Fragment,{children:[s.jsxs(de,{variant:"outline",className:"flex-1",onClick:()=>g.mutate(A.id),disabled:g.isPending,children:[s.jsx(Ni,{className:"h-4 w-4 mr-2"}),"Cancel"]}),s.jsxs(de,{className:"flex-1",onClick:()=>window.open(j(A.id)||A.zoom_link,"_blank"),children:[s.jsx(oa,{className:"h-4 w-4 mr-2"}),"Join Zoom"]})]}):s.jsx(de,{className:"w-full",onClick:()=>m.mutate(A.id),disabled:m.isPending||N(A),children:N(A)?"Event Full":s.jsxs(s.Fragment,{children:[s.jsx(ru,{className:"h-4 w-4 mr-2"}),"Register"]})})})]},A.id))}),P.length>0&&s.jsxs("div",{className:"mt-12",children:[s.jsx("h3",{className:"text-xl font-semibold mb-4 text-muted-foreground",children:"Past Events"}),s.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:P.map(A=>s.jsx(at,{className:"opacity-60 cursor-pointer hover:opacity-80 transition-opacity",onClick:()=>t(`/events/${A.id}`),children:s.jsxs(xr,{children:[s.jsx(wr,{className:"text-base line-clamp-1",children:A.title}),s.jsx(us,{children:Vn(new Date(A.event_date),"MMMM d, yyyy")})]})},A.id))})]})]})})}function L5e({open:t,onOpenChange:e,resourceType:r,resourceId:n,resourceTitle:i}){const{user:o,isAdmin:c,isBrokerageManager:a}=rn(),[m,g]=D.useState([]),[_,j]=D.useState([]),[N,C]=D.useState(""),[P,A]=D.useState(""),[I,O]=D.useState(!1),[R,z]=D.useState(!1),W=c||a;D.useEffect(()=>{t&&o&&V()},[t,o]);const V=async()=>{if(o){O(!0);try{const{data:he}=await ae.from("profiles").select("brokerage_id").eq("id",o.id).single();if(!(he!=null&&he.brokerage_id)){Dt.error("You must be part of a brokerage to share resources"),e(!1);return}const{data:xe,error:pe}=await ae.from("profiles").select("id, name, email").eq("brokerage_id",he.brokerage_id).neq("id",o.id).order("name");if(pe)throw pe;g(xe||[])}catch(he){console.error("Error loading agents:",he),Dt.error("Failed to load agents")}finally{O(!1)}}},K=m.filter(he=>he.name.toLowerCase().includes(N.toLowerCase())||he.email.toLowerCase().includes(N.toLowerCase())),Q=()=>{_.length===K.length?j([]):j(K.map(he=>he.id))},te=he=>{if(!W){j([he]);return}j(xe=>xe.includes(he)?xe.filter(pe=>pe!==he):[...xe,he])},X=async()=>{if(_.length===0){Dt.error("Please select at least one agent to share with");return}z(!0);try{const{data:he,error:xe}=await ae.functions.invoke("send-share-notification",{body:{recipientIds:_,resourceType:r,resourceId:n,resourceTitle:i,message:P.trim()||void 0}});if(xe)throw xe;Dt.success(`Shared with ${_.length} agent${_.length>1?"s":""}`),e(!1),j([]),A("")}catch(he){console.error("Error sharing resource:",he),Dt.error("Failed to share resource")}finally{z(!1)}},ie=he=>he.split(" ").map(xe=>xe[0]).join("").toUpperCase().slice(0,2);return s.jsx(mn,{open:t,onOpenChange:e,children:s.jsxs(pn,{className:"sm:max-w-md",children:[s.jsxs(xn,{children:[s.jsxs(gn,{className:"flex items-center gap-2",children:[s.jsx(Dc,{className:"h-5 w-5"}),"Share Resource"]}),s.jsxs(fi,{children:['Share "',i,'" with agents in your brokerage']})]}),s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"relative",children:[s.jsx(ba,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),s.jsx(Et,{placeholder:"Search agents...",value:N,onChange:he=>C(he.target.value),className:"pl-9"})]}),W&&K.length>0&&s.jsxs("div",{className:"flex items-center justify-between px-1",children:[s.jsxs(de,{variant:"ghost",size:"sm",onClick:Q,className:"text-xs",children:[s.jsx(_i,{className:"h-3 w-3 mr-1"}),_.length===K.length?"Deselect All":"Select All"]}),s.jsxs("span",{className:"text-xs text-muted-foreground",children:[_.length," selected"]})]}),s.jsx(qu,{className:"h-[200px] border rounded-md",children:I?s.jsx("div",{className:"flex items-center justify-center h-full",children:s.jsx(Ps,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):K.length===0?s.jsx("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:"No agents found"}):s.jsx("div",{className:"p-2 space-y-1",children:K.map(he=>s.jsxs("div",{className:`flex items-center gap-3 p-2 rounded-md cursor-pointer hover:bg-accent transition-colors ${_.includes(he.id)?"bg-accent":""}`,onClick:()=>te(he.id),children:[s.jsx(dx,{checked:_.includes(he.id),onCheckedChange:()=>te(he.id)}),s.jsx(ql,{className:"h-8 w-8",children:s.jsx(Hl,{className:"text-xs",children:ie(he.name)})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("p",{className:"text-sm font-medium truncate",children:he.name}),s.jsx("p",{className:"text-xs text-muted-foreground truncate",children:he.email})]})]},he.id))})}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"message",children:"Add a message (optional)"}),s.jsx(mi,{id:"message",placeholder:"I thought you might find this useful...",value:P,onChange:he=>A(he.target.value),rows:2})]}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(de,{variant:"outline",onClick:()=>e(!1),children:"Cancel"}),s.jsx(de,{onClick:X,disabled:_.length===0||R,children:R?s.jsxs(s.Fragment,{children:[s.jsx(Ps,{className:"h-4 w-4 mr-2 animate-spin"}),"Sharing..."]}):s.jsxs(s.Fragment,{children:[s.jsx(Dc,{className:"h-4 w-4 mr-2"}),"Share"]})})]})]})]})})}function Wj({resourceType:t,resourceId:e,resourceTitle:r,variant:n="outline",size:i="sm",className:o=""}){const[c,a]=D.useState(!1),{user:m}=rn();return m?s.jsxs(s.Fragment,{children:[s.jsxs(de,{variant:n,size:i,onClick:()=>a(!0),className:o,children:[s.jsx(ph,{className:"h-4 w-4 mr-2"}),"Share"]}),s.jsx(L5e,{open:c,onOpenChange:a,resourceType:t,resourceId:e,resourceTitle:r})]}):null}function F5e(){const{eventId:t}=mu(),e=Bs(),{user:r}=rn(),[n,i]=D.useState(null),[o,c]=D.useState(null),[a,m]=D.useState(0),[g,_]=D.useState(!0),[j,N]=D.useState(!1);D.useEffect(()=>{t&&C()},[t,r]);const C=async()=>{try{const{data:z,error:W}=await ae.from("events").select("*").eq("id",t).single();if(W)throw W;i(z);const{count:V}=await ae.from("event_registrations").select("*",{count:"exact",head:!0}).eq("event_id",t);if(m(V||0),r){const{data:K}=await ae.from("event_registrations").select("id, zoom_join_url").eq("event_id",t).eq("user_id",r.id).maybeSingle();c(K)}}catch(z){console.error("Error loading event:",z),Dt.error("Failed to load event"),e("/events")}finally{_(!1)}},P=async()=>{if(!(!r||!n)){N(!0);try{if(o){const{error:z}=await ae.functions.invoke("zoom-unregister",{body:{event_id:n.id}});if(z)throw z;Dt.success("Successfully cancelled registration"),c(null),m(W=>W-1)}else{const{data:z,error:W}=await ae.functions.invoke("zoom-register",{body:{event_id:n.id}});if(W)throw W;Dt.success("Successfully registered for event!"),c({id:z.registration_id,zoom_join_url:z.zoom_join_url}),m(V=>V+1)}}catch(z){console.error("Registration error:",z),Dt.error(o?"Failed to cancel registration":"Failed to register for event")}finally{N(!1)}}},A=z=>{var W,V,K;if(z.includes("iframe.mediadelivery.net")||z.includes("video.bunnycdn.com")){const Q=z.match(/embed\/(\d+)\/([a-f0-9-]+)/);if(Q)return`https://iframe.mediadelivery.net/embed/${Q[1]}/${Q[2]}?autoplay=false&preload=true`}if(z.includes("youtube.com")||z.includes("youtu.be")){const Q=z.includes("youtu.be")?(W=z.split("youtu.be/")[1])==null?void 0:W.split("?")[0]:(V=z.split("v=")[1])==null?void 0:V.split("&")[0];if(Q)return`https://www.youtube.com/embed/${Q}`}if(z.includes("vimeo.com")){const Q=(K=z.split("vimeo.com/")[1])==null?void 0:K.split("?")[0];if(Q)return`https://player.vimeo.com/video/${Q}`}return z};if(g)return s.jsx(Jr,{title:"Event",children:s.jsx("div",{className:"flex items-center justify-center py-16",children:s.jsxs("div",{className:"text-center",children:[s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent mx-auto mb-4"}),s.jsx("p",{className:"text-muted-foreground",children:"Loading event..."})]})})});if(!n)return s.jsx(Jr,{title:"Event Not Found",children:s.jsxs("div",{className:"text-center py-16",children:[s.jsx("p",{className:"text-muted-foreground",children:"Event not found"}),s.jsx(de,{onClick:()=>e("/events"),className:"mt-4",children:"Back to Events"})]})});const I=VM(new Date(n.event_date)),O=n.capacity&&a>=n.capacity,R=(o==null?void 0:o.zoom_join_url)||n.zoom_link;return s.jsx(Jr,{title:n.title,children:s.jsxs("div",{className:"max-w-4xl mx-auto",children:[s.jsxs(de,{variant:"ghost",className:"mb-6 gap-2",onClick:()=>e("/events"),children:[s.jsx(Ka,{className:"h-4 w-4"}),"Back to Events"]}),n.image_url&&s.jsxs("div",{className:"relative aspect-video rounded-xl overflow-hidden mb-6",children:[s.jsx("img",{src:n.image_url,alt:n.title,className:"w-full h-full object-cover"}),I&&s.jsx("div",{className:"absolute inset-0 bg-black/50 flex items-center justify-center",children:s.jsx(ir,{variant:"secondary",className:"text-lg px-4 py-2",children:"Event Ended"})})]}),s.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[s.jsxs("div",{className:"lg:col-span-2 space-y-6",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-start justify-between gap-4 mb-4",children:[s.jsx("h1",{className:"text-3xl font-bold text-foreground",children:n.title}),s.jsx(Wj,{resourceType:"event",resourceId:n.id,resourceTitle:n.title})]}),n.description&&s.jsx("div",{className:"prose prose-sm max-w-none text-muted-foreground",children:s.jsx("p",{className:"whitespace-pre-wrap",children:n.description})})]}),n.video_url&&s.jsxs("div",{className:"space-y-3",children:[s.jsxs("h3",{className:"text-lg font-semibold flex items-center gap-2",children:[s.jsx(dM,{className:"h-5 w-5"}),"Event Preview"]}),s.jsx("div",{className:"relative w-full aspect-video rounded-xl overflow-hidden border bg-muted",children:s.jsx("iframe",{src:A(n.video_url),className:"absolute inset-0 w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,title:"Event Preview Video"})})]})]}),s.jsx("div",{className:"space-y-4",children:s.jsx(at,{children:s.jsxs(ct,{className:"p-6 space-y-4",children:[s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx(ko,{className:"h-5 w-5 text-primary mt-0.5"}),s.jsxs("div",{children:[s.jsx("p",{className:"font-medium",children:Vn(new Date(n.event_date),"EEEE, MMMM d, yyyy")}),s.jsx("p",{className:"text-sm text-muted-foreground",children:Vn(new Date(n.event_date),"h:mm a")})]})]}),n.capacity&&s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx(_i,{className:"h-5 w-5 text-primary mt-0.5"}),s.jsxs("div",{children:[s.jsxs("p",{className:"font-medium",children:[a," / ",n.capacity]}),s.jsx("p",{className:"text-sm text-muted-foreground",children:"Registered"})]})]}),o&&s.jsxs("div",{className:"flex items-center gap-2 p-3 bg-green-500/10 rounded-lg",children:[s.jsx(gc,{className:"h-5 w-5 text-green-600"}),s.jsx("span",{className:"text-sm font-medium text-green-700",children:"You're registered!"})]}),s.jsxs("div",{className:"space-y-2 pt-2",children:[!I&&s.jsx(s.Fragment,{children:o?s.jsxs(s.Fragment,{children:[s.jsxs(de,{className:"w-full gap-2",onClick:()=>window.open(R,"_blank"),children:[s.jsx(oa,{className:"h-4 w-4"}),"Join Event"]}),s.jsxs(de,{variant:"outline",className:"w-full",onClick:P,disabled:j,children:[j?s.jsx(Ps,{className:"h-4 w-4 animate-spin mr-2"}):null,"Cancel Registration"]})]}):s.jsx(de,{className:"w-full gap-2",onClick:P,disabled:j||(O??!1),children:j?s.jsx(Ps,{className:"h-4 w-4 animate-spin"}):O?"Event Full":"Register Now"})}),I&&o&&s.jsxs(de,{variant:"outline",className:"w-full gap-2",onClick:()=>window.open(n.zoom_link,"_blank"),children:[s.jsx(oa,{className:"h-4 w-4"}),"View Recording"]})]})]})})})]})]})})}const z5e=()=>{const{user:t,isAdmin:e}=rn(),r=Bs(),[n,i]=D.useState([]),[o,c]=D.useState(!0),[a,m]=D.useState(""),[g,_]=D.useState("all"),[j,N]=D.useState(new Set);D.useEffect(()=>{C()},[t]);const C=async()=>{try{const{data:R}=await ae.from("user_tags").select("tag").eq("user_id",t==null?void 0:t.id),z=(R==null?void 0:R.map(ie=>ie.tag))||[],{data:W,error:V}=await ae.from("app_tiles").select("*").order("name");if(V)throw V;const{data:K}=await ae.from("user_favorites").select("app_id").eq("user_id",t==null?void 0:t.id),Q=new Set((K==null?void 0:K.map(ie=>ie.app_id))||[]);N(Q);const X=((W==null?void 0:W.filter(ie=>!ie.required_tags||ie.required_tags.length===0?!0:ie.required_tags.some(he=>z.includes(he))))||[]).sort((ie,he)=>ie.name==="LevelUp Members Portal"?-1:he.name==="LevelUp Members Portal"?1:0);i(X)}catch(R){console.error("Error loading apps:",R),Dt.error("Failed to load apps")}finally{c(!1)}},P=async R=>{var W;const z=window.open("about:blank","_blank");try{await ae.from("activity_logs").insert({user_id:t==null?void 0:t.id,app_id:R.app_id,app_name:R.name,user_agent:navigator.userAgent});const{data:V,error:K}=await ae.functions.invoke("sso-launch",{body:{app_id:R.app_id}});if(K)throw K;V!=null&&V.redirect_url?z&&!z.closed?(z.location.href=V.redirect_url,(W=z.focus)==null||W.call(z)):window.location.assign(V.redirect_url):(z==null||z.close(),Dt.error("Launch link unavailable"))}catch(V){z==null||z.close(),console.error("Error launching app:",V),Dt.error("Failed to launch app")}},A=async(R,z)=>{R.stopPropagation();const W=j.has(z);try{if(W){const{error:V}=await ae.from("user_favorites").delete().eq("user_id",t==null?void 0:t.id).eq("app_id",z);if(V)throw V;N(K=>{const Q=new Set(K);return Q.delete(z),Q}),Dt.success("Removed from favorites")}else{const{error:V}=await ae.from("user_favorites").insert({user_id:t==null?void 0:t.id,app_id:z});if(V)throw V;N(K=>new Set(K).add(z)),Dt.success("Added to favorites")}}catch(V){console.error("Error toggling favorite:",V),Dt.error("Failed to update favorites")}},I=n.filter(R=>{var W;const z=R.name.toLowerCase().includes(a.toLowerCase())||((W=R.description)==null?void 0:W.toLowerCase().includes(a.toLowerCase()));return g==="favorites"?z&&j.has(R.id):z}),O=[{id:"all",label:"All"},{id:"favorites",label:"Favorites"}];return o?s.jsx(Jr,{title:"Apps & Tools",children:s.jsx("div",{className:"flex items-center justify-center py-16",children:s.jsxs("div",{className:"text-center",children:[s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent mx-auto mb-4"}),s.jsx("p",{className:"text-muted-foreground",children:"Loading apps..."})]})})}):s.jsxs(Jr,{title:"Apps & Tools",children:[s.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6",children:[s.jsx("h2",{className:"text-2xl font-bold text-foreground",children:"Apps & Tools"}),s.jsxs("div",{className:"relative max-w-sm w-full",children:[s.jsx(ba,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),s.jsx(Et,{placeholder:"Search apps...",className:"pl-10 bg-muted/50 border-0 focus-visible:ring-1",value:a,onChange:R=>m(R.target.value)})]})]}),s.jsx("div",{className:"flex gap-6 border-b border-border mb-8",children:O.map(R=>s.jsxs("button",{onClick:()=>_(R.id),className:ar("pb-3 text-sm font-medium transition-colors relative",g===R.id?"text-primary":"text-muted-foreground hover:text-foreground"),children:[R.label,g===R.id&&s.jsx("span",{className:"absolute bottom-0 left-0 right-0 h-0.5 bg-primary"})]},R.id))}),I.length===0?s.jsx("div",{className:"flex flex-col items-center justify-center py-16 bg-card rounded-xl border border-border",children:g==="favorites"?s.jsxs(s.Fragment,{children:[s.jsx(g_,{className:"h-12 w-12 text-muted-foreground mb-4"}),s.jsx("p",{className:"text-lg font-medium mb-2 text-foreground",children:"No favorites yet"}),s.jsx("p",{className:"text-sm text-muted-foreground text-center max-w-md",children:"Click the bookmark icon on any app to add it to your favorites"})]}):s.jsxs(s.Fragment,{children:[s.jsx(mM,{className:"h-12 w-12 text-muted-foreground mb-4"}),s.jsx("p",{className:"text-lg font-medium mb-2 text-foreground",children:"No apps available"}),s.jsx("p",{className:"text-sm text-muted-foreground text-center max-w-md",children:e?"Get started by adding apps in the admin panel":"Contact your administrator to get access to apps"}),e&&s.jsx(de,{className:"mt-4",onClick:()=>r("/admin/apps"),children:"Add Apps"})]})}):s.jsx("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-3",children:I.map(R=>{const z=j.has(R.id);return s.jsxs("div",{onClick:()=>P(R),className:"group flex items-start gap-4 p-5 bg-card rounded-xl border border-border cursor-pointer transition-all duration-200 hover:shadow-lg hover:border-primary/30",children:[s.jsx("div",{className:"flex-shrink-0 w-14 h-14 rounded-xl bg-primary/10 flex items-center justify-center text-3xl",children:R.icon}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("h3",{className:"font-semibold text-foreground group-hover:text-primary transition-colors truncate",children:R.name}),s.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:R.description})]}),s.jsx("button",{className:ar("flex-shrink-0 p-1 transition-colors",z?"text-primary":"text-muted-foreground/50 hover:text-primary"),onClick:W=>A(W,R.id),children:s.jsx(g_,{className:ar("h-5 w-5",z&&"fill-current")})})]},R.id)})})]})},B5e=()=>{const t=Bs(),[e,r]=D.useState(""),[n,i]=D.useState("all"),[o,c]=D.useState("all"),[a,m]=D.useState("grid"),{data:g=[]}=Sr({queryKey:["template-categories"],queryFn:async()=>{const{data:O,error:R}=await ae.from("template_categories").select("*").order("name");if(R)throw R;return O}}),{data:_=[]}=Sr({queryKey:["template-types"],queryFn:async()=>{const{data:O,error:R}=await ae.from("template_types").select("*").order("name");if(R)throw R;return O}}),{data:j=[],isLoading:N}=Sr({queryKey:["canva-templates"],queryFn:async()=>{const{data:O,error:R}=await ae.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).order("publish_date",{ascending:!1});if(R)throw R;const{data:z,error:W}=await ae.from("template_links").select("*").order("sort_order");if(W)throw W;const{data:V}=await ae.from("template_likes").select("template_id"),{data:K}=await ae.from("template_comments").select("template_id"),Q=new Map;V==null||V.forEach(ie=>{Q.set(ie.template_id,(Q.get(ie.template_id)||0)+1)});const te=new Map;return K==null||K.forEach(ie=>{te.set(ie.template_id,(te.get(ie.template_id)||0)+1)}),(O||[]).map(ie=>({...ie,links:(z||[]).filter(he=>he.template_id===ie.id)||[],likesCount:Q.get(ie.id)||0,commentsCount:te.get(ie.id)||0}))}}),C=j.filter(O=>{var V;const R=O.name.toLowerCase().includes(e.toLowerCase())||((V=O.description)==null?void 0:V.toLowerCase().includes(e.toLowerCase())),z=n==="all"||O.category_id===n,W=o==="all"||O.type_id===o;return R&&z&&W}),P=()=>{r(""),i("all"),c("all")},A=e||n!=="all"||o!=="all",I=O=>{t(`/templates/${O}`)};return s.jsx(Jr,{title:"Canva Templates",children:s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{children:[s.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Canva Templates"}),s.jsx("p",{className:"text-muted-foreground mt-1",children:"Browse and use our collection of professionally designed templates"})]}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[s.jsxs("div",{className:"relative flex-1 max-w-sm",children:[s.jsx(ba,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),s.jsx(Et,{placeholder:"Search templates...",value:e,onChange:O=>r(O.target.value),className:"pl-9"})]}),s.jsxs(Kn,{value:n,onValueChange:i,children:[s.jsx(qn,{className:"w-full sm:w-48",children:s.jsx(Zn,{placeholder:"All Categories"})}),s.jsxs(Hn,{children:[s.jsx(_r,{value:"all",children:"All Categories"}),g.map(O=>s.jsx(_r,{value:O.id,children:O.name},O.id))]})]}),s.jsxs(Kn,{value:o,onValueChange:c,children:[s.jsx(qn,{className:"w-full sm:w-48",children:s.jsx(Zn,{placeholder:"All Types"})}),s.jsxs(Hn,{children:[s.jsx(_r,{value:"all",children:"All Types"}),_.map(O=>s.jsx(_r,{value:O.id,children:O.name},O.id))]})]}),s.jsxs("div",{className:"flex gap-2",children:[A&&s.jsx(de,{variant:"outline",size:"sm",onClick:P,children:"Clear Filters"}),s.jsxs("div",{className:"flex border rounded-md",children:[s.jsx(de,{variant:a==="grid"?"secondary":"ghost",size:"icon",onClick:()=>m("grid"),className:"rounded-r-none",children:s.jsx(tD,{className:"h-4 w-4"})}),s.jsx(de,{variant:a==="list"?"secondary":"ghost",size:"icon",onClick:()=>m("list"),className:"rounded-l-none",children:s.jsx(Aj,{className:"h-4 w-4"})})]})]})]}),s.jsxs("div",{className:"text-sm text-muted-foreground",children:[C.length," template",C.length!==1?"s":""," found"]}),N&&s.jsx("div",{className:a==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-4",children:[...Array(8)].map((O,R)=>s.jsx(at,{children:s.jsxs(ct,{className:"p-4",children:[s.jsx(Dn,{className:"aspect-[4/3] w-full rounded-lg mb-4"}),s.jsx(Dn,{className:"h-5 w-3/4 mb-2"}),s.jsx(Dn,{className:"h-4 w-full mb-4"}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(Dn,{className:"h-5 w-16"}),s.jsx(Dn,{className:"h-5 w-20"})]})]})},R))}),!N&&C.length===0&&s.jsxs("div",{className:"text-center py-12",children:[s.jsx("div",{className:"text-muted-foreground mb-4",children:A?"No templates match your filters":"No templates available yet"}),A&&s.jsx(de,{variant:"outline",onClick:P,children:"Clear Filters"})]}),!N&&C.length>0&&s.jsx("div",{className:a==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-4",children:C.map(O=>s.jsxs(at,{className:`group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer ${a==="list"?"flex flex-row":""}`,onClick:()=>I(O.id),children:[s.jsxs("div",{className:`relative overflow-hidden bg-muted ${a==="list"?"w-48 shrink-0":"aspect-[4/3]"}`,children:[O.preview_image_url?s.jsx("img",{src:O.preview_image_url,alt:O.name,className:"w-full h-full object-contain group-hover:scale-105 transition-transform duration-300"}):s.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:"No Preview"}),O.links.length>1&&s.jsx("div",{className:"absolute top-2 right-2",children:s.jsxs(ir,{variant:"secondary",className:"gap-1 bg-background/90 backdrop-blur-sm",children:[s.jsx(Go,{className:"h-3 w-3"}),O.links.length]})})]}),s.jsxs(ct,{className:`p-4 flex flex-col ${a==="list"?"flex-1":""}`,children:[s.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 mb-1",children:O.name}),O.description&&s.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3 flex-1",children:O.description}),s.jsxs("div",{className:"flex flex-wrap gap-2 mb-3",children:[O.category&&s.jsx(ir,{variant:"secondary",className:"text-xs",children:O.category.name}),O.type&&s.jsx(ir,{variant:"outline",className:"text-xs",children:O.type.name})]}),s.jsxs("div",{className:"flex items-center gap-4 text-sm text-muted-foreground mb-3",children:[s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(Ip,{className:"h-3.5 w-3.5"}),O.likesCount]}),s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(lu,{className:"h-3.5 w-3.5"}),O.commentsCount]})]}),s.jsxs(de,{size:"sm",className:"w-full gap-2",onClick:R=>{R.stopPropagation(),I(O.id)},children:[s.jsx(oa,{className:"h-4 w-4"}),"View Template"]})]})]},O.id))})]})})};var $5e="Separator",fQ="horizontal",U5e=["horizontal","vertical"],qpe=D.forwardRef((t,e)=>{const{decorative:r,orientation:n=fQ,...i}=t,o=V5e(n)?n:fQ,a=r?{role:"none"}:{"aria-orientation":o==="vertical"?o:void 0,role:"separator"};return s.jsx(yn.div,{"data-orientation":o,...a,...i,ref:e})});qpe.displayName=$5e;function V5e(t){return U5e.includes(t)}var Hpe=qpe;const xf=D.forwardRef(({className:t,orientation:e="horizontal",decorative:r=!0,...n},i)=>s.jsx(Hpe,{ref:i,decorative:r,orientation:e,className:ar("shrink-0 bg-border",e==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",t),...n}));xf.displayName=Hpe.displayName;const MT=()=>({trackEngagement:D.useCallback(async(e,r,n,i="view")=>{try{const{data:{user:o}}=await ae.auth.getUser();if(!o)return;await ae.from("content_engagement_logs").insert({user_id:o.id,resource_type:e,resource_id:r,resource_title:n,action_type:i})}catch(o){console.error("Error tracking engagement:",o)}},[])}),q5e=()=>{const{templateId:t}=mu(),{user:e}=rn(),{toast:r}=Ri(),n=Wn(),{trackEngagement:i}=MT(),[o,c]=D.useState(""),{data:a,isLoading:m}=Sr({queryKey:["template-detail",t],queryFn:async()=>{const{data:O,error:R}=await ae.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).eq("id",t).single();if(R)throw R;const{data:z}=await ae.from("template_links").select("*").eq("template_id",t).order("sort_order"),{data:W}=await ae.from("template_guides").select("*").eq("template_id",t).order("sort_order");return{...O,links:z||[],guides:W||[]}},enabled:!!t});D.useEffect(()=>{a&&i("template",a.id,a.name,"view")},[a==null?void 0:a.id]);const{data:g=[]}=Sr({queryKey:["template-likes",t],queryFn:async()=>{const{data:O,error:R}=await ae.from("template_likes").select("*").eq("template_id",t);if(R)throw R;return O},enabled:!!t}),{data:_=[]}=Sr({queryKey:["template-comments",t],queryFn:async()=>{const{data:O,error:R}=await ae.from("template_comments").select("*").eq("template_id",t).order("created_at",{ascending:!1});if(R)throw R;const z=[...new Set(O.map(K=>K.user_id))],{data:W}=await ae.from("profiles").select("id, name").in("id",z),V=new Map((W==null?void 0:W.map(K=>[K.id,K.name]))||[]);return O.map(K=>({...K,user_name:V.get(K.user_id)||"Unknown User"}))},enabled:!!t}),j=zr({mutationFn:async O=>{const{error:R}=await ae.from("template_comments").insert({template_id:t,user_id:e.id,content:O});if(R)throw R},onSuccess:()=>{n.invalidateQueries({queryKey:["template-comments",t]}),c(""),r({title:"Comment added!"})},onError:O=>{r({title:"Error adding comment",description:O.message,variant:"destructive"})}}),N=zr({mutationFn:async O=>{const{error:R}=await ae.from("template_comments").delete().eq("id",O);if(R)throw R},onSuccess:()=>{n.invalidateQueries({queryKey:["template-comments",t]}),r({title:"Comment deleted"})}}),C=zr({mutationFn:async()=>{const O=g.find(R=>R.user_id===(e==null?void 0:e.id));if(O){const{error:R}=await ae.from("template_likes").delete().eq("id",O.id);if(R)throw R}else{const{error:R}=await ae.from("template_likes").insert({template_id:t,user_id:e.id});if(R)throw R}},onSuccess:()=>{n.invalidateQueries({queryKey:["template-likes",t]})}}),P=g.some(O=>O.user_id===(e==null?void 0:e.id)),A=O=>O.split(" ").map(R=>R[0]).join("").toUpperCase().slice(0,2),I=O=>{O.preventDefault(),!(!o.trim()||!e)&&j.mutate(o.trim())};return m?s.jsx(Jr,{title:"Templates",children:s.jsx("div",{className:"flex justify-center py-12",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):a?s.jsx(Jr,{title:a.name,children:s.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[s.jsx(de,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:s.jsxs(jd,{to:"/templates",children:[s.jsx(Ka,{className:"h-4 w-4"}),"Back to Templates"]})}),a.preview_image_url&&s.jsx("div",{className:"relative w-full rounded-lg overflow-hidden bg-muted",children:s.jsx("img",{src:a.preview_image_url,alt:a.name,className:"w-full max-h-[500px] object-contain"})}),a.video_url&&s.jsx(at,{children:s.jsx(ct,{className:"pt-6",children:s.jsx("div",{className:"aspect-video w-full rounded-lg overflow-hidden",children:s.jsx("iframe",{src:a.video_url,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})})}),s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx("h1",{className:"text-2xl font-bold text-foreground",children:a.name}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[a.category&&s.jsx(ir,{variant:"secondary",children:a.category.name}),a.type&&s.jsx(ir,{variant:"outline",children:a.type.name})]})]}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(Wj,{resourceType:"template",resourceId:a.id,resourceTitle:a.name}),s.jsxs(de,{variant:P?"default":"outline",className:"gap-2 w-fit",onClick:()=>C.mutate(),disabled:!e||C.isPending,children:[s.jsx(Ip,{className:`h-4 w-4 ${P?"fill-current":""}`}),g.length," ",g.length===1?"Like":"Likes"]})]})]}),a.description&&s.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:a.description})]}),s.jsx(at,{children:s.jsxs(ct,{className:"pt-6",children:[s.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[s.jsx(Go,{className:"h-4 w-4"}),a.links.length===1?"Template Link":"Template Links"]}),s.jsx("div",{className:"grid gap-2",children:a.links.map(O=>s.jsxs(de,{variant:"outline",className:"w-full justify-between gap-2 h-auto py-3",onClick:()=>{i("template",a.id,a.name,"click_canva"),window.open(O.canva_share_link,"_blank")},children:[s.jsx("span",{className:"font-medium",children:O.title}),s.jsx(oa,{className:"h-4 w-4 text-muted-foreground"})]},O.id))})]})}),a.guides&&a.guides.length>0&&s.jsx(at,{children:s.jsxs(ct,{className:"pt-6",children:[s.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[s.jsx(Ii,{className:"h-4 w-4"}),"Guide Files"]}),s.jsx("div",{className:"grid gap-2",children:a.guides.map(O=>s.jsxs(de,{variant:"outline",className:"w-full justify-between gap-2 h-auto py-3",onClick:()=>{i("template",a.id,a.name,"click_pdf"),window.open(O.file_url,"_blank")},children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Ii,{className:"h-4 w-4 text-muted-foreground"}),s.jsx("span",{className:"font-medium",children:O.name}),O.file_size&&s.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",(O.file_size/1024).toFixed(0)," KB)"]})]}),s.jsx(Pp,{className:"h-4 w-4 text-muted-foreground"})]},O.id))})]})}),s.jsx(xf,{}),s.jsxs("div",{className:"space-y-4",children:[s.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[s.jsx(lu,{className:"h-5 w-5"}),"Comments (",_.length,")"]}),e?s.jsxs("form",{onSubmit:I,className:"flex gap-2",children:[s.jsx(mi,{placeholder:"Add a comment...",value:o,onChange:O=>c(O.target.value),className:"min-h-[80px] resize-none flex-1"}),s.jsx(de,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!o.trim()||j.isPending,children:s.jsx(Dc,{className:"h-4 w-4"})})]}):s.jsx("p",{className:"text-sm text-muted-foreground",children:"Log in to add a comment"}),s.jsx("div",{className:"space-y-4",children:_.length===0?s.jsx(at,{children:s.jsx(ct,{className:"py-8 text-center",children:s.jsx("p",{className:"text-muted-foreground",children:"No comments yet. Be the first to share your thoughts!"})})}):_.map(O=>s.jsx(at,{children:s.jsx(ct,{className:"pt-4 pb-4",children:s.jsxs("div",{className:"flex gap-3",children:[s.jsx(ql,{className:"h-10 w-10 flex-shrink-0",children:s.jsx(Hl,{className:"text-sm",children:A(O.user_name||"U")})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx("span",{className:"font-medium",children:O.user_name}),s.jsx("span",{className:"text-sm text-muted-foreground",children:Bu(new Date(O.created_at),{addSuffix:!0})}),O.user_id===(e==null?void 0:e.id)&&s.jsx(de,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>N.mutate(O.id),children:s.jsx(oi,{className:"h-3 w-3 text-muted-foreground"})})]}),s.jsx("p",{className:"text-sm whitespace-pre-wrap",children:O.content})]})]})})},O.id))})]})]})}):s.jsx(Jr,{title:"Templates",children:s.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[s.jsx(Go,{className:"h-12 w-12 text-muted-foreground mb-4"}),s.jsx("h3",{className:"text-lg font-semibold",children:"Template not found"}),s.jsx("p",{className:"text-muted-foreground mt-1",children:"This template may have been removed or is not available."}),s.jsx(de,{asChild:!0,className:"mt-4",children:s.jsx(jd,{to:"/templates",children:"Back to Templates"})})]})})};var VD="Tabs",[H5e]=Yo(VD,[Uj]),Wpe=Uj(),[W5e,Pq]=H5e(VD),Gpe=D.forwardRef((t,e)=>{const{__scopeTabs:r,value:n,onValueChange:i,defaultValue:o,orientation:c="horizontal",dir:a,activationMode:m="automatic",...g}=t,_=i0(a),[j,N]=Uu({prop:n,onChange:i,defaultProp:o??"",caller:VD});return s.jsx(W5e,{scope:r,baseId:Al(),value:j,onValueChange:N,orientation:c,dir:_,activationMode:m,children:s.jsx(yn.div,{dir:_,"data-orientation":c,...g,ref:e})})});Gpe.displayName=VD;var Kpe="TabsList",Zpe=D.forwardRef((t,e)=>{const{__scopeTabs:r,loop:n=!0,...i}=t,o=Pq(Kpe,r),c=Wpe(r);return s.jsx(R8,{asChild:!0,...c,orientation:o.orientation,dir:o.dir,loop:n,children:s.jsx(yn.div,{role:"tablist","aria-orientation":o.orientation,...i,ref:e})})});Zpe.displayName=Kpe;var Ype="TabsTrigger",Xpe=D.forwardRef((t,e)=>{const{__scopeTabs:r,value:n,disabled:i=!1,...o}=t,c=Pq(Ype,r),a=Wpe(r),m=eme(c.baseId,n),g=tme(c.baseId,n),_=n===c.value;return s.jsx(D8,{asChild:!0,...a,focusable:!i,active:_,children:s.jsx(yn.button,{type:"button",role:"tab","aria-selected":_,"aria-controls":g,"data-state":_?"active":"inactive","data-disabled":i?"":void 0,disabled:i,id:m,...o,ref:e,onMouseDown:Yr(t.onMouseDown,j=>{!i&&j.button===0&&j.ctrlKey===!1?c.onValueChange(n):j.preventDefault()}),onKeyDown:Yr(t.onKeyDown,j=>{[" ","Enter"].includes(j.key)&&c.onValueChange(n)}),onFocus:Yr(t.onFocus,()=>{const j=c.activationMode!=="manual";!_&&!i&&j&&c.onValueChange(n)})})})});Xpe.displayName=Ype;var Qpe="TabsContent",Jpe=D.forwardRef((t,e)=>{const{__scopeTabs:r,value:n,forceMount:i,children:o,...c}=t,a=Pq(Qpe,r),m=eme(a.baseId,n),g=tme(a.baseId,n),_=n===a.value,j=D.useRef(_);return D.useEffect(()=>{const N=requestAnimationFrame(()=>j.current=!1);return()=>cancelAnimationFrame(N)},[]),s.jsx(gl,{present:i||_,children:({present:N})=>s.jsx(yn.div,{"data-state":_?"active":"inactive","data-orientation":a.orientation,role:"tabpanel","aria-labelledby":m,hidden:!N,id:g,tabIndex:0,...c,ref:e,style:{...t.style,animationDuration:j.current?"0s":void 0},children:N&&o})})});Jpe.displayName=Qpe;function eme(t,e){return`${t}-trigger-${e}`}function tme(t,e){return`${t}-content-${e}`}var G5e=Gpe,rme=Zpe,nme=Xpe,sme=Jpe;const go=G5e,ao=D.forwardRef(({className:t,...e},r)=>s.jsx(rme,{ref:r,className:ar("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",t),...e}));ao.displayName=rme.displayName;const Bn=D.forwardRef(({className:t,...e},r)=>s.jsx(nme,{ref:r,className:ar("inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",t),...e}));Bn.displayName=nme.displayName;const xs=D.forwardRef(({className:t,...e},r)=>s.jsx(sme,{ref:r,className:ar("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",t),...e}));xs.displayName=sme.displayName;const K5e=()=>{const{user:t}=rn(),[e,r]=D.useState(""),[n,i]=D.useState("all"),{data:o=[]}=Sr({queryKey:["academy-categories"],queryFn:async()=>{const{data:N,error:C}=await ae.from("academy_categories").select("*").order("sort_order",{ascending:!0});if(C)throw C;return N}}),{data:c=[],isLoading:a}=Sr({queryKey:["academy-videos"],queryFn:async()=>{const{data:N,error:C}=await ae.from("academy_videos").select(` *, category:academy_categories(id, name) `).eq("is_published",!0).order("publish_date",{ascending:!1});if(C)throw C;const{data:P,error:A}=await ae.from("academy_resources").select("*").order("sort_order");if(A)throw A;return N.map(O=>({...O,resources:(P==null?void 0:P.filter(R=>R.video_id===O.id))||[]}))}}),{data:m=[]}=Sr({queryKey:["academy-video-likes"],queryFn:async()=>{const{data:N,error:C}=await ae.from("academy_video_likes").select("video_id, user_id");if(C)throw C;return N}}),g=c.filter(N=>{var A;const C=e===""||N.title.toLowerCase().includes(e.toLowerCase())||((A=N.description)==null?void 0:A.toLowerCase().includes(e.toLowerCase())),P=n==="all"||N.category_id===n;return C&&P}),_=N=>m.filter(C=>C.video_id===N).length,j=N=>m.some(C=>C.video_id===N&&C.user_id===(t==null?void 0:t.id));return s.jsx(Jr,{title:"Academy",children:s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{children:[s.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Academy"}),s.jsx("p",{className:"text-muted-foreground mt-1",children:"On-demand training videos and resources"})]}),s.jsx("div",{className:"flex flex-col sm:flex-row gap-4",children:s.jsxs("div",{className:"relative flex-1",children:[s.jsx(ba,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),s.jsx(Et,{placeholder:"Search videos...",value:e,onChange:N=>r(N.target.value),className:"pl-10"})]})}),s.jsx(go,{value:n,onValueChange:i,children:s.jsxs(ao,{className:"w-full justify-start flex-wrap h-auto gap-2 bg-transparent p-0",children:[s.jsx(Bn,{value:"all",className:"data-[state=active]:bg-primary data-[state=active]:text-primary-foreground",children:"All Videos"}),o.map(N=>s.jsx(Bn,{value:N.id,className:"data-[state=active]:bg-primary data-[state=active]:text-primary-foreground",children:N.name},N.id))]})}),a?s.jsx("div",{className:"flex justify-center py-12",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):g.length===0?s.jsx(at,{children:s.jsxs(ct,{className:"flex flex-col items-center justify-center py-12 text-center",children:[s.jsx(Ia,{className:"h-12 w-12 text-muted-foreground mb-4"}),s.jsx("h3",{className:"text-lg font-semibold",children:"No videos found"}),s.jsx("p",{className:"text-muted-foreground mt-1",children:e?"Try adjusting your search terms":"Check back soon for new content"})]})}):s.jsx("div",{className:"grid gap-6 sm:grid-cols-2 lg:grid-cols-3",children:g.map(N=>s.jsx(jd,{to:`/academy/${N.id}`,children:s.jsxs(at,{className:"overflow-hidden cursor-pointer hover:shadow-lg transition-shadow group h-full",children:[s.jsxs("div",{className:"relative aspect-video bg-muted",children:[N.thumbnail_url?s.jsx("img",{src:N.thumbnail_url,alt:N.title,className:"w-full h-full object-cover"}):s.jsx("div",{className:"w-full h-full flex items-center justify-center",children:s.jsx(Ia,{className:"h-12 w-12 text-muted-foreground"})}),s.jsx("div",{className:"absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center",children:s.jsx("div",{className:"w-16 h-16 rounded-full bg-primary/90 flex items-center justify-center",children:s.jsx(Sf,{className:"h-8 w-8 text-primary-foreground ml-1"})})}),N.duration&&s.jsxs("div",{className:"absolute bottom-2 right-2 bg-black/70 text-white text-xs px-2 py-1 rounded flex items-center gap-1",children:[s.jsx(No,{className:"h-3 w-3"}),N.duration]})]}),s.jsxs(xr,{className:"pb-2",children:[s.jsx("div",{className:"flex items-start justify-between gap-2",children:s.jsx(wr,{className:"text-lg line-clamp-2",children:N.title})}),N.category&&s.jsx(ir,{variant:"secondary",className:"w-fit",children:N.category.name})]}),s.jsxs(ct,{className:"pt-0",children:[N.description&&s.jsx(us,{className:"line-clamp-2",children:N.description}),s.jsxs("div",{className:"flex items-center gap-4 mt-3 text-sm text-muted-foreground",children:[s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(Ip,{className:`h-4 w-4 ${j(N.id)?"fill-primary text-primary":""}`}),_(N.id)]}),N.resources&&N.resources.length>0&&s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(Ii,{className:"h-4 w-4"}),N.resources.length]})]})]})]})},N.id))})]})})},Z5e=(t,e)=>{if(e==="bunny_stream"){let r=t.replace("iframe.mediadelivery.net","player.mediadelivery.net");return r.includes("?")||(r+="?autoplay=false&loop=false&muted=false&preload=true&responsive=true"),r}if(e==="youtube"){const r=/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/,n=t.match(r);if(n)return`https://www.youtube.com/embed/${n[1]}`}if(e==="vimeo"){const r=/vimeo\.com\/(?:video\/)?(\d+)/,n=t.match(r);if(n)return`https://player.vimeo.com/video/${n[1]}`}if(e==="loom"){const r=/loom\.com\/share\/([a-zA-Z0-9]+)/,n=t.match(r);if(n)return`https://www.loom.com/embed/${n[1]}`}return t},Y5e=()=>{const{videoId:t}=mu();Bs();const{user:e}=rn(),{toast:r}=Ri(),n=Wn(),{trackEngagement:i}=MT(),[o,c]=D.useState(""),{data:a,isLoading:m}=Sr({queryKey:["academy-video",t],queryFn:async()=>{const{data:R,error:z}=await ae.from("academy_videos").select(` *, category:academy_categories(id, name) `).eq("id",t).eq("is_published",!0).single();if(z)throw z;const{data:W}=await ae.from("academy_resources").select("*").eq("video_id",t).order("sort_order");return{...R,resources:W||[]}},enabled:!!t});D.useEffect(()=>{a&&i("academy_video",a.id,a.title,"view")},[a==null?void 0:a.id]);const{data:g=[]}=Sr({queryKey:["academy-video-likes",t],queryFn:async()=>{const{data:R,error:z}=await ae.from("academy_video_likes").select("*").eq("video_id",t);if(z)throw z;return R},enabled:!!t}),{data:_=[]}=Sr({queryKey:["academy-video-comments",t],queryFn:async()=>{const{data:R,error:z}=await ae.from("academy_video_comments").select("*").eq("video_id",t).order("created_at",{ascending:!1});if(z)throw z;const W=[...new Set(R.map(Q=>Q.user_id))],{data:V}=await ae.from("profiles").select("id, name").in("id",W),K=new Map((V==null?void 0:V.map(Q=>[Q.id,Q.name]))||[]);return R.map(Q=>({...Q,user_name:K.get(Q.user_id)||"Unknown User"}))},enabled:!!t}),j=zr({mutationFn:async R=>{const{error:z}=await ae.from("academy_video_comments").insert({video_id:t,user_id:e.id,content:R});if(z)throw z},onSuccess:()=>{n.invalidateQueries({queryKey:["academy-video-comments",t]}),c(""),r({title:"Comment added!"})},onError:R=>{r({title:"Error adding comment",description:R.message,variant:"destructive"})}}),N=zr({mutationFn:async R=>{const{error:z}=await ae.from("academy_video_comments").delete().eq("id",R);if(z)throw z},onSuccess:()=>{n.invalidateQueries({queryKey:["academy-video-comments",t]}),r({title:"Comment deleted"})}}),C=zr({mutationFn:async()=>{const R=g.find(z=>z.user_id===(e==null?void 0:e.id));if(R){const{error:z}=await ae.from("academy_video_likes").delete().eq("id",R.id);if(z)throw z}else{const{error:z}=await ae.from("academy_video_likes").insert({video_id:t,user_id:e.id});if(z)throw z}},onSuccess:()=>{n.invalidateQueries({queryKey:["academy-video-likes",t]})}}),P=g.some(R=>R.user_id===(e==null?void 0:e.id)),A=R=>{switch(R==null?void 0:R.toLowerCase()){case"pdf":return"📄";case"pptx":case"ppt":return"📊";case"xlsx":case"xls":return"📈";case"docx":case"doc":return"📝";case"zip":return"📦";default:return"📁"}},I=R=>R.split(" ").map(z=>z[0]).join("").toUpperCase().slice(0,2),O=R=>{R.preventDefault(),!(!o.trim()||!e)&&j.mutate(o.trim())};return m?s.jsx(Jr,{title:"Academy",children:s.jsx("div",{className:"flex justify-center py-12",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):a?s.jsx(Jr,{title:a.title,children:s.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[s.jsx(de,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:s.jsxs(jd,{to:"/academy",children:[s.jsx(Ka,{className:"h-4 w-4"}),"Back to Academy"]})}),s.jsx("div",{className:"relative w-full rounded-lg overflow-hidden bg-black",style:{paddingTop:"56.25%"},children:["youtube","vimeo","loom","bunny_stream"].includes(a.video_type)?s.jsx("iframe",{src:Z5e(a.video_url,a.video_type),loading:"lazy",style:{border:0,position:"absolute",top:0,left:0,height:"100%",width:"100%"},allow:"accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture",allowFullScreen:!0}):s.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center text-white gap-4",children:[s.jsx(Ia,{className:"h-16 w-16 opacity-50"}),s.jsx(de,{variant:"secondary",asChild:!0,children:s.jsxs("a",{href:a.video_url,target:"_blank",rel:"noopener noreferrer",className:"gap-2",children:[s.jsx(oa,{className:"h-4 w-4"}),"Open Video"]})})]})}),s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx("h1",{className:"text-2xl font-bold text-foreground",children:a.title}),a.category&&s.jsx(ir,{variant:"secondary",children:a.category.name})]}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(Wj,{resourceType:"academy_video",resourceId:a.id,resourceTitle:a.title}),s.jsxs(de,{variant:P?"default":"outline",className:"gap-2 w-fit",onClick:()=>C.mutate(),disabled:!e||C.isPending,children:[s.jsx(Ip,{className:`h-4 w-4 ${P?"fill-current":""}`}),g.length," ",g.length===1?"Like":"Likes"]})]})]}),a.description&&s.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:a.description})]}),a.resources&&a.resources.length>0&&s.jsx(at,{children:s.jsxs(ct,{className:"pt-6",children:[s.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[s.jsx(Ii,{className:"h-4 w-4"}),"Resources"]}),s.jsx("div",{className:"grid gap-2",children:a.resources.map(R=>s.jsxs("a",{href:R.file_url,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-3 p-3 rounded-lg border hover:bg-muted transition-colors",children:[s.jsx("span",{className:"text-2xl",children:A(R.file_type)}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("p",{className:"font-medium truncate",children:R.title}),s.jsx("p",{className:"text-xs text-muted-foreground uppercase",children:R.file_type})]}),s.jsx(Pp,{className:"h-4 w-4 text-muted-foreground"})]},R.id))})]})}),s.jsx(xf,{}),s.jsxs("div",{className:"space-y-4",children:[s.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[s.jsx(lu,{className:"h-5 w-5"}),"Comments (",_.length,")"]}),e?s.jsxs("form",{onSubmit:O,className:"flex gap-2",children:[s.jsx(mi,{placeholder:"Add a comment...",value:o,onChange:R=>c(R.target.value),className:"min-h-[80px] resize-none flex-1"}),s.jsx(de,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!o.trim()||j.isPending,children:s.jsx(Dc,{className:"h-4 w-4"})})]}):s.jsx("p",{className:"text-sm text-muted-foreground",children:"Log in to add a comment"}),s.jsx("div",{className:"space-y-4",children:_.length===0?s.jsx(at,{children:s.jsx(ct,{className:"py-8 text-center",children:s.jsx("p",{className:"text-muted-foreground",children:"No comments yet. Be the first to share your thoughts!"})})}):_.map(R=>s.jsx(at,{children:s.jsx(ct,{className:"pt-4 pb-4",children:s.jsxs("div",{className:"flex gap-3",children:[s.jsx(ql,{className:"h-10 w-10 flex-shrink-0",children:s.jsx(Hl,{className:"text-sm",children:I(R.user_name||"U")})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx("span",{className:"font-medium",children:R.user_name}),s.jsx("span",{className:"text-sm text-muted-foreground",children:Bu(new Date(R.created_at),{addSuffix:!0})}),R.user_id===(e==null?void 0:e.id)&&s.jsx(de,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>N.mutate(R.id),children:s.jsx(oi,{className:"h-3 w-3 text-muted-foreground"})})]}),s.jsx("p",{className:"text-sm whitespace-pre-wrap",children:R.content})]})]})})},R.id))})]})]})}):s.jsx(Jr,{title:"Academy",children:s.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[s.jsx(Ia,{className:"h-12 w-12 text-muted-foreground mb-4"}),s.jsx("h3",{className:"text-lg font-semibold",children:"Video not found"}),s.jsx("p",{className:"text-muted-foreground mt-1",children:"This video may have been removed or is not available."}),s.jsx(de,{asChild:!0,className:"mt-4",children:s.jsx(jd,{to:"/academy",children:"Back to Academy"})})]})})};function X5e(){const t=Bs(),[e,r]=D.useState(""),{data:n,isLoading:i}=Sr({queryKey:["resource-kits-published"],queryFn:async()=>{const{data:C,error:P}=await ae.from("resource_kits").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(P)throw P;return C}}),{data:o}=Sr({queryKey:["resource-kit-files-all"],queryFn:async()=>{const{data:C,error:P}=await ae.from("resource_kit_files").select("*").order("sort_order",{ascending:!0});if(P)throw P;return C}}),{data:c}=Sr({queryKey:["resource-kit-likes-all"],queryFn:async()=>{const{data:C,error:P}=await ae.from("resource_kit_likes").select("kit_id");if(P)throw P;return C}}),{data:a}=Sr({queryKey:["resource-kit-comments-all"],queryFn:async()=>{const{data:C,error:P}=await ae.from("resource_kit_comments").select("kit_id");if(P)throw P;return C}}),m=n==null?void 0:n.filter(C=>{var P;return C.name.toLowerCase().includes(e.toLowerCase())||((P=C.description)==null?void 0:P.toLowerCase().includes(e.toLowerCase()))}),g=C=>(o==null?void 0:o.filter(P=>P.kit_id===C))||[],_=C=>(c==null?void 0:c.filter(P=>P.kit_id===C).length)||0,j=C=>(a==null?void 0:a.filter(P=>P.kit_id===C).length)||0,N=C=>{t(`/toolbox/${C}`)};return s.jsx(Jr,{title:"Toolbox",description:"Download resource kits and tools to help grow your business",children:s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"relative max-w-md",children:[s.jsx(ba,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),s.jsx(Et,{placeholder:"Search resource kits...",value:e,onChange:C=>r(C.target.value),className:"pl-10"})]}),!i&&s.jsxs("p",{className:"text-sm text-muted-foreground",children:[(m==null?void 0:m.length)||0," resource kit",(m==null?void 0:m.length)!==1?"s":""," available"]}),i?s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:[...Array(8)].map((C,P)=>s.jsx(at,{children:s.jsxs(ct,{className:"p-4",children:[s.jsx(Dn,{className:"aspect-[4/3] w-full rounded-lg mb-4"}),s.jsx(Dn,{className:"h-5 w-3/4 mb-2"}),s.jsx(Dn,{className:"h-4 w-full mb-4"}),s.jsx(Dn,{className:"h-4 w-2/3"})]})},P))}):(m==null?void 0:m.length)===0?s.jsxs(at,{className:"p-12 text-center",children:[s.jsx(O1,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),s.jsx("h3",{className:"text-lg font-medium mb-2",children:"No resource kits found"}),s.jsx("p",{className:"text-muted-foreground",children:e?"Try adjusting your search terms":"Check back later for new resources"})]}):s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:m==null?void 0:m.map(C=>{const P=g(C.id).length,A=_(C.id),I=j(C.id);return s.jsxs(at,{className:"group overflow-hidden cursor-pointer hover:shadow-lg transition-all duration-200",onClick:()=>N(C.id),children:[s.jsx("div",{className:"relative overflow-hidden bg-muted aspect-[4/3]",children:C.featured_image_url?s.jsx("img",{src:C.featured_image_url,alt:C.name,className:"w-full h-full object-contain group-hover:scale-105 transition-transform duration-300"}):s.jsx("div",{className:"w-full h-full flex items-center justify-center",children:s.jsx(O1,{className:"h-16 w-16 text-muted-foreground"})})}),s.jsxs(ct,{className:"p-4",children:[s.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 mb-1",children:C.name}),C.description&&s.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3",children:C.description}),s.jsxs("div",{className:"flex items-center justify-between text-sm text-muted-foreground",children:[s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(Ii,{className:"h-4 w-4"}),P," file",P!==1?"s":""]}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(Ip,{className:"h-3.5 w-3.5"}),A]}),s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(lu,{className:"h-3.5 w-3.5"}),I]})]})]})]})]},C.id)})})]})})}const Q5e=()=>{const{kitId:t}=mu(),{user:e}=rn(),{toast:r}=Ri(),n=Wn(),{trackEngagement:i}=MT(),[o,c]=D.useState(""),{data:a,isLoading:m}=Sr({queryKey:["resource-kit-detail",t],queryFn:async()=>{const{data:R,error:z}=await ae.from("resource_kits").select("*").eq("id",t).eq("is_published",!0).single();if(z)throw z;const{data:W}=await ae.from("resource_kit_files").select("*").eq("kit_id",t).order("sort_order"),{data:V}=await ae.from("resource_kit_links").select("*").eq("kit_id",t).order("sort_order");return{...R,files:W||[],links:V||[]}},enabled:!!t});D.useEffect(()=>{a&&i("toolbox",a.id,a.name,"view")},[a==null?void 0:a.id]);const{data:g=[]}=Sr({queryKey:["resource-kit-likes",t],queryFn:async()=>{const{data:R,error:z}=await ae.from("resource_kit_likes").select("*").eq("kit_id",t);if(z)throw z;return R},enabled:!!t}),{data:_=[]}=Sr({queryKey:["resource-kit-comments",t],queryFn:async()=>{const{data:R,error:z}=await ae.from("resource_kit_comments").select("*").eq("kit_id",t).order("created_at",{ascending:!1});if(z)throw z;const W=[...new Set(R.map(Q=>Q.user_id))],{data:V}=await ae.from("profiles").select("id, name").in("id",W),K=new Map((V==null?void 0:V.map(Q=>[Q.id,Q.name]))||[]);return R.map(Q=>({...Q,user_name:K.get(Q.user_id)||"Unknown User"}))},enabled:!!t}),j=zr({mutationFn:async R=>{const{error:z}=await ae.from("resource_kit_comments").insert({kit_id:t,user_id:e.id,content:R});if(z)throw z},onSuccess:()=>{n.invalidateQueries({queryKey:["resource-kit-comments",t]}),c(""),r({title:"Comment added!"})},onError:R=>{r({title:"Error adding comment",description:R.message,variant:"destructive"})}}),N=zr({mutationFn:async R=>{const{error:z}=await ae.from("resource_kit_comments").delete().eq("id",R);if(z)throw z},onSuccess:()=>{n.invalidateQueries({queryKey:["resource-kit-comments",t]}),r({title:"Comment deleted"})}}),C=zr({mutationFn:async()=>{const R=g.find(z=>z.user_id===(e==null?void 0:e.id));if(R){const{error:z}=await ae.from("resource_kit_likes").delete().eq("id",R.id);if(z)throw z}else{const{error:z}=await ae.from("resource_kit_likes").insert({kit_id:t,user_id:e.id});if(z)throw z}},onSuccess:()=>{n.invalidateQueries({queryKey:["resource-kit-likes",t]})}}),P=g.some(R=>R.user_id===(e==null?void 0:e.id)),A=R=>R.split(" ").map(z=>z[0]).join("").toUpperCase().slice(0,2),I=R=>R?R<1024?R+" B":R<1024*1024?(R/1024).toFixed(1)+" KB":(R/(1024*1024)).toFixed(1)+" MB":"",O=R=>{R.preventDefault(),!(!o.trim()||!e)&&j.mutate(o.trim())};return m?s.jsx(Jr,{title:"Toolbox",children:s.jsx("div",{className:"flex justify-center py-12",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):a?s.jsx(Jr,{title:a.name,children:s.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[s.jsx(de,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:s.jsxs(jd,{to:"/toolbox",children:[s.jsx(Ka,{className:"h-4 w-4"}),"Back to Toolbox"]})}),a.featured_image_url&&s.jsx("div",{className:"relative w-full rounded-lg overflow-hidden bg-muted",children:s.jsx("img",{src:a.featured_image_url,alt:a.name,className:"w-full max-h-[400px] object-cover"})}),s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4",children:[s.jsx("div",{className:"space-y-2",children:s.jsx("h1",{className:"text-2xl font-bold text-foreground",children:a.name})}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(Wj,{resourceType:"resource_kit",resourceId:a.id,resourceTitle:a.name}),s.jsxs(de,{variant:P?"default":"outline",className:"gap-2 w-fit",onClick:()=>C.mutate(),disabled:!e||C.isPending,children:[s.jsx(Ip,{className:`h-4 w-4 ${P?"fill-current":""}`}),g.length," ",g.length===1?"Like":"Likes"]})]})]}),a.description&&s.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:a.description})]}),a.files&&a.files.length>0&&s.jsx(at,{children:s.jsxs(ct,{className:"pt-6",children:[s.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[s.jsx(Ii,{className:"h-4 w-4"}),"Included Resources (",a.files.length,")"]}),s.jsx("div",{className:"grid gap-2",children:a.files.map(R=>s.jsxs("a",{href:R.file_url,target:"_blank",rel:"noopener noreferrer",onClick:()=>i("toolbox",a.id,a.name,"click_pdf"),className:"flex items-center justify-between p-3 rounded-lg border hover:bg-muted transition-colors group",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"p-2 rounded-md bg-primary/10",children:s.jsx(Ii,{className:"h-4 w-4 text-primary"})}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-sm",children:R.name}),R.file_size&&s.jsx("div",{className:"text-xs text-muted-foreground",children:I(R.file_size)})]})]}),s.jsx(Pp,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors"})]},R.id))})]})}),a.links&&a.links.length>0&&s.jsx(at,{children:s.jsxs(ct,{className:"pt-6",children:[s.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[s.jsx(oa,{className:"h-4 w-4"}),"Canva Templates (",a.links.length,")"]}),s.jsx("div",{className:"grid gap-2",children:a.links.map(R=>s.jsxs("a",{href:R.canva_share_link,target:"_blank",rel:"noopener noreferrer",onClick:()=>i("toolbox",a.id,a.name,"click_canva"),className:"flex items-center justify-between p-3 rounded-lg border hover:bg-muted transition-colors group",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"p-2 rounded-md bg-purple-500/10",children:s.jsx(oa,{className:"h-4 w-4 text-purple-600"})}),s.jsx("div",{className:"font-medium text-sm",children:R.title})]}),s.jsx("span",{className:"text-xs text-muted-foreground group-hover:text-primary transition-colors",children:"Open in Canva"})]},R.id))})]})}),s.jsx(xf,{}),s.jsxs("div",{className:"space-y-4",children:[s.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[s.jsx(lu,{className:"h-5 w-5"}),"Comments (",_.length,")"]}),e?s.jsxs("form",{onSubmit:O,className:"flex gap-2",children:[s.jsx(mi,{placeholder:"Add a comment...",value:o,onChange:R=>c(R.target.value),className:"min-h-[80px] resize-none flex-1"}),s.jsx(de,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!o.trim()||j.isPending,children:s.jsx(Dc,{className:"h-4 w-4"})})]}):s.jsx("p",{className:"text-sm text-muted-foreground",children:"Log in to add a comment"}),s.jsx("div",{className:"space-y-4",children:_.length===0?s.jsx(at,{children:s.jsx(ct,{className:"py-8 text-center",children:s.jsx("p",{className:"text-muted-foreground",children:"No comments yet. Be the first to share your thoughts!"})})}):_.map(R=>s.jsx(at,{children:s.jsx(ct,{className:"pt-4 pb-4",children:s.jsxs("div",{className:"flex gap-3",children:[s.jsx(ql,{className:"h-10 w-10 flex-shrink-0",children:s.jsx(Hl,{className:"text-sm",children:A(R.user_name||"U")})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx("span",{className:"font-medium",children:R.user_name}),s.jsx("span",{className:"text-sm text-muted-foreground",children:Bu(new Date(R.created_at),{addSuffix:!0})}),R.user_id===(e==null?void 0:e.id)&&s.jsx(de,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>N.mutate(R.id),children:s.jsx(oi,{className:"h-3 w-3 text-muted-foreground"})})]}),s.jsx("p",{className:"text-sm whitespace-pre-wrap",children:R.content})]})]})})},R.id))})]})]})}):s.jsx(Jr,{title:"Toolbox",children:s.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[s.jsx(O1,{className:"h-12 w-12 text-muted-foreground mb-4"}),s.jsx("h3",{className:"text-lg font-semibold",children:"Resource kit not found"}),s.jsx("p",{className:"text-muted-foreground mt-1",children:"This resource kit may have been removed or is not available."}),s.jsx(de,{asChild:!0,className:"mt-4",children:s.jsx(jd,{to:"/toolbox",children:"Back to Toolbox"})})]})})},J5e=()=>{const t=Bs(),[e,r]=D.useState(""),[n,i]=D.useState("grid"),{data:o=[],isLoading:c}=Sr({queryKey:["social-swag"],queryFn:async()=>{const{data:g,error:_}=await ae.from("social_swag").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(_)throw _;const{data:j,error:N}=await ae.from("social_swag_links").select("*").order("sort_order");if(N)throw N;const{data:C}=await ae.from("social_swag_likes").select("swag_id"),{data:P}=await ae.from("social_swag_comments").select("swag_id"),A=new Map;C==null||C.forEach(R=>{A.set(R.swag_id,(A.get(R.swag_id)||0)+1)});const I=new Map;return P==null||P.forEach(R=>{I.set(R.swag_id,(I.get(R.swag_id)||0)+1)}),(g||[]).map(R=>({...R,links:(j||[]).filter(z=>z.swag_id===R.id)||[],likesCount:A.get(R.id)||0,commentsCount:I.get(R.id)||0}))}}),a=o.filter(g=>{var j;return g.title.toLowerCase().includes(e.toLowerCase())||((j=g.description)==null?void 0:j.toLowerCase().includes(e.toLowerCase()))}),m=g=>{t(`/social-swag/${g}`)};return s.jsx(Jr,{title:"Social Swag",children:s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{children:[s.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Social Swag"}),s.jsx("p",{className:"text-muted-foreground mt-1",children:"Browse our collection of social media content and graphics"})]}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[s.jsxs("div",{className:"relative flex-1 max-w-sm",children:[s.jsx(ba,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),s.jsx(Et,{placeholder:"Search social swag...",value:e,onChange:g=>r(g.target.value),className:"pl-9"})]}),s.jsxs("div",{className:"flex gap-2",children:[e&&s.jsx(de,{variant:"outline",size:"sm",onClick:()=>r(""),children:"Clear"}),s.jsxs("div",{className:"flex border rounded-md",children:[s.jsx(de,{variant:n==="grid"?"secondary":"ghost",size:"icon",onClick:()=>i("grid"),className:"rounded-r-none",children:s.jsx(tD,{className:"h-4 w-4"})}),s.jsx(de,{variant:n==="list"?"secondary":"ghost",size:"icon",onClick:()=>i("list"),className:"rounded-l-none",children:s.jsx(Aj,{className:"h-4 w-4"})})]})]})]}),s.jsxs("div",{className:"text-sm text-muted-foreground",children:[a.length," item",a.length!==1?"s":""," found"]}),c&&s.jsx("div",{className:n==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-4",children:[...Array(8)].map((g,_)=>s.jsx(at,{children:s.jsxs(ct,{className:"p-4",children:[s.jsx(Dn,{className:"aspect-[4/3] w-full rounded-lg mb-4"}),s.jsx(Dn,{className:"h-5 w-3/4 mb-2"}),s.jsx(Dn,{className:"h-4 w-full mb-4"})]})},_))}),!c&&a.length===0&&s.jsxs("div",{className:"text-center py-12",children:[s.jsx("div",{className:"text-muted-foreground mb-4",children:e?"No items match your search":"No social swag available yet"}),e&&s.jsx(de,{variant:"outline",onClick:()=>r(""),children:"Clear Search"})]}),!c&&a.length>0&&s.jsx("div",{className:n==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-4",children:a.map(g=>s.jsxs(at,{className:`group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer ${n==="list"?"flex flex-row":""}`,onClick:()=>m(g.id),children:[s.jsxs("div",{className:`relative overflow-hidden bg-muted ${n==="list"?"w-48 shrink-0":"aspect-[4/3]"}`,children:[g.preview_image_url?s.jsx("img",{src:g.preview_image_url,alt:g.title,className:"w-full h-full object-contain group-hover:scale-105 transition-transform duration-300"}):s.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:"No Preview"}),g.links.length>1&&s.jsx("div",{className:"absolute top-2 right-2",children:s.jsxs(ir,{variant:"secondary",className:"gap-1 bg-background/90 backdrop-blur-sm",children:[s.jsx(Go,{className:"h-3 w-3"}),g.links.length]})})]}),s.jsxs(ct,{className:`p-4 flex flex-col ${n==="list"?"flex-1":""}`,children:[s.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 mb-1",children:g.title}),g.description&&s.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3 flex-1",children:g.description}),s.jsxs("div",{className:"flex items-center gap-4 text-sm text-muted-foreground mb-3",children:[s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(Ip,{className:"h-3.5 w-3.5"}),g.likesCount]}),s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(lu,{className:"h-3.5 w-3.5"}),g.commentsCount]})]}),s.jsxs(de,{size:"sm",className:"w-full gap-2",onClick:_=>{_.stopPropagation(),m(g.id)},children:[s.jsx(oa,{className:"h-4 w-4"}),"View Details"]})]})]},g.id))})]})})},e$e=()=>{const{swagId:t}=mu(),{user:e}=rn(),{toast:r}=Ri(),n=Wn(),{trackEngagement:i}=MT(),[o,c]=D.useState(""),{data:a,isLoading:m}=Sr({queryKey:["social-swag-detail",t],queryFn:async()=>{const{data:O,error:R}=await ae.from("social_swag").select("*").eq("id",t).single();if(R)throw R;const{data:z}=await ae.from("social_swag_links").select("*").eq("swag_id",t).order("sort_order");return{...O,links:z||[]}},enabled:!!t});D.useEffect(()=>{a&&i("social_swag",a.id,a.title,"view")},[a==null?void 0:a.id]);const{data:g=[]}=Sr({queryKey:["social-swag-likes",t],queryFn:async()=>{const{data:O,error:R}=await ae.from("social_swag_likes").select("*").eq("swag_id",t);if(R)throw R;return O},enabled:!!t}),{data:_=[]}=Sr({queryKey:["social-swag-comments",t],queryFn:async()=>{const{data:O,error:R}=await ae.from("social_swag_comments").select("*").eq("swag_id",t).order("created_at",{ascending:!1});if(R)throw R;const z=[...new Set(O.map(K=>K.user_id))],{data:W}=await ae.from("profiles").select("id, name").in("id",z),V=new Map((W==null?void 0:W.map(K=>[K.id,K.name]))||[]);return O.map(K=>({...K,user_name:V.get(K.user_id)||"Unknown User"}))},enabled:!!t}),j=zr({mutationFn:async O=>{const{error:R}=await ae.from("social_swag_comments").insert({swag_id:t,user_id:e.id,content:O});if(R)throw R},onSuccess:()=>{n.invalidateQueries({queryKey:["social-swag-comments",t]}),c(""),r({title:"Comment added!"})},onError:O=>{r({title:"Error adding comment",description:O.message,variant:"destructive"})}}),N=zr({mutationFn:async O=>{const{error:R}=await ae.from("social_swag_comments").delete().eq("id",O);if(R)throw R},onSuccess:()=>{n.invalidateQueries({queryKey:["social-swag-comments",t]}),r({title:"Comment deleted"})}}),C=zr({mutationFn:async()=>{const O=g.find(R=>R.user_id===(e==null?void 0:e.id));if(O){const{error:R}=await ae.from("social_swag_likes").delete().eq("id",O.id);if(R)throw R}else{const{error:R}=await ae.from("social_swag_likes").insert({swag_id:t,user_id:e.id});if(R)throw R}},onSuccess:()=>{n.invalidateQueries({queryKey:["social-swag-likes",t]})}}),P=g.some(O=>O.user_id===(e==null?void 0:e.id)),A=O=>O.split(" ").map(R=>R[0]).join("").toUpperCase().slice(0,2),I=O=>{O.preventDefault(),!(!o.trim()||!e)&&j.mutate(o.trim())};return m?s.jsx(Jr,{title:"Social Swag",children:s.jsx("div",{className:"flex justify-center py-12",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):a?s.jsx(Jr,{title:a.title,children:s.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[s.jsx(de,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:s.jsxs(jd,{to:"/social-swag",children:[s.jsx(Ka,{className:"h-4 w-4"}),"Back to Social Swag"]})}),a.preview_image_url&&s.jsx("div",{className:"relative w-full rounded-lg overflow-hidden bg-muted",children:s.jsx("img",{src:a.preview_image_url,alt:a.title,className:"w-full max-h-[500px] object-contain"})}),s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4",children:[s.jsx("div",{className:"space-y-2",children:s.jsx("h1",{className:"text-2xl font-bold text-foreground",children:a.title})}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(Wj,{resourceType:"social_swag",resourceId:a.id,resourceTitle:a.title}),s.jsxs(de,{variant:P?"default":"outline",className:"gap-2 w-fit",onClick:()=>C.mutate(),disabled:!e||C.isPending,children:[s.jsx(Ip,{className:`h-4 w-4 ${P?"fill-current":""}`}),g.length," ",g.length===1?"Like":"Likes"]})]})]}),a.description&&s.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:a.description})]}),a.links.length>0&&s.jsx(at,{children:s.jsxs(ct,{className:"pt-6",children:[s.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[s.jsx(Go,{className:"h-4 w-4"}),a.links.length===1?"Canva Link":"Canva Links"]}),s.jsx("div",{className:"grid gap-2",children:a.links.map(O=>s.jsxs(de,{variant:"outline",className:"w-full justify-between gap-2 h-auto py-3",onClick:()=>{i("social_swag",a.id,a.title,"click_canva"),window.open(O.canva_share_link,"_blank")},children:[s.jsx("span",{className:"font-medium",children:O.title}),s.jsx(oa,{className:"h-4 w-4 text-muted-foreground"})]},O.id))})]})}),s.jsx(xf,{}),s.jsxs("div",{className:"space-y-4",children:[s.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[s.jsx(lu,{className:"h-5 w-5"}),"Comments (",_.length,")"]}),e?s.jsxs("form",{onSubmit:I,className:"flex gap-2",children:[s.jsx(mi,{placeholder:"Add a comment...",value:o,onChange:O=>c(O.target.value),className:"min-h-[80px] resize-none flex-1"}),s.jsx(de,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!o.trim()||j.isPending,children:s.jsx(Dc,{className:"h-4 w-4"})})]}):s.jsx("p",{className:"text-sm text-muted-foreground",children:"Log in to add a comment"}),s.jsx("div",{className:"space-y-4",children:_.length===0?s.jsx(at,{children:s.jsx(ct,{className:"py-8 text-center",children:s.jsx("p",{className:"text-muted-foreground",children:"No comments yet. Be the first to share your thoughts!"})})}):_.map(O=>s.jsx(at,{children:s.jsx(ct,{className:"pt-4 pb-4",children:s.jsxs("div",{className:"flex gap-3",children:[s.jsx(ql,{className:"h-10 w-10 flex-shrink-0",children:s.jsx(Hl,{className:"text-sm",children:A(O.user_name||"U")})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx("span",{className:"font-medium",children:O.user_name}),s.jsx("span",{className:"text-sm text-muted-foreground",children:Bu(new Date(O.created_at),{addSuffix:!0})}),O.user_id===(e==null?void 0:e.id)&&s.jsx(de,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>N.mutate(O.id),children:s.jsx(oi,{className:"h-3 w-3 text-muted-foreground"})})]}),s.jsx("p",{className:"text-sm whitespace-pre-wrap",children:O.content})]})]})})},O.id))})]})]})}):s.jsx(Jr,{title:"Social Swag",children:s.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[s.jsx(Go,{className:"h-12 w-12 text-muted-foreground mb-4"}),s.jsx("h3",{className:"text-lg font-semibold",children:"Item not found"}),s.jsx("p",{className:"text-muted-foreground mt-1",children:"This item may have been removed or is not available."}),s.jsx(de,{asChild:!0,className:"mt-4",children:s.jsx(jd,{to:"/social-swag",children:"Back to Social Swag"})})]})})};var qD="Popover",[ime]=Yo(qD,[gx]),OT=gx(),[t$e,jx]=ime(qD),ame=t=>{const{__scopePopover:e,children:r,open:n,defaultOpen:i,onOpenChange:o,modal:c=!1}=t,a=OT(e),m=D.useRef(null),[g,_]=D.useState(!1),[j,N]=Uu({prop:n,defaultProp:i??!1,onChange:o,caller:qD});return s.jsx(aD,{...a,children:s.jsx(t$e,{scope:e,contentId:Al(),triggerRef:m,open:j,onOpenChange:N,onOpenToggle:D.useCallback(()=>N(C=>!C),[N]),hasCustomAnchor:g,onCustomAnchorAdd:D.useCallback(()=>_(!0),[]),onCustomAnchorRemove:D.useCallback(()=>_(!1),[]),modal:c,children:r})})};ame.displayName=qD;var ome="PopoverAnchor",r$e=D.forwardRef((t,e)=>{const{__scopePopover:r,...n}=t,i=jx(ome,r),o=OT(r),{onCustomAnchorAdd:c,onCustomAnchorRemove:a}=i;return D.useEffect(()=>(c(),()=>a()),[c,a]),s.jsx(bT,{...o,...n,ref:e})});r$e.displayName=ome;var lme="PopoverTrigger",cme=D.forwardRef((t,e)=>{const{__scopePopover:r,...n}=t,i=jx(lme,r),o=OT(r),c=vs(e,i.triggerRef),a=s.jsx(yn.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":pme(i.open),...n,ref:c,onClick:Yr(t.onClick,i.onOpenToggle)});return i.hasCustomAnchor?a:s.jsx(bT,{asChild:!0,...o,children:a})});cme.displayName=lme;var Iq="PopoverPortal",[n$e,s$e]=ime(Iq,{forceMount:void 0}),ume=t=>{const{__scopePopover:e,forceMount:r,children:n,container:i}=t,o=jx(Iq,e);return s.jsx(n$e,{scope:e,forceMount:r,children:s.jsx(gl,{present:r||o.open,children:s.jsx(Tj,{asChild:!0,container:i,children:n})})})};ume.displayName=Iq;var Z1="PopoverContent",dme=D.forwardRef((t,e)=>{const r=s$e(Z1,t.__scopePopover),{forceMount:n=r.forceMount,...i}=t,o=jx(Z1,t.__scopePopover);return s.jsx(gl,{present:n||o.open,children:o.modal?s.jsx(a$e,{...i,ref:e}):s.jsx(o$e,{...i,ref:e})})});dme.displayName=Z1;var i$e=nx("PopoverContent.RemoveScroll"),a$e=D.forwardRef((t,e)=>{const r=jx(Z1,t.__scopePopover),n=D.useRef(null),i=vs(e,n),o=D.useRef(!1);return D.useEffect(()=>{const c=n.current;if(c)return yD(c)},[]),s.jsx(ST,{as:i$e,allowPinchZoom:!0,children:s.jsx(hme,{...t,ref:i,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Yr(t.onCloseAutoFocus,c=>{var a;c.preventDefault(),o.current||(a=r.triggerRef.current)==null||a.focus()}),onPointerDownOutside:Yr(t.onPointerDownOutside,c=>{const a=c.detail.originalEvent,m=a.button===0&&a.ctrlKey===!0,g=a.button===2||m;o.current=g},{checkForDefaultPrevented:!1}),onFocusOutside:Yr(t.onFocusOutside,c=>c.preventDefault(),{checkForDefaultPrevented:!1})})})}),o$e=D.forwardRef((t,e)=>{const r=jx(Z1,t.__scopePopover),n=D.useRef(!1),i=D.useRef(!1);return s.jsx(hme,{...t,ref:e,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:o=>{var c,a;(c=t.onCloseAutoFocus)==null||c.call(t,o),o.defaultPrevented||(n.current||(a=r.triggerRef.current)==null||a.focus(),o.preventDefault()),n.current=!1,i.current=!1},onInteractOutside:o=>{var m,g;(m=t.onInteractOutside)==null||m.call(t,o),o.defaultPrevented||(n.current=!0,o.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const c=o.target;((g=r.triggerRef.current)==null?void 0:g.contains(c))&&o.preventDefault(),o.detail.originalEvent.type==="focusin"&&i.current&&o.preventDefault()}})}),hme=D.forwardRef((t,e)=>{const{__scopePopover:r,trapFocus:n,onOpenAutoFocus:i,onCloseAutoFocus:o,disableOutsidePointerEvents:c,onEscapeKeyDown:a,onPointerDownOutside:m,onFocusOutside:g,onInteractOutside:_,...j}=t,N=jx(Z1,r),C=OT(r);return mD(),s.jsx(jT,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:i,onUnmountAutoFocus:o,children:s.jsx(t0,{asChild:!0,disableOutsidePointerEvents:c,onInteractOutside:_,onEscapeKeyDown:a,onPointerDownOutside:m,onFocusOutside:g,onDismiss:()=>N.onOpenChange(!1),children:s.jsx(oD,{"data-state":pme(N.open),role:"dialog",id:N.contentId,...C,...j,ref:e,style:{...j.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),fme="PopoverClose",l$e=D.forwardRef((t,e)=>{const{__scopePopover:r,...n}=t,i=jx(fme,r);return s.jsx(yn.button,{type:"button",...n,ref:e,onClick:Yr(t.onClick,()=>i.onOpenChange(!1))})});l$e.displayName=fme;var c$e="PopoverArrow",u$e=D.forwardRef((t,e)=>{const{__scopePopover:r,...n}=t,i=OT(r);return s.jsx(lD,{...i,...n,ref:e})});u$e.displayName=c$e;function pme(t){return t?"open":"closed"}var d$e=ame,h$e=cme,f$e=ume,mme=dme;const HD=d$e,WD=h$e,RT=D.forwardRef(({className:t,align:e="center",sideOffset:r=4,...n},i)=>s.jsx(f$e,{children:s.jsx(mme,{ref:i,align:e,sideOffset:r,className:ar("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...n})}));RT.displayName=mme.displayName;const IP=[{type:"like",emoji:"👍",label:"Like"},{type:"love",emoji:"❤️",label:"Love"},{type:"laugh",emoji:"😂",label:"Haha"},{type:"wow",emoji:"😮",label:"Wow"},{type:"sad",emoji:"😢",label:"Sad"},{type:"angry",emoji:"😠",label:"Angry"}],p$e=()=>{const{user:t}=rn(),{avatarUrl:e}=Bue(t==null?void 0:t.id),{toast:r}=Ri(),n=Wn(),i=D.useRef(null),[o,c]=D.useState("all"),[a,m]=D.useState(""),[g,_]=D.useState(""),[j,N]=D.useState(""),[C,P]=D.useState([]),[A,I]=D.useState([]),[O,R]=D.useState(""),[z,W]=D.useState(!1),[V,K]=D.useState(null),[Q,te]=D.useState(""),[X,ie]=D.useState(new Set),[he,xe]=D.useState({}),{data:pe=[]}=Sr({queryKey:["community-categories"],queryFn:async()=>{const{data:Me,error:Oe}=await ae.from("community_categories").select("*").order("sort_order");if(Oe)throw Oe;return Me}}),{data:ve=[]}=Sr({queryKey:["community-private-groups"],queryFn:async()=>{const{data:Me,error:Oe}=await ae.from("community_private_groups").select("*").order("sort_order");if(Oe)throw Oe;return Me}}),{data:ge=[],isLoading:ke}=Sr({queryKey:["community-posts",o],queryFn:async()=>{let Me=ae.from("community_posts").select("*").order("created_at",{ascending:!1});if(o.startsWith("group:")){const kr=o.replace("group:","");Me=Me.eq("private_group_id",kr)}else o==="all"||(Me=Me.eq("category_id",o).is("private_group_id",null));const{data:Oe,error:Ie}=await Me;if(Ie)throw Ie;const Be=[...new Set(Oe.map(kr=>kr.user_id))],{data:Pe}=await ae.from("profiles").select("id, name").in("id",Be),ut=new Map((Pe==null?void 0:Pe.map(kr=>[kr.id,kr.name]))||[]),jt=await MX(Be),$t=[...new Set(Oe.filter(kr=>kr.category_id).map(kr=>kr.category_id))],{data:Ht}=await ae.from("community_categories").select("*").in("id",$t),Lt=new Map((Ht==null?void 0:Ht.map(kr=>[kr.id,kr]))||[]),Kt=Oe.map(kr=>kr.id),{data:Ar}=await ae.from("community_post_media").select("*").in("post_id",Kt).order("sort_order"),{data:rt}=await ae.from("community_reactions").select("*").in("post_id",Kt),{data:We}=await ae.from("community_comments").select("*").in("post_id",Kt).order("created_at",{ascending:!0}),_t=[...new Set((We==null?void 0:We.map(kr=>kr.user_id))||[])],{data:Gt}=await ae.from("profiles").select("id, name").in("id",_t),rr=new Map((Gt==null?void 0:Gt.map(kr=>[kr.id,kr.name]))||[]),pr=await MX(_t);return Oe.map(kr=>({...kr,user_name:ut.get(kr.user_id)||"Unknown User",user_avatar:jt.get(kr.user_id),category:kr.category_id?Lt.get(kr.category_id):null,media:(Ar==null?void 0:Ar.filter(Hr=>Hr.post_id===kr.id))||[],reactions:(rt==null?void 0:rt.filter(Hr=>Hr.post_id===kr.id))||[],comments:((We==null?void 0:We.filter(Hr=>Hr.post_id===kr.id))||[]).map(Hr=>({...Hr,user_name:rr.get(Hr.user_id)||"Unknown User",user_avatar:pr.get(Hr.user_id)}))}))}}),Ce=zr({mutationFn:async()=>{W(!0);const{data:Me,error:Oe}=await ae.from("community_posts").insert({user_id:t.id,category_id:j?null:g||null,private_group_id:j||null,content:a,link_url:O||null}).select().single();if(Oe)throw Oe;for(let Ie=0;Ie{n.invalidateQueries({queryKey:["community-posts"]}),m(""),_(""),N(""),P([]),I([]),R(""),r({title:"Post created!"})},onError:Me=>{r({title:"Error creating post",description:Me.message,variant:"destructive"})},onSettled:()=>W(!1)}),Se=zr({mutationFn:async({postId:Me,content:Oe})=>{const{error:Ie}=await ae.from("community_posts").update({content:Oe}).eq("id",Me);if(Ie)throw Ie},onSuccess:()=>{n.invalidateQueries({queryKey:["community-posts"]}),K(null),te(""),r({title:"Post updated!"})}}),je=zr({mutationFn:async Me=>{const{error:Oe}=await ae.from("community_posts").delete().eq("id",Me);if(Oe)throw Oe},onSuccess:()=>{n.invalidateQueries({queryKey:["community-posts"]}),r({title:"Post deleted"})}}),et=zr({mutationFn:async({postId:Me,reactionType:Oe})=>{var Be;const Ie=(Be=ge.find(Pe=>Pe.id===Me))==null?void 0:Be.reactions.find(Pe=>Pe.user_id===(t==null?void 0:t.id));Ie?Ie.reaction_type===Oe?await ae.from("community_reactions").delete().eq("id",Ie.id):await ae.from("community_reactions").update({reaction_type:Oe}).eq("id",Ie.id):await ae.from("community_reactions").insert({post_id:Me,user_id:t.id,reaction_type:Oe})},onSuccess:()=>n.invalidateQueries({queryKey:["community-posts"]})}),bt=zr({mutationFn:async({postId:Me,content:Oe})=>{const{error:Ie}=await ae.from("community_comments").insert({post_id:Me,user_id:t.id,content:Oe});if(Ie)throw Ie},onSuccess:(Me,{postId:Oe})=>{n.invalidateQueries({queryKey:["community-posts"]}),xe(Ie=>({...Ie,[Oe]:""}))}}),_e=zr({mutationFn:async Me=>{const{error:Oe}=await ae.from("community_comments").delete().eq("id",Me);if(Oe)throw Oe},onSuccess:()=>n.invalidateQueries({queryKey:["community-posts"]})}),Ye=Me=>{const Oe=Array.from(Me.target.files||[]);if(Oe.length+C.length>10){r({title:"Maximum 10 files allowed",variant:"destructive"});return}P(Ie=>[...Ie,...Oe]),Oe.forEach(Ie=>{const Be=new FileReader;Be.onloadend=()=>{I(Pe=>[...Pe,Be.result])},Be.readAsDataURL(Ie)})},pt=Me=>{P(Oe=>Oe.filter((Ie,Be)=>Be!==Me)),I(Oe=>Oe.filter((Ie,Be)=>Be!==Me))},nt=Me=>Me.split(" ").map(Oe=>Oe[0]).join("").toUpperCase().slice(0,2),Qt=Me=>{const Oe={};return Me.forEach(Ie=>{Oe[Ie.reaction_type]=(Oe[Ie.reaction_type]||0)+1}),Oe},gt=Me=>{var Oe;return(Oe=Me.find(Ie=>Ie.user_id===(t==null?void 0:t.id)))==null?void 0:Oe.reaction_type};return s.jsx(Jr,{title:"Community",children:s.jsxs("div",{className:"max-w-2xl mx-auto space-y-6 w-full",children:[s.jsxs("div",{className:"px-1",children:[s.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Community"}),s.jsx("p",{className:"text-muted-foreground mt-1",children:"Connect and share with fellow agents"})]}),s.jsxs("div",{className:"px-1 pb-2",children:[s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(de,{variant:o==="all"?"default":"outline",size:"sm",onClick:()=>c("all"),children:"All"}),pe.map(Me=>s.jsxs(de,{variant:o===Me.id?"default":"outline",size:"sm",onClick:()=>c(Me.id),children:[Me.icon," ",Me.name]},Me.id))]}),ve.length>0&&s.jsx("div",{className:"mt-2 pt-2 border-t",children:s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:"text-sm text-muted-foreground flex items-center whitespace-nowrap w-full sm:w-auto sm:mr-2",children:"🔒 Private Groups:"}),ve.map(Me=>s.jsxs(de,{variant:o===`group:${Me.id}`?"default":"outline",size:"sm",onClick:()=>c(`group:${Me.id}`),children:[Me.icon||"🔒"," ",Me.name]},Me.id))]})})]}),s.jsx(at,{children:s.jsx(ct,{className:"pt-6",children:s.jsxs("div",{className:"flex gap-3",children:[s.jsxs(ql,{className:"h-10 w-10",children:[s.jsx(Iy,{src:e||void 0}),s.jsx(Hl,{children:t!=null&&t.email?nt(t.email.split("@")[0]):"U"})]}),s.jsxs("div",{className:"flex-1 space-y-3",children:[s.jsx(mi,{placeholder:"What's on your mind?",value:a,onChange:Me=>m(Me.target.value),className:"min-h-[80px] resize-none"}),A.length>0&&s.jsx("div",{className:"grid grid-cols-3 gap-2",children:A.map((Me,Oe)=>{var Ie;return s.jsxs("div",{className:"relative aspect-square rounded-lg overflow-hidden bg-muted",children:[(Ie=C[Oe])!=null&&Ie.type.startsWith("video/")?s.jsx("video",{src:Me,className:"w-full h-full object-cover"}):s.jsx("img",{src:Me,alt:"",className:"w-full h-full object-cover"}),s.jsx(de,{variant:"destructive",size:"icon",className:"absolute top-1 right-1 h-6 w-6",onClick:()=>pt(Oe),children:s.jsx(Ni,{className:"h-3 w-3"})})]},Oe)})}),O&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Go,{className:"h-4 w-4 text-muted-foreground"}),s.jsx(Et,{value:O,onChange:Me=>R(Me.target.value),placeholder:"https://...",className:"flex-1"}),s.jsx(de,{variant:"ghost",size:"icon",onClick:()=>R(""),children:s.jsx(Ni,{className:"h-4 w-4"})})]}),s.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3",children:[s.jsxs("div",{className:"flex gap-1 flex-wrap",children:[s.jsx("input",{type:"file",ref:i,onChange:Ye,accept:"image/*,video/*",multiple:!0,className:"hidden"}),s.jsxs(de,{variant:"ghost",size:"sm",onClick:()=>{var Me;return(Me=i.current)==null?void 0:Me.click()},children:[s.jsx(Wm,{className:"h-4 w-4 mr-1"}),"Photo"]}),s.jsxs(de,{variant:"ghost",size:"sm",onClick:()=>{var Me;return(Me=i.current)==null?void 0:Me.click()},children:[s.jsx(Ia,{className:"h-4 w-4 mr-1"}),"Video"]}),s.jsxs(de,{variant:"ghost",size:"sm",onClick:()=>R("https://"),children:[s.jsx(Go,{className:"h-4 w-4 mr-1"}),"Link"]})]}),s.jsxs("div",{className:"flex items-center gap-2 w-full sm:w-auto justify-end",children:[ve.length>0?s.jsxs(Kn,{value:j||g||"none",onValueChange:Me=>{Me==="none"?(_(""),N("")):Me.startsWith("group:")?(N(Me.replace("group:","")),_("")):(_(Me),N(""))},children:[s.jsx(qn,{className:"w-[130px] sm:w-[160px] h-8 text-xs sm:text-sm",children:s.jsx(Zn,{placeholder:"Select..."})}),s.jsxs(Hn,{children:[s.jsx(_r,{value:"none",children:"No category"}),pe.map(Me=>s.jsxs(_r,{value:Me.id,children:[Me.icon," ",Me.name]},Me.id)),ve.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"px-2 py-1 text-xs font-semibold text-muted-foreground border-t mt-1 pt-1",children:"🔒 Private Groups"}),ve.map(Me=>s.jsxs(_r,{value:`group:${Me.id}`,children:[Me.icon||"🔒"," ",Me.name]},Me.id))]})]})]}):s.jsxs(Kn,{value:g,onValueChange:_,children:[s.jsx(qn,{className:"w-[110px] sm:w-[140px] h-8 text-xs sm:text-sm",children:s.jsx(Zn,{placeholder:"Category"})}),s.jsx(Hn,{children:pe.map(Me=>s.jsxs(_r,{value:Me.id,children:[Me.icon," ",Me.name]},Me.id))})]}),s.jsxs(de,{size:"sm",onClick:()=>Ce.mutate(),disabled:!a.trim()||z,children:[s.jsx(Dc,{className:"h-4 w-4 mr-1"}),"Post"]})]})]})]})]})})}),ke?s.jsx("div",{className:"space-y-4",children:[...Array(3)].map((Me,Oe)=>s.jsx(at,{children:s.jsx(ct,{className:"pt-6",children:s.jsxs("div",{className:"flex gap-3",children:[s.jsx(Dn,{className:"h-10 w-10 rounded-full"}),s.jsxs("div",{className:"flex-1 space-y-2",children:[s.jsx(Dn,{className:"h-4 w-32"}),s.jsx(Dn,{className:"h-4 w-full"}),s.jsx(Dn,{className:"h-4 w-3/4"})]})]})})},Oe))}):ge.length===0?s.jsx(at,{children:s.jsxs(ct,{className:"py-12 text-center",children:[s.jsx(lu,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),s.jsx("h3",{className:"font-semibold mb-2",children:"No posts yet"}),s.jsx("p",{className:"text-muted-foreground",children:"Be the first to start a conversation!"})]})}):s.jsx("div",{className:"space-y-4",children:ge.map(Me=>{var Oe,Ie,Be,Pe;return s.jsx(at,{children:s.jsxs(ct,{className:"pt-6",children:[s.jsxs("div",{className:"flex items-start justify-between mb-3",children:[s.jsxs("div",{className:"flex gap-3 min-w-0",children:[s.jsxs(ql,{className:"h-10 w-10",children:[s.jsx(Iy,{src:Me.user_avatar||void 0}),s.jsx(Hl,{children:nt(Me.user_name||"U")})]}),s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"font-semibold break-words",children:Me.user_name}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-sm text-muted-foreground",children:[s.jsx("span",{children:Bu(new Date(Me.created_at),{addSuffix:!0})}),Me.category&&s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"•"}),s.jsxs(ir,{variant:"secondary",className:"text-xs",children:[Me.category.icon," ",Me.category.name]})]})]})]})]}),Me.user_id===(t==null?void 0:t.id)&&s.jsxs(rg,{children:[s.jsx(ng,{asChild:!0,children:s.jsx(de,{variant:"ghost",size:"icon",className:"h-8 w-8",children:s.jsx(K6,{className:"h-4 w-4"})})}),s.jsxs(Op,{align:"end",children:[s.jsxs(Ro,{onClick:()=>{K(Me),te(Me.content)},children:[s.jsx(io,{className:"h-4 w-4 mr-2"}),"Edit"]}),s.jsxs(Ro,{className:"text-destructive",onClick:()=>je.mutate(Me.id),children:[s.jsx(oi,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})]}),s.jsx("p",{className:"whitespace-pre-wrap mb-3",children:Me.content}),Me.media.length>0&&s.jsx("div",{className:`grid gap-2 mb-3 ${Me.media.length===1?"grid-cols-1":(Me.media.length===2,"grid-cols-2")}`,children:Me.media.map((ut,jt)=>s.jsx("div",{className:`rounded-lg overflow-hidden bg-muted ${Me.media.length===1?"max-h-[400px]":"aspect-square"}`,children:ut.media_type==="video"?s.jsx("video",{src:ut.media_url,controls:!0,className:"w-full h-full object-cover"}):s.jsx("img",{src:ut.media_url,alt:"",className:"w-full h-full object-cover"})},ut.id))}),Me.link_url&&s.jsx("a",{href:Me.link_url,target:"_blank",rel:"noopener noreferrer",className:"block p-3 rounded-lg border hover:bg-muted transition-colors mb-3",children:s.jsxs("div",{className:"flex items-center gap-2 text-sm text-primary",children:[s.jsx(Go,{className:"h-4 w-4"}),Me.link_url]})}),Me.reactions.length>0&&s.jsxs("div",{className:"flex items-center gap-2 mb-3 text-sm text-muted-foreground",children:[s.jsx("div",{className:"flex -space-x-1",children:Object.entries(Qt(Me.reactions)).slice(0,3).map(([ut])=>{var jt;return s.jsx("span",{className:"text-base",children:(jt=IP.find($t=>$t.type===ut))==null?void 0:jt.emoji},ut)})}),s.jsx("span",{children:Me.reactions.length})]}),s.jsxs("div",{className:"flex items-center gap-1 border-t border-b py-1 my-2",children:[s.jsxs(HD,{children:[s.jsx(WD,{asChild:!0,children:s.jsxs(de,{variant:"ghost",size:"sm",className:"flex-1",children:[gt(Me.reactions)?s.jsx("span",{className:"mr-1",children:(Oe=IP.find(ut=>ut.type===gt(Me.reactions)))==null?void 0:Oe.emoji}):s.jsx(Ip,{className:"h-4 w-4 mr-1"}),gt(Me.reactions)?(Ie=IP.find(ut=>ut.type===gt(Me.reactions)))==null?void 0:Ie.label:"Like"]})}),s.jsx(RT,{className:"w-auto p-2",side:"top",children:s.jsx("div",{className:"flex gap-1",children:IP.map(ut=>s.jsx("button",{onClick:()=>et.mutate({postId:Me.id,reactionType:ut.type}),className:"text-2xl hover:scale-125 transition-transform p-1",title:ut.label,children:ut.emoji},ut.type))})})]}),s.jsxs(de,{variant:"ghost",size:"sm",className:"flex-1",onClick:()=>ie(ut=>{const jt=new Set(ut);return jt.has(Me.id)?jt.delete(Me.id):jt.add(Me.id),jt}),children:[s.jsx(lu,{className:"h-4 w-4 mr-1"}),"Comment ",Me.comments.length>0&&`(${Me.comments.length})`]})]}),(X.has(Me.id)||Me.comments.length>0)&&s.jsxs("div",{className:"space-y-3 mt-3",children:[Me.comments.map(ut=>s.jsxs("div",{className:"flex gap-2",children:[s.jsxs(ql,{className:"h-8 w-8",children:[s.jsx(Iy,{src:ut.user_avatar||void 0}),s.jsx(Hl,{className:"text-xs",children:nt(ut.user_name||"U")})]}),s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"bg-muted rounded-lg px-3 py-2",children:[s.jsx("div",{className:"font-medium text-sm",children:ut.user_name}),s.jsx("p",{className:"text-sm",children:ut.content})]}),s.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-muted-foreground",children:[s.jsx("span",{children:Bu(new Date(ut.created_at),{addSuffix:!0})}),ut.user_id===(t==null?void 0:t.id)&&s.jsx("button",{onClick:()=>_e.mutate(ut.id),className:"hover:text-destructive",children:"Delete"})]})]})]},ut.id)),t&&s.jsxs("div",{className:"flex gap-2",children:[s.jsxs(ql,{className:"h-8 w-8",children:[s.jsx(Iy,{src:e||void 0}),s.jsx(Hl,{className:"text-xs",children:nt(((Be=t.email)==null?void 0:Be.split("@")[0])||"U")})]}),s.jsxs("div",{className:"flex-1 flex gap-2",children:[s.jsx(Et,{placeholder:"Write a comment...",value:he[Me.id]||"",onChange:ut=>xe(jt=>({...jt,[Me.id]:ut.target.value})),onKeyDown:ut=>{var jt;ut.key==="Enter"&&((jt=he[Me.id])!=null&&jt.trim())&&bt.mutate({postId:Me.id,content:he[Me.id]})},className:"h-8"}),s.jsx(de,{size:"sm",variant:"ghost",onClick:()=>{var ut;(ut=he[Me.id])!=null&&ut.trim()&&bt.mutate({postId:Me.id,content:he[Me.id]})},disabled:!((Pe=he[Me.id])!=null&&Pe.trim()),children:s.jsx(Dc,{className:"h-4 w-4"})})]})]})]})]})},Me.id)})}),s.jsx(mn,{open:!!V,onOpenChange:()=>K(null),children:s.jsxs(pn,{children:[s.jsx(xn,{children:s.jsx(gn,{children:"Edit Post"})}),s.jsx(mi,{value:Q,onChange:Me=>te(Me.target.value),className:"min-h-[120px]"}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(de,{variant:"outline",onClick:()=>K(null),children:"Cancel"}),s.jsx(de,{onClick:()=>{V&&Se.mutate({postId:V.id,content:Q})},disabled:!Q.trim(),children:"Save Changes"})]})]})})]})})},fw={open:{label:"Open",icon:No,color:"bg-yellow-500"},in_progress:{label:"In Progress",icon:lu,color:"bg-blue-500"},resolved:{label:"Resolved",icon:gc,color:"bg-green-500"},closed:{label:"Closed",icon:W2,color:"bg-muted-foreground"}},pQ={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function m$e(){const{user:t}=rn(),e=Wn(),[r,n]=D.useState(null),[i,o]=D.useState(""),{data:c=[],isLoading:a}=Sr({queryKey:["support-tickets"],queryFn:async()=>{const{data:j,error:N}=await ae.from("support_tickets").select("*").eq("user_id",t==null?void 0:t.id).order("created_at",{ascending:!1});if(N)throw N;return j},enabled:!!t}),{data:m=[]}=Sr({queryKey:["ticket-replies",r==null?void 0:r.id],queryFn:async()=>{if(!r)return[];const{data:j,error:N}=await ae.from("support_ticket_replies").select("*, profiles(name)").eq("ticket_id",r.id).order("created_at",{ascending:!0});if(N)throw N;return j},enabled:!!r}),g=zr({mutationFn:async j=>{if(!r||!t)throw new Error("Missing data");const{error:N}=await ae.from("support_ticket_replies").insert({ticket_id:r.id,user_id:t.id,content:j,is_admin_reply:!1});if(N)throw N},onSuccess:()=>{e.invalidateQueries({queryKey:["ticket-replies",r==null?void 0:r.id]}),o(""),Dt.success("Reply sent!")},onError:()=>{Dt.error("Failed to send reply")}}),_=()=>{i.trim()&&g.mutate(i)};if(r){const j=fw[r.status].icon;return s.jsx(Jr,{children:s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"flex items-center gap-4",children:[s.jsx(de,{variant:"ghost",size:"icon",onClick:()=>n(null),children:s.jsx(Ka,{className:"h-5 w-5"})}),s.jsxs("div",{className:"flex-1",children:[s.jsx("h1",{className:"text-2xl font-bold",children:r.subject}),s.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[s.jsx(ir,{variant:"secondary",children:pQ[r.category]}),s.jsxs(ir,{className:fw[r.status].color,children:[s.jsx(j,{className:"h-3 w-3 mr-1"}),fw[r.status].label]})]})]})]}),s.jsxs(at,{children:[s.jsx(xr,{children:s.jsxs(us,{children:["Created on ",Vn(new Date(r.created_at),"MMM d, yyyy 'at' h:mm a")]})}),s.jsx(ct,{children:s.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:r.description})})]}),s.jsxs(at,{children:[s.jsx(xr,{children:s.jsx(wr,{className:"text-lg",children:"Conversation"})}),s.jsxs(ct,{children:[s.jsx(qu,{className:"h-[300px] pr-4",children:m.length===0?s.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No replies yet"}):s.jsx("div",{className:"space-y-4",children:m.map(N=>{var C;return s.jsxs("div",{className:`p-4 rounded-lg ${N.is_admin_reply?"bg-primary/10 ml-4":"bg-muted mr-4"}`,children:[s.jsxs("div",{className:"flex justify-between items-start mb-2",children:[s.jsx("span",{className:"font-medium text-sm",children:N.is_admin_reply?"Support Team":((C=N.profiles)==null?void 0:C.name)||"You"}),s.jsx("span",{className:"text-xs text-muted-foreground",children:Vn(new Date(N.created_at),"MMM d, h:mm a")})]}),s.jsx("p",{className:"text-sm whitespace-pre-wrap",children:N.content})]},N.id)})})}),r.status!=="closed"&&s.jsxs(s.Fragment,{children:[s.jsx(xf,{className:"my-4"}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(mi,{placeholder:"Type your reply...",value:i,onChange:N=>o(N.target.value),className:"min-h-[80px]"}),s.jsx(de,{onClick:_,disabled:!i.trim()||g.isPending,className:"self-end",children:s.jsx(Dc,{className:"h-4 w-4"})})]})]})]})]})]})})}return s.jsx(Jr,{children:s.jsxs("div",{className:"space-y-6",children:[s.jsx(at,{className:"bg-gradient-to-br from-primary/10 via-primary/5 to-background border-primary/20",children:s.jsx(ct,{className:"p-6 sm:p-8",children:s.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center gap-6",children:[s.jsx("div",{className:"p-4 bg-primary/20 rounded-full",children:s.jsx(ooe,{className:"h-8 w-8 text-primary"})}),s.jsxs("div",{className:"flex-1",children:[s.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Need Help?"}),s.jsx("p",{className:"text-muted-foreground mb-4",children:"Submit a support ticket and our team will get back to you as soon as possible."}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[s.jsx(P$,{trigger:s.jsxs(de,{size:"lg",className:"gap-2",children:[s.jsx(Qn,{className:"h-5 w-5"}),"Submit a Ticket"]})}),s.jsxs("div",{className:"flex items-center gap-2 px-4 py-2 bg-muted rounded-lg",children:[s.jsx(Yl,{className:"h-4 w-4 text-muted-foreground"}),s.jsxs("span",{className:"text-sm text-muted-foreground",children:["Or text us: ",s.jsx("span",{className:"font-semibold text-foreground",children:"1-866-527-8668"})]})]})]})]})]})})}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsx("h2",{className:"text-lg font-semibold",children:"Your Tickets"}),s.jsx(P$,{trigger:s.jsxs(de,{variant:"outline",size:"sm",className:"gap-2",children:[s.jsx(Qn,{className:"h-4 w-4"}),"New Ticket"]})})]}),a?s.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading tickets..."}):c.length===0?s.jsx(at,{className:"border-dashed",children:s.jsxs(ct,{className:"text-center py-12",children:[s.jsx(lu,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),s.jsx("h3",{className:"text-lg font-medium mb-2",children:"No tickets yet"}),s.jsx("p",{className:"text-muted-foreground",children:"You haven't submitted any support tickets. Use the button above to get started!"})]})}):s.jsx("div",{className:"space-y-3",children:c.map(j=>{const N=fw[j.status].icon;return s.jsx(at,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>n(j),children:s.jsx(ct,{className:"p-4",children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("h3",{className:"font-medium truncate",children:j.subject}),s.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[s.jsx(ir,{variant:"outline",className:"text-xs",children:pQ[j.category]}),s.jsx("span",{className:"text-xs text-muted-foreground",children:Vn(new Date(j.created_at),"MMM d, yyyy")})]})]}),s.jsxs(ir,{className:fw[j.status].color,children:[s.jsx(N,{className:"h-3 w-3 mr-1"}),fw[j.status].label]})]})})},j.id)})})]})})}function g$e({open:t,onOpenChange:e}){return s.jsx(mn,{open:t,onOpenChange:e,children:s.jsxs(pn,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[s.jsx(xn,{children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:s.jsx(ko,{className:"h-5 w-5 text-primary"})}),s.jsxs("div",{children:[s.jsx(gn,{children:"Schedule Agent Onboarding"}),s.jsx(fi,{children:"Book a one-on-one onboarding session with LevelUp"})]})]})}),t&&s.jsx("iframe",{src:"https://tidycal.com/jeremycollins/new-agent-onboarding",className:"w-full border-0 rounded-lg",style:{height:"600px",minHeight:"500px"},title:"Schedule Agent Onboarding"})]})})}function y$e({open:t,onOpenChange:e}){const{brokerageId:r}=rn(),[n,i]=D.useState(""),[o,c]=D.useState([]),[a,m]=D.useState(!1),{data:g,isLoading:_}=Sr({queryKey:["brokerage-agents-for-onboarding",r],queryFn:async()=>{if(!r)return[];const{data:A,error:I}=await ae.from("profiles").select("id, name, email").eq("brokerage_id",r).order("name",{ascending:!0});if(I)throw I;return A},enabled:t&&!!r}),j=g==null?void 0:g.filter(A=>A.name.toLowerCase().includes(n.toLowerCase())||A.email.toLowerCase().includes(n.toLowerCase())),N=A=>{c(I=>I.includes(A)?I.filter(O=>O!==A):[...I,A])},C=async()=>{if(o.length===0){Dt.error("Please select at least one agent");return}m(!0);try{const{data:A,error:I}=await ae.functions.invoke("send-onboarding-link",{body:{agentIds:o}});if(I)throw I;Dt.success(`Onboarding link sent to ${o.length} agent${o.length>1?"s":""}`),c([]),e(!1)}catch(A){console.error("Error sending onboarding link:",A),Dt.error(A.message||"Failed to send onboarding link")}finally{m(!1)}},P=A=>{A||(c([]),i("")),e(A)};return s.jsx(mn,{open:t,onOpenChange:P,children:s.jsxs(pn,{className:"max-w-md",children:[s.jsx(xn,{children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:s.jsx(Dc,{className:"h-5 w-5 text-primary"})}),s.jsxs("div",{children:[s.jsx(gn,{children:"Send Onboarding Link"}),s.jsx(fi,{children:"Select agents to receive the onboarding booking link"})]})]})}),s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"relative",children:[s.jsx(ba,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),s.jsx(Et,{placeholder:"Search agents...",value:n,onChange:A=>i(A.target.value),className:"pl-10"})]}),_?s.jsx("div",{className:"flex items-center justify-center py-8",children:s.jsx(Ps,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):(j==null?void 0:j.length)===0?s.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[s.jsx(_i,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),s.jsx("p",{children:"No agents found"})]}):s.jsx(qu,{className:"h-[300px] border rounded-lg",children:s.jsx("div",{className:"p-2 space-y-1",children:j==null?void 0:j.map(A=>s.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-lg hover:bg-muted cursor-pointer",onClick:()=>N(A.id),children:[s.jsx(dx,{checked:o.includes(A.id),onCheckedChange:()=>N(A.id)}),s.jsx(ql,{className:"h-8 w-8",children:s.jsx(Hl,{className:"text-xs",children:A.name.split(" ").map(I=>I[0]).join("").toUpperCase()})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("p",{className:"text-sm font-medium truncate",children:A.name}),s.jsx("p",{className:"text-xs text-muted-foreground truncate",children:A.email})]})]},A.id))})}),o.length>0&&s.jsxs("p",{className:"text-sm text-muted-foreground",children:[o.length," agent",o.length>1?"s":""," selected"]})]}),s.jsxs(zi,{children:[s.jsx(de,{variant:"outline",onClick:()=>P(!1),children:"Cancel"}),s.jsx(de,{onClick:C,disabled:o.length===0||a,children:a?s.jsxs(s.Fragment,{children:[s.jsx(Ps,{className:"h-4 w-4 mr-2 animate-spin"}),"Sending..."]}):s.jsxs(s.Fragment,{children:[s.jsx(Dc,{className:"h-4 w-4 mr-2"}),"Send Link"]})})]})]})})}function x$e(){const[t,e]=D.useState(!1),[r,n]=D.useState(!1);return s.jsxs(s.Fragment,{children:[s.jsxs(at,{className:"mb-8",children:[s.jsx(xr,{children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:s.jsx(_i,{className:"h-6 w-6 text-primary"})}),s.jsxs("div",{children:[s.jsx(wr,{children:"Agent Onboarding"}),s.jsx(us,{children:"Schedule onboarding sessions for yourself or your agents"})]})]})}),s.jsx(ct,{children:s.jsxs("div",{className:"flex flex-wrap gap-4",children:[s.jsxs(de,{onClick:()=>e(!0),className:"flex items-center gap-2",children:[s.jsx(ko,{className:"h-4 w-4"}),"Schedule Agent Onboarding"]}),s.jsxs(de,{variant:"outline",onClick:()=>n(!0),className:"flex items-center gap-2",children:[s.jsx(Dc,{className:"h-4 w-4"}),"Send New Agent Onboarding Link"]})]})})]}),s.jsx(g$e,{open:t,onOpenChange:e}),s.jsx(y$e,{open:r,onOpenChange:n})]})}function v$e({open:t,onOpenChange:e}){return s.jsx(mn,{open:t,onOpenChange:e,children:s.jsxs(pn,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[s.jsx(xn,{children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:s.jsx(G2,{className:"h-5 w-5 text-primary"})}),s.jsxs("div",{children:[s.jsx(gn,{children:"Schedule Launch Meeting"}),s.jsx(fi,{children:"Book a private LevelUp information session for your brokerage"})]})]})}),t&&s.jsx("iframe",{src:"https://tidycal.com/jeremycollins/levelup-launch-call",className:"w-full border-0 rounded-lg",style:{height:"600px",minHeight:"500px"},title:"Schedule Launch Meeting"})]})})}function _$e(){const[t,e]=D.useState(!1);return s.jsxs(s.Fragment,{children:[s.jsxs(at,{className:"mb-8",children:[s.jsx(xr,{children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:s.jsx(G2,{className:"h-6 w-6 text-primary"})}),s.jsxs("div",{children:[s.jsx(wr,{children:"Launch or ReLaunch Meeting"}),s.jsx(us,{children:"Schedule a private LevelUp information session for your brokerage. Have one of our staff host a meeting to help your team get the most out of all our trainings, tools, and resources."})]})]})}),s.jsx(ct,{children:s.jsxs(de,{onClick:()=>e(!0),className:"flex items-center gap-2",children:[s.jsx(G2,{className:"h-4 w-4"}),"Schedule Launch Meeting"]})})]}),s.jsx(v$e,{open:t,onOpenChange:e})]})}function b$e(){const t=Bs(),[e,r]=D.useState(""),[n,i]=D.useState(null),{data:o,isLoading:c}=Sr({queryKey:["brokerage-resources-published"],queryFn:async()=>{const{data:A,error:I}=await ae.from("brokerage_resources").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(I)throw I;return A}}),{data:a}=Sr({queryKey:["brokerage-resource-categories"],queryFn:async()=>{const{data:A,error:I}=await ae.from("brokerage_resource_categories").select("*").order("sort_order",{ascending:!0});if(I)throw I;return A}}),{data:m}=Sr({queryKey:["brokerage-resource-pdfs-all"],queryFn:async()=>{const{data:A,error:I}=await ae.from("brokerage_resource_pdfs").select("resource_id");if(I)throw I;return A}}),{data:g}=Sr({queryKey:["brokerage-resource-videos-all"],queryFn:async()=>{const{data:A,error:I}=await ae.from("brokerage_resource_videos").select("resource_id");if(I)throw I;return A}}),{data:_}=Sr({queryKey:["brokerage-resource-links-all"],queryFn:async()=>{const{data:A,error:I}=await ae.from("brokerage_resource_links").select("resource_id");if(I)throw I;return A}}),j=o==null?void 0:o.filter(A=>{var R;const I=A.title.toLowerCase().includes(e.toLowerCase())||((R=A.description)==null?void 0:R.toLowerCase().includes(e.toLowerCase())),O=!n||A.category_id===n;return I&&O}),N=a==null?void 0:a.filter(A=>o==null?void 0:o.some(I=>I.category_id===A.id)),C=A=>{const I=(m==null?void 0:m.filter(z=>z.resource_id===A).length)||0,O=(g==null?void 0:g.filter(z=>z.resource_id===A).length)||0,R=(_==null?void 0:_.filter(z=>z.resource_id===A).length)||0;return{pdfCount:I,videoCount:O,linkCount:R}},P=A=>{t(`/brokerage-resources/${A}`)};return s.jsx(Jr,{title:"Brokerage Resources",description:"Access exclusive resources for brokerage managers",children:s.jsxs("div",{className:"space-y-6",children:[s.jsx(x$e,{}),s.jsx(_$e,{}),s.jsxs("div",{className:"relative max-w-md",children:[s.jsx(ba,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),s.jsx(Et,{placeholder:"Search resources...",value:e,onChange:A=>r(A.target.value),className:"pl-10"})]}),N&&N.length>0&&s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(ir,{variant:n===null?"default":"outline",className:"cursor-pointer",onClick:()=>i(null),children:"All"}),N.map(A=>s.jsx(ir,{variant:n===A.id?"default":"outline",className:"cursor-pointer",onClick:()=>i(A.id),children:A.name},A.id))]}),!c&&s.jsxs("p",{className:"text-sm text-muted-foreground",children:[(j==null?void 0:j.length)||0," resource",(j==null?void 0:j.length)!==1?"s":""," available"]}),c?s.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:[...Array(6)].map((A,I)=>s.jsxs(at,{children:[s.jsx(Dn,{className:"h-40 w-full"}),s.jsx(xr,{children:s.jsx(Dn,{className:"h-5 w-3/4"})}),s.jsxs(ct,{children:[s.jsx(Dn,{className:"h-4 w-full mb-2"}),s.jsx(Dn,{className:"h-4 w-2/3"})]})]},I))}):(j==null?void 0:j.length)===0?s.jsxs(at,{className:"p-12 text-center",children:[s.jsx(Hm,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),s.jsx("h3",{className:"text-lg font-medium mb-2",children:"No resources found"}),s.jsx("p",{className:"text-muted-foreground",children:e||n?"Try adjusting your filters":"Check back later for new resources"})]}):s.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:j==null?void 0:j.map(A=>{const{pdfCount:I,videoCount:O,linkCount:R}=C(A.id),z=a==null?void 0:a.find(W=>W.id===A.category_id);return s.jsxs(at,{className:"overflow-hidden cursor-pointer hover:shadow-lg transition-shadow",onClick:()=>P(A.id),children:[A.preview_image_url?s.jsx("img",{src:A.preview_image_url,alt:A.title,className:"w-full h-40 object-cover"}):s.jsx("div",{className:"w-full h-40 bg-muted flex items-center justify-center",children:s.jsx(Hm,{className:"h-16 w-16 text-muted-foreground"})}),s.jsx(xr,{className:"pb-2",children:s.jsxs("div",{className:"flex items-start justify-between gap-2",children:[s.jsx(wr,{className:"text-lg line-clamp-1",children:A.title}),z&&s.jsx(ir,{variant:"secondary",className:"shrink-0 text-xs",children:z.name})]})}),s.jsxs(ct,{children:[A.description&&s.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3",children:A.description}),s.jsxs("div",{className:"flex items-center gap-4 text-sm text-muted-foreground",children:[I>0&&s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(Ii,{className:"h-4 w-4"}),I]}),O>0&&s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(Ia,{className:"h-4 w-4"}),O]}),R>0&&s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(Go,{className:"h-4 w-4"}),R]})]})]})]},A.id)})})]})})}const w$e=()=>{const{resourceId:t}=mu(),{data:e,isLoading:r}=Sr({queryKey:["brokerage-resource-detail",t],queryFn:async()=>{const{data:i,error:o}=await ae.from("brokerage_resources").select("*").eq("id",t).eq("is_published",!0).single();if(o)throw o;const{data:c}=await ae.from("brokerage_resource_pdfs").select("*").eq("resource_id",t).order("sort_order"),{data:a}=await ae.from("brokerage_resource_videos").select("*").eq("resource_id",t).order("sort_order"),{data:m}=await ae.from("brokerage_resource_links").select("*").eq("resource_id",t).order("sort_order");return{...i,pdfs:c||[],videos:a||[],links:m||[]}},enabled:!!t}),n=i=>i?i<1024?i+" B":i<1024*1024?(i/1024).toFixed(1)+" KB":(i/(1024*1024)).toFixed(1)+" MB":"";return r?s.jsx(Jr,{title:"Brokerage Resources",children:s.jsx("div",{className:"flex justify-center py-12",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e?s.jsx(Jr,{title:e.title,children:s.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[s.jsx(de,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:s.jsxs(jd,{to:"/brokerage-resources",children:[s.jsx(Ka,{className:"h-4 w-4"}),"Back to Resources"]})}),e.preview_image_url&&s.jsx("div",{className:"relative w-full rounded-lg overflow-hidden bg-muted",children:s.jsx("img",{src:e.preview_image_url,alt:e.title,className:"w-full max-h-[400px] object-cover"})}),s.jsxs("div",{className:"space-y-4",children:[s.jsx("h1",{className:"text-2xl font-bold text-foreground",children:e.title}),e.description&&s.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:e.description})]}),e.videos&&e.videos.length>0&&s.jsx(at,{children:s.jsxs(ct,{className:"pt-6",children:[s.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[s.jsx(Ia,{className:"h-4 w-4"}),"Videos (",e.videos.length,")"]}),s.jsx("div",{className:"space-y-4",children:e.videos.map(i=>s.jsxs("div",{className:"space-y-2",children:[s.jsx("h4",{className:"font-medium",children:i.title}),s.jsx("div",{className:"relative w-full",style:{paddingTop:"56.25%"},children:s.jsx("iframe",{src:i.video_url,className:"absolute top-0 left-0 w-full h-full rounded-lg border",allow:"accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture",allowFullScreen:!0})})]},i.id))})]})}),e.pdfs&&e.pdfs.length>0&&s.jsx(at,{children:s.jsxs(ct,{className:"pt-6",children:[s.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[s.jsx(Ii,{className:"h-4 w-4"}),"Documents (",e.pdfs.length,")"]}),s.jsx("div",{className:"grid gap-2",children:e.pdfs.map(i=>s.jsxs("a",{href:i.file_url,target:"_blank",rel:"noopener noreferrer",className:"flex items-center justify-between p-3 rounded-lg border hover:bg-muted transition-colors group",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"p-2 rounded-md bg-primary/10",children:s.jsx(Ii,{className:"h-4 w-4 text-primary"})}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-sm",children:i.name}),i.file_size&&s.jsx("div",{className:"text-xs text-muted-foreground",children:n(i.file_size)})]})]}),s.jsx(Pp,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors"})]},i.id))})]})}),e.links&&e.links.length>0&&s.jsx(at,{children:s.jsxs(ct,{className:"pt-6",children:[s.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[s.jsx(oa,{className:"h-4 w-4"}),"Canva Templates (",e.links.length,")"]}),s.jsx("div",{className:"grid gap-2",children:e.links.map(i=>s.jsxs("a",{href:i.canva_share_link,target:"_blank",rel:"noopener noreferrer",className:"flex items-center justify-between p-3 rounded-lg border hover:bg-muted transition-colors group",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"p-2 rounded-md bg-primary/10",children:s.jsx(oa,{className:"h-4 w-4 text-primary"})}),s.jsx("div",{className:"font-medium text-sm",children:i.title})]}),s.jsx(oa,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors"})]},i.id))})]})})]})}):s.jsx(Jr,{title:"Brokerage Resources",children:s.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[s.jsx(Hm,{className:"h-12 w-12 text-muted-foreground mb-4"}),s.jsx("h3",{className:"text-lg font-semibold",children:"Resource not found"}),s.jsx("p",{className:"text-muted-foreground mt-1",children:"This resource may have been removed or is not available."}),s.jsx(de,{asChild:!0,className:"mt-4",children:s.jsx(jd,{to:"/brokerage-resources",children:"Back to Resources"})})]})})},mQ={users:{label:"Users & Access",sections:[{title:"Members",description:"Manage users, roles, and brokerage assignments",icon:_i,path:"/admin/members",color:"bg-blue-500/10 text-blue-600"},{title:"Invite Codes",description:"Create and manage signup invite codes",icon:q2e,path:"/admin/invite-codes",color:"bg-amber-500/10 text-amber-600"},{title:"Subscriptions",description:"Track and manage user subscriptions",icon:fM,path:"/admin/subscriptions",color:"bg-gradient-to-br from-green-500/20 to-green-500/10 text-green-600"},{title:"Subscription Discounts",description:"Create and manage coupon codes",icon:joe,path:"/admin/discounts",color:"bg-red-500/10 text-red-600"},{title:"Referral Program",description:"Track brokerage referrals and discounts",icon:ph,path:"/admin/referrals",color:"bg-teal-500/10 text-teal-600"}]},content:{label:"Content",sections:[{title:"Manage Templates",description:"Upload and organize Canva templates",icon:A_,path:"/admin/templates",color:"bg-pink-500/10 text-pink-600"},{title:"Manage Academy",description:"Upload videos and training content",icon:eD,path:"/admin/academy",color:"bg-indigo-500/10 text-indigo-600"},{title:"Manage Toolbox",description:"Create and manage resource kits",icon:xT,path:"/admin/toolbox",color:"bg-orange-500/10 text-orange-600"},{title:"Social Swag",description:"Manage social media content and links",icon:cu,path:"/admin/social-swag",color:"bg-fuchsia-500/10 text-fuchsia-600"},{title:"Newsletters",description:"Manage monthly newsletter templates",icon:gT,path:"/admin/newsletters",color:"bg-violet-500/10 text-violet-600"},{title:"Manage Events",description:"Create and publish events with Zoom integration",icon:H2,path:"/admin/events",color:"bg-green-500/10 text-green-600"},{title:"Additional Services",description:"Manage additional service offerings",icon:Hm,path:"/admin/additional-services",color:"bg-lime-500/10 text-lime-600"},{title:"Brokerage Resources",description:"Manage resources for brokerage managers",icon:Hm,path:"/admin/brokerage-resources",color:"bg-slate-500/10 text-slate-600"}]},platform:{label:"Platform",sections:[{title:"Dashboard Management",description:"Configure banners and dashboard modules",icon:moe,path:"/admin/dashboard-management",color:"bg-teal-500/10 text-teal-600"},{title:"Manage Apps",description:"Configure app tiles and access requirements",icon:C5,path:"/admin/apps",color:"bg-purple-500/10 text-purple-600"},{title:"Email Templates",description:"Customize system email templates",icon:Fo,path:"/admin/email-templates",color:"bg-sky-500/10 text-sky-600"},{title:"The LevelUp Brief",description:"Create popup briefs with videos, links, and polls",icon:mT,path:"/admin/levelup-brief",color:"bg-gradient-to-br from-primary/20 to-primary/10 text-primary"},{title:"Onboarding Checklist",description:"Manage getting started tasks for new users",icon:N2e,path:"/admin/onboarding-checklist",color:"bg-emerald-500/10 text-emerald-600"}]},community:{label:"Community & Support",sections:[{title:"Community Management",description:"Manage categories and private groups",icon:Tf,path:"/admin/community",color:"bg-cyan-500/10 text-cyan-600"},{title:"Support Tickets",description:"View and respond to agent support requests",icon:goe,path:"/admin/support-tickets",color:"bg-rose-500/10 text-rose-600"},{title:"Wishlist",description:"Review and manage community feature requests",icon:pM,path:"/admin/wishlist",color:"bg-yellow-500/10 text-yellow-600"},{title:"Membership Reviews",description:"View member feedback and ratings",icon:mh,path:"/admin/membership-reviews",color:"bg-amber-500/10 text-amber-600"},{title:"Weekly Digest",description:"Configure automated weekly email digests",icon:Fo,path:"/admin/weekly-digest",color:"bg-indigo-500/10 text-indigo-600"}]},insights:{label:"Insights",sections:[{title:"Analytics",description:"View activity logs and platform statistics",icon:_p,path:"/admin/analytics",color:"bg-emerald-500/10 text-emerald-600"}]},"agent-os":{label:"Agent OS",sections:[{title:"Agent OS Control Center",description:"Manage InnerCircle feature: relationship types, action types, scripts, plans & feature flags",icon:bp,path:"/admin/agent-os",color:"bg-gradient-to-br from-rose-500/20 to-pink-500/10 text-rose-600"},{title:"Listing Exchange",description:"Approve, feature, and moderate community listings",icon:ou,path:"/admin/listing-exchange",color:"bg-gradient-to-br from-blue-500/20 to-sky-500/10 text-blue-600"}]}};function j$e(){const t=Bs();return s.jsx(Jr,{title:"Admin Dashboard",children:s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{children:[s.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Admin Dashboard"}),s.jsx("p",{className:"text-muted-foreground",children:"Manage all aspects of your platform"})]}),s.jsxs(go,{defaultValue:"users",className:"w-full",children:[s.jsx(ao,{className:"w-full justify-start flex-wrap h-auto gap-1 bg-muted/50 p-1",children:Object.entries(mQ).map(([e,r])=>s.jsx(Bn,{value:e,className:"data-[state=active]:bg-background",children:r.label},e))}),Object.entries(mQ).map(([e,r])=>s.jsx(xs,{value:e,className:"mt-6",children:s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:r.sections.map(n=>s.jsxs(at,{className:"cursor-pointer hover:shadow-md transition-all hover:border-primary/50 group",onClick:()=>t(n.path),children:[s.jsxs(xr,{className:"pb-3",children:[s.jsx("div",{className:`w-10 h-10 rounded-lg flex items-center justify-center ${n.color} mb-2 group-hover:scale-110 transition-transform`,children:s.jsx(n.icon,{className:"h-5 w-5"})}),s.jsx(wr,{className:"text-base",children:n.title})]}),s.jsx(ct,{className:"pt-0",children:s.jsx(us,{className:"text-sm",children:n.description})})]},n.path))})},e))]})]})})}const ni=D.forwardRef(({className:t,...e},r)=>s.jsx("div",{className:"relative w-full overflow-auto",children:s.jsx("table",{ref:r,className:ar("w-full caption-bottom text-sm",t),...e})}));ni.displayName="Table";const si=D.forwardRef(({className:t,...e},r)=>s.jsx("thead",{ref:r,className:ar("[&_tr]:border-b",t),...e}));si.displayName="TableHeader";const ii=D.forwardRef(({className:t,...e},r)=>s.jsx("tbody",{ref:r,className:ar("[&_tr:last-child]:border-0",t),...e}));ii.displayName="TableBody";const S$e=D.forwardRef(({className:t,...e},r)=>s.jsx("tfoot",{ref:r,className:ar("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",t),...e}));S$e.displayName="TableFooter";const Dr=D.forwardRef(({className:t,...e},r)=>s.jsx("tr",{ref:r,className:ar("border-b transition-colors data-[state=selected]:bg-muted hover:bg-muted/50",t),...e}));Dr.displayName="TableRow";const Nt=D.forwardRef(({className:t,...e},r)=>s.jsx("th",{ref:r,className:ar("h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",t),...e}));Nt.displayName="TableHead";const xt=D.forwardRef(({className:t,...e},r)=>s.jsx("td",{ref:r,className:ar("p-4 align-middle [&:has([role=checkbox])]:pr-0",t),...e}));xt.displayName="TableCell";const N$e=D.forwardRef(({className:t,...e},r)=>s.jsx("caption",{ref:r,className:ar("mt-4 text-sm text-muted-foreground",t),...e}));N$e.displayName="TableCaption";const C$e=()=>{const{isAdmin:t}=rn(),e=Bs(),[r,n]=D.useState([]),[i,o]=D.useState(!0),[c,a]=D.useState(!1),[m,g]=D.useState(null);D.useEffect(()=>{if(!t){e("/dashboard");return}_()},[t]);const _=async()=>{try{const{data:A,error:I}=await ae.from("app_tiles").select("*").order("name");if(I)throw I;n(A||[])}catch(A){console.error("Error loading apps:",A),Dt.error("Failed to load apps")}finally{o(!1)}},j=async A=>{A.preventDefault();const I=new FormData(A.currentTarget),O={name:I.get("name"),description:I.get("description"),icon:I.get("icon"),app_id:I.get("app_id"),target_url:I.get("target_url"),required_tags:I.get("required_tags").split(",").map(R=>R.trim()).filter(Boolean)};try{if(m){const{error:R}=await ae.from("app_tiles").update(O).eq("id",m.id);if(R)throw R;Dt.success("App updated successfully")}else{const{error:R}=await ae.from("app_tiles").insert([O]);if(R)throw R;Dt.success("App created successfully")}a(!1),g(null),_()}catch(R){console.error("Error saving app:",R),Dt.error("Failed to save app")}},N=async A=>{if(confirm("Are you sure you want to delete this app?"))try{const{error:I}=await ae.from("app_tiles").delete().eq("id",A);if(I)throw I;Dt.success("App deleted successfully"),_()}catch(I){console.error("Error deleting app:",I),Dt.error("Failed to delete app")}},C=A=>{g(A),a(!0)},P=()=>{g(null),a(!0)};return i?s.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}):s.jsxs("div",{className:"min-h-screen bg-background",children:[s.jsx("header",{className:"border-b bg-card",children:s.jsx("div",{className:"container mx-auto px-4 py-4",children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-4",children:[s.jsxs(de,{variant:"ghost",size:"sm",onClick:()=>e("/dashboard"),children:[s.jsx(Ka,{className:"h-4 w-4 mr-2"}),"Back"]}),s.jsxs("div",{children:[s.jsx("h1",{className:"text-2xl font-bold",children:"Manage Apps"}),s.jsx("p",{className:"text-sm text-muted-foreground",children:"Create and configure application tiles"})]})]}),s.jsxs(mn,{open:c,onOpenChange:a,children:[s.jsx(Do,{asChild:!0,children:s.jsxs(de,{onClick:P,children:[s.jsx(Qn,{className:"mr-2 h-4 w-4"}),"Add App"]})}),s.jsxs(pn,{className:"max-w-2xl",children:[s.jsxs(xn,{children:[s.jsx(gn,{children:m?"Edit App":"Create New App"}),s.jsx(fi,{children:"Configure the application tile settings"})]}),s.jsxs("form",{onSubmit:j,className:"space-y-4",children:[s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"name",children:"App Name"}),s.jsx(Et,{id:"name",name:"name",defaultValue:m==null?void 0:m.name,required:!0})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"app_id",children:"App ID"}),s.jsx(Et,{id:"app_id",name:"app_id",defaultValue:m==null?void 0:m.app_id,placeholder:"agent_connect",required:!0})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"description",children:"Description"}),s.jsx(mi,{id:"description",name:"description",defaultValue:m==null?void 0:m.description})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"icon",children:"Icon (emoji)"}),s.jsx(Et,{id:"icon",name:"icon",defaultValue:m==null?void 0:m.icon,placeholder:"🚀",required:!0})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"target_url",children:"Target URL"}),s.jsx(Et,{id:"target_url",name:"target_url",type:"url",defaultValue:m==null?void 0:m.target_url,required:!0})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"required_tags",children:"Required Tags (comma-separated)"}),s.jsx(Et,{id:"required_tags",name:"required_tags",defaultValue:m==null?void 0:m.required_tags.join(", "),placeholder:"levelup-member, agent-connect"})]}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(de,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),s.jsx(de,{type:"submit",children:m?"Update":"Create"})]})]})]})]})]})})}),s.jsx("div",{className:"container mx-auto px-4 py-8",children:s.jsxs(at,{children:[s.jsxs(xr,{children:[s.jsx(wr,{children:"Application Tiles"}),s.jsx(us,{children:"Manage the apps that appear on the member dashboard"})]}),s.jsx(ct,{children:r.length===0?s.jsxs("div",{className:"text-center py-12",children:[s.jsx("p",{className:"text-muted-foreground mb-4",children:"No apps configured yet"}),s.jsxs(de,{onClick:P,children:[s.jsx(Qn,{className:"mr-2 h-4 w-4"}),"Create First App"]})]}):s.jsxs(ni,{children:[s.jsx(si,{children:s.jsxs(Dr,{children:[s.jsx(Nt,{children:"Icon"}),s.jsx(Nt,{children:"Name"}),s.jsx(Nt,{children:"App ID"}),s.jsx(Nt,{children:"Target URL"}),s.jsx(Nt,{children:"Tags"}),s.jsx(Nt,{className:"text-right",children:"Actions"})]})}),s.jsx(ii,{children:r.map(A=>s.jsxs(Dr,{children:[s.jsx(xt,{className:"text-2xl",children:A.icon}),s.jsx(xt,{className:"font-medium",children:A.name}),s.jsx(xt,{className:"font-mono text-sm",children:A.app_id}),s.jsx(xt,{className:"text-sm text-muted-foreground max-w-xs truncate",children:A.target_url}),s.jsx(xt,{children:s.jsx("div",{className:"flex flex-wrap gap-1",children:A.required_tags.map(I=>s.jsx("span",{className:"text-xs bg-secondary text-secondary-foreground px-2 py-1 rounded",children:I},I))})}),s.jsx(xt,{className:"text-right",children:s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(de,{size:"sm",variant:"ghost",onClick:()=>C(A),children:s.jsx(io,{className:"h-4 w-4"})}),s.jsx(de,{size:"sm",variant:"ghost",onClick:()=>N(A.id),children:s.jsx(oi,{className:"h-4 w-4"})})]})})]},A.id))})]})})]})})]})},gQ=({expiresAt:t,className:e})=>{const r=new Date().getTime(),n=new Date(t).getTime(),i=Math.ceil((n-r)/(1e3*60*60*24));return i<=0?s.jsxs(ir,{variant:"destructive",className:ar("gap-1",e),children:[s.jsx(yT,{className:"h-3 w-3"}),"Trial Expired"]}):i<=1?s.jsxs(ir,{variant:"destructive",className:ar("gap-1",e),children:[s.jsx(No,{className:"h-3 w-3"}),"Trial: <1 day left"]}):i<=3?s.jsxs(ir,{className:ar("gap-1 bg-amber-500 hover:bg-amber-600",e),children:[s.jsx(No,{className:"h-3 w-3"}),"Trial: ",i," days left"]}):s.jsxs(ir,{variant:"secondary",className:ar("gap-1",e),children:[s.jsx(No,{className:"h-3 w-3"}),"Trial: ",i," days left"]})},gme=({open:t,onOpenChange:e,brokerages:r,fixedBrokerageId:n,onSuccess:i})=>{const{toast:o}=Ri(),c=D.useRef(null),[a,m]=D.useState([]),[g,_]=D.useState(""),[j,N]=D.useState(!1),[C,P]=D.useState("upload"),[A,I]=D.useState(null),O=()=>{m([]),_(""),P("upload"),I(null),c.current&&(c.current.value="")},R=()=>{O(),e(!1)},z=te=>{const X=te.split(` `).map(ve=>ve.trim()).filter(ve=>ve);if(X.length===0)return[];const ie=X[0].toLowerCase(),xe=ie.includes("first")||ie.includes("last")||ie.includes("email")||ie.includes("name")?X.slice(1):X,pe=[];for(const ve of xe){const ke=(ve.includes(" ")?ve.split(" "):ve.split(",")).map(Ce=>Ce.trim().replace(/^["']|["']$/g,""));if(ke.length>=2){let Ce="",Se="",je="";if(ke.length===2){const _e=ke[0].split(" ");Ce=_e[0]||"",Se=_e.slice(1).join(" ")||"",je=ke[1]}else ke.length>=3&&(Ce=ke[0],Se=ke[1],je=ke[2]);const bt=/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(je);pe.push({firstName:Ce.trim(),lastName:Se.trim(),email:je.trim().toLowerCase(),isValid:bt&&Ce.trim().length>0,error:bt?Ce.trim()?void 0:"Missing name":"Invalid email"})}}return pe},W=te=>{var he;const X=(he=te.target.files)==null?void 0:he[0];if(!X)return;const ie=new FileReader;ie.onload=xe=>{var ge;const pe=(ge=xe.target)==null?void 0:ge.result,ve=z(pe);if(ve.length===0){o({title:"No data found",description:"The CSV file appears to be empty or in an unsupported format.",variant:"destructive"});return}m(ve),P("preview")},ie.readAsText(X)},V=async()=>{const te=a.filter(ie=>ie.isValid);if(te.length===0){o({title:"No valid users",description:"There are no valid users to import.",variant:"destructive"});return}const X=n||g||null;N(!0);try{const{data:{session:ie}}=await ae.auth.getSession(),he=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/bulk-create-users",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${ie==null?void 0:ie.access_token}`},body:JSON.stringify({users:te.map(pe=>({firstName:pe.firstName,lastName:pe.lastName,email:pe.email})),brokerageId:X})}),xe=await he.json();if(!he.ok)throw new Error(xe.error||"Failed to import users");I(xe),P("result"),xe.created>0&&i(),o({title:"Import Complete",description:`${xe.created} user(s) created successfully.${xe.failed>0?` ${xe.failed} failed.`:""}`})}catch(ie){console.error("Import error:",ie),o({title:"Import Failed",description:ie.message||"Failed to import users",variant:"destructive"})}finally{N(!1)}},K=a.filter(te=>te.isValid).length,Q=a.filter(te=>!te.isValid).length;return s.jsx(mn,{open:t,onOpenChange:R,children:s.jsxs(pn,{className:"max-w-2xl max-h-[85vh] overflow-hidden flex flex-col",children:[s.jsxs(xn,{children:[s.jsxs(gn,{className:"flex items-center gap-2",children:[s.jsx(JR,{className:"h-5 w-5"}),"Import Agents from CSV"]}),s.jsx(fi,{children:"Upload a CSV file with agent information. Each row should contain First Name, Last Name, and Email."})]}),C==="upload"&&s.jsxs("div",{className:"space-y-4 py-4",children:[s.jsxs("div",{className:"border-2 border-dashed rounded-lg p-8 text-center",children:[s.jsx("input",{type:"file",accept:".csv,.txt",ref:c,onChange:W,className:"hidden"}),s.jsx(Vu,{className:"h-10 w-10 mx-auto text-muted-foreground mb-4"}),s.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Click to upload or drag and drop a CSV file"}),s.jsx(de,{onClick:()=>{var te;return(te=c.current)==null?void 0:te.click()},children:"Select CSV File"})]}),s.jsxs("div",{className:"bg-muted/50 rounded-lg p-4 text-sm",children:[s.jsx("p",{className:"font-medium mb-2",children:"Expected CSV Format:"}),s.jsxs("code",{className:"text-xs block bg-background p-2 rounded",children:["First Name, Last Name, Email",s.jsx("br",{}),"John, Doe, john@example.com",s.jsx("br",{}),"Jane, Smith, jane@example.com"]}),s.jsx("p",{className:"text-muted-foreground mt-2 text-xs",children:"The first row can be a header (optional). Columns can also be tab-separated."})]})]}),C==="preview"&&s.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col space-y-4",children:[!n&&r&&r.length>0&&s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Assign to Brokerage (optional)"}),s.jsxs(Kn,{value:g||"none",onValueChange:te=>_(te==="none"?"":te),children:[s.jsx(qn,{children:s.jsx(Zn,{placeholder:"Select a brokerage..."})}),s.jsxs(Hn,{children:[s.jsx(_r,{value:"none",children:"No brokerage"}),r.map(te=>s.jsx(_r,{value:te.id,children:te.name},te.id))]})]})]}),s.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(E_,{className:"h-4 w-4 text-green-500"}),s.jsxs("span",{children:[K," valid"]})]}),Q>0&&s.jsxs("div",{className:"flex items-center gap-2 text-destructive",children:[s.jsx(sx,{className:"h-4 w-4"}),s.jsxs("span",{children:[Q," invalid"]})]})]}),s.jsxs("div",{className:"flex-1 overflow-auto border rounded-lg",children:[s.jsxs(ni,{children:[s.jsx(si,{children:s.jsxs(Dr,{className:"bg-muted/30",children:[s.jsx(Nt,{children:"First Name"}),s.jsx(Nt,{children:"Last Name"}),s.jsx(Nt,{children:"Email"}),s.jsx(Nt,{children:"Status"})]})}),s.jsx(ii,{children:a.slice(0,100).map((te,X)=>s.jsxs(Dr,{children:[s.jsx(xt,{children:te.firstName}),s.jsx(xt,{children:te.lastName}),s.jsx(xt,{children:te.email}),s.jsx(xt,{children:te.isValid?s.jsx(ir,{variant:"default",className:"bg-green-500/10 text-green-600",children:"Valid"}):s.jsx(ir,{variant:"destructive",children:te.error||"Invalid"})})]},X))})]}),a.length>100&&s.jsxs("p",{className:"text-sm text-muted-foreground text-center py-2",children:["Showing first 100 of ",a.length," users"]})]})]}),C==="result"&&A&&s.jsxs("div",{className:"space-y-4 py-4",children:[s.jsxs("div",{className:"text-center",children:[s.jsx(E_,{className:"h-12 w-12 mx-auto text-green-500 mb-4"}),s.jsx("h3",{className:"text-lg font-semibold",children:"Import Complete"}),s.jsxs("p",{className:"text-muted-foreground mt-2",children:[A.created," agent(s) created and invited"]}),A.failed>0&&s.jsxs("p",{className:"text-destructive mt-1",children:[A.failed," failed to create"]})]}),A.errors.length>0&&s.jsxs("div",{className:"bg-destructive/10 border border-destructive/20 rounded-lg p-4 max-h-40 overflow-auto",children:[s.jsx("p",{className:"font-medium text-destructive text-sm mb-2",children:"Errors:"}),s.jsxs("ul",{className:"text-sm text-muted-foreground space-y-1",children:[A.errors.slice(0,10).map((te,X)=>s.jsxs("li",{children:["• ",te]},X)),A.errors.length>10&&s.jsxs("li",{children:["...and ",A.errors.length-10," more"]})]})]})]}),s.jsxs(zi,{children:[C==="upload"&&s.jsx(de,{variant:"outline",onClick:R,children:"Cancel"}),C==="preview"&&s.jsxs(s.Fragment,{children:[s.jsx(de,{variant:"outline",onClick:O,children:"Back"}),s.jsx(de,{onClick:V,disabled:j||K===0,children:j?s.jsxs(s.Fragment,{children:[s.jsx(Ps,{className:"mr-2 h-4 w-4 animate-spin"}),"Importing..."]}):`Import ${K} Agent${K!==1?"s":""}`})]}),C==="result"&&s.jsx(de,{onClick:R,children:"Done"})]})]})})},k$e=()=>{const t=Bs(),{user:e,isAdmin:r}=rn(),{toast:n}=Ri(),[i,o]=D.useState([]),[c,a]=D.useState([]),[m,g]=D.useState([]),[_,j]=D.useState(!0),[N,C]=D.useState({}),[P,A]=D.useState(!1),[I,O]=D.useState({email:"",name:"",password:"",brokerage_id:"",role:"user"}),[R,z]=D.useState(!1),[W,V]=D.useState(""),[K,Q]=D.useState("all"),[te,X]=D.useState("all"),[ie,he]=D.useState("all"),[xe,pe]=D.useState(!1),[ve,ge]=D.useState(!1),[ke,Ce]=D.useState(null),[Se,je]=D.useState(null),[et,bt]=D.useState(!1),[_e,Ye]=D.useState({name:"",email:"",brokerage_id:""}),[pt,nt]=D.useState(null),[Qt,gt]=D.useState(!1),[Me,Oe]=D.useState(""),[Ie,Be]=D.useState(!1),[Pe,ut]=D.useState(!1),[jt,$t]=D.useState(null),[Ht,Lt]=D.useState(""),[Kt,Ar]=D.useState(!1),[rt,We]=D.useState(!1),[_t,Gt]=D.useState(null),[rr,pr]=D.useState(!1),[kr,Hr]=D.useState(!1),[Fn,Os]=D.useState(null),[ia,pa]=D.useState(""),[zo,Xo]=D.useState(!1),[Xs,Ma]=D.useState({email:"",name:"",password:""}),[Qo,ec]=D.useState(!1),[yl,tc]=D.useState(!1),[Jo,wh]=D.useState("");D.useEffect(()=>{!e||!r||(xa(),Qs())},[e,r]);const xa=async()=>{try{j(!0);const{data:Ge,error:ur}=await ae.functions.invoke("get-user-details");if(ur)throw ur;o(Ge.users||[]),g(Ge.brokerages||[])}catch(Ge){console.error("Error loading members:",Ge),n({title:"Error",description:"Failed to load members",variant:"destructive"})}finally{j(!1)}},Qs=async()=>{try{const{data:Ge,error:ur}=await ae.from("app_tiles").select("id, name, icon, app_id, required_tags").order("name");if(ur)throw ur;a(Ge||[])}catch(Ge){console.error("Error loading apps:",Ge),n({title:"Error",description:"Failed to load apps",variant:"destructive"})}},La=async Ge=>{if(!_e.name.trim()||!_e.email.trim()){n({title:"Error",description:"Name and email are required",variant:"destructive"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(_e.email)){n({title:"Error",description:"Please enter a valid email address",variant:"destructive"});return}try{const{error:jr}=await ae.from("profiles").update({name:_e.name.trim(),email:_e.email.trim(),brokerage_id:_e.brokerage_id||null}).eq("id",Ge);if(jr)throw jr;n({title:"Success",description:"Member details updated successfully"}),Ce(null),xa()}catch(jr){console.error("Error updating member:",jr),n({title:"Error",description:jr.message||"Failed to update member",variant:"destructive"})}},Ss=async Ge=>{try{const{data:{session:ur}}=await ae.auth.getSession(),jr=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${ur==null?void 0:ur.access_token}`},body:JSON.stringify({userId:Ge})}),Vr=await jr.json();if(!jr.ok)throw new Error(Vr.error||"Failed to resend welcome email");n({title:"Success",description:"Welcome email sent successfully"})}catch(ur){console.error("Error resending welcome email:",ur),n({title:"Error",description:ur.message||"Failed to resend welcome email",variant:"destructive"})}},bi=async(Ge,ur)=>{if(confirm(`Are you sure you want to delete ${ur}? This action cannot be undone.`))try{const{data:{session:jr}}=await ae.auth.getSession(),Vr=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${jr==null?void 0:jr.access_token}`},body:JSON.stringify({userId:Ge})}),cn=await Vr.json();if(!Vr.ok)throw new Error(cn.error||"Failed to delete user");n({title:"Success",description:"User deleted successfully"}),xa()}catch(jr){console.error("Error deleting user:",jr),n({title:"Error",description:jr.message||"Failed to delete user",variant:"destructive"})}},ki=async()=>{if(!I.email||!I.name||!I.password){n({title:"Error",description:"Please fill in all fields",variant:"destructive"});return}A(!0);try{const{data:{session:Ge}}=await ae.auth.getSession(),ur=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Ge==null?void 0:Ge.access_token}`},body:JSON.stringify(I)}),jr=await ur.json();if(!ur.ok)throw new Error(jr.error||"Failed to create user");I.role&&I.role!=="user"&&jr.userId&&await yo(jr.userId,I.role,"add"),n({title:"Success",description:`User ${I.email} created successfully`}),O({email:"",name:"",password:"",brokerage_id:"",role:"user"}),z(!1),xa()}catch(Ge){console.error("Error creating user:",Ge),n({title:"Error",description:Ge.message||"Failed to create user",variant:"destructive"})}finally{A(!1)}},yo=async(Ge,ur,jr)=>{try{const{data:{session:Vr}}=await ae.auth.getSession(),cn=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Vr==null?void 0:Vr.access_token}`},body:JSON.stringify({userId:Ge,role:ur,action:jr})}),Ns=await cn.json();if(!cn.ok)throw new Error(Ns.error||"Failed to manage user role");n({title:"Success",description:`Role ${jr==="add"?"added":"removed"} successfully`}),xa()}catch(Vr){console.error("Error managing user role:",Vr),n({title:"Error",description:Vr.message||"Failed to manage user role",variant:"destructive"})}},Wt=(Ge,ur)=>ur.length===0?!0:ur.some(jr=>Ge.includes(jr)),xo=async(Ge,ur,jr)=>{const Vr=`${Ge}-${ur.id}`;nt(Vr);try{if(jr){const cn=i.find(Mi=>Mi.id===Ge),Ns=ur.required_tags.filter(Mi=>cn==null?void 0:cn.tags.includes(Mi));for(const Mi of Ns){const{error:Zi}=await ae.from("user_tags").delete().eq("user_id",Ge).eq("tag",Mi);if(Zi)throw Zi}n({title:"Access Removed",description:`Removed access to ${ur.name}`})}else if(ur.required_tags.length>0){const{error:cn}=await ae.from("user_tags").insert({user_id:Ge,tag:ur.required_tags[0]});if(cn)throw cn;n({title:"Access Granted",description:`Granted access to ${ur.name}`})}await xa()}catch(cn){console.error("Error toggling access:",cn),n({title:"Error",description:cn.message||"Failed to update access",variant:"destructive"})}finally{nt(null)}},zc=async()=>{const Ge=Me.trim();if(!Ge){n({title:"Error",description:"Brokerage name is required",variant:"destructive"});return}if(Ge.length>100){n({title:"Error",description:"Brokerage name must be less than 100 characters",variant:"destructive"});return}if(m.find(jr=>jr.name.toLowerCase()===Ge.toLowerCase())){n({title:"Error",description:"A brokerage with this name already exists",variant:"destructive"});return}Be(!0);try{const{error:jr}=await ae.from("brokerages").insert({name:Ge});if(jr)throw jr;n({title:"Success",description:`Brokerage "${Ge}" created successfully`}),Oe(""),gt(!1),xa()}catch(jr){console.error("Error creating brokerage:",jr),n({title:"Error",description:jr.message||"Failed to create brokerage",variant:"destructive"})}finally{Be(!1)}},oo=Ge=>{$t(Ge),Lt(Ge.name),ut(!0)},Xn=()=>{$t(null),Lt(""),ut(!1)},Bo=async()=>{if(!jt)return;const Ge=Ht.trim();if(!Ge){n({title:"Error",description:"Brokerage name is required",variant:"destructive"});return}if(Ge.length>100){n({title:"Error",description:"Brokerage name must be less than 100 characters",variant:"destructive"});return}Ar(!0);try{const{error:ur}=await ae.from("brokerages").update({name:Ge}).eq("id",jt.id);if(ur)throw ur;n({title:"Success",description:"Brokerage updated successfully"}),Xn(),xa()}catch(ur){console.error("Error updating brokerage:",ur),n({title:"Error",description:ur.message||"Failed to update brokerage",variant:"destructive"})}finally{Ar(!1)}},Px=async(Ge,ur)=>{var jr;try{const{error:Vr}=await ae.from("profiles").update({brokerage_id:ur}).eq("id",Ge);if(Vr)throw Vr;const{data:{session:cn}}=await ae.auth.getSession(),Ns=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${cn==null?void 0:cn.access_token}`},body:JSON.stringify({userId:Ge,role:"brokerage_manager",action:"add"})}),Mi=await Ns.json();if(!Ns.ok&&!((jr=Mi.error)!=null&&jr.includes("duplicate")))throw new Error(Mi.error||"Failed to add role");n({title:"Success",description:"Manager assigned to brokerage"}),xa()}catch(Vr){console.error("Error assigning manager:",Vr),n({title:"Error",description:Vr.message||"Failed to assign manager",variant:"destructive"})}},jh=Ge=>{Gt(Ge),We(!0)},Fp=async()=>{if(_t){pr(!0);try{const Ge=i.filter(Vr=>Vr.brokerage_id===_t.id),{data:{session:ur}}=await ae.auth.getSession();for(const Vr of Ge){const cn=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${ur==null?void 0:ur.access_token}`},body:JSON.stringify({userId:Vr.id})});if(!cn.ok){const Ns=await cn.json();console.error(`Failed to delete user ${Vr.email}:`,Ns.error)}}const{error:jr}=await ae.from("brokerages").delete().eq("id",_t.id);if(jr)throw jr;n({title:"Success",description:`Brokerage "${_t.name}" and ${Ge.length} member(s) deleted`}),We(!1),Gt(null),xa()}catch(Ge){console.error("Error deleting brokerage:",Ge),n({title:"Error",description:Ge.message||"Failed to delete brokerage",variant:"destructive"})}finally{pr(!1)}}},vt=Ge=>{Os(Ge),pa(""),Hr(!0)},ue=()=>{Os(null),pa(""),Hr(!1)},be=async Ge=>{try{const{error:ur}=await ae.from("profiles").update({brokerage_id:null}).eq("id",Ge);if(ur)throw ur;n({title:"Success",description:"User removed from brokerage"}),xa()}catch(ur){console.error("Error removing user from brokerage:",ur),n({title:"Error",description:ur.message||"Failed to remove user",variant:"destructive"})}},Re=async(Ge,ur)=>{try{const{error:jr}=await ae.from("profiles").update({brokerage_id:ur}).eq("id",Ge);if(jr)throw jr;n({title:"Success",description:"User added to brokerage"}),xa()}catch(jr){console.error("Error adding user to brokerage:",jr),n({title:"Error",description:jr.message||"Failed to add user",variant:"destructive"})}},tt=async()=>{if(!Fn||!Xs.email||!Xs.name||!Xs.password){n({title:"Error",description:"Please fill in all fields",variant:"destructive"});return}ec(!0);try{const{data:{session:Ge}}=await ae.auth.getSession(),ur=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Ge==null?void 0:Ge.access_token}`},body:JSON.stringify({...Xs,brokerage_id:Fn.id,role:"user"})}),jr=await ur.json();if(!ur.ok)throw new Error(jr.error||"Failed to create agent");n({title:"Success",description:`Agent ${Xs.email} created successfully`}),Ma({email:"",name:"",password:""}),Xo(!1),xa()}catch(Ge){console.error("Error creating agent:",Ge),n({title:"Error",description:Ge.message||"Failed to create agent",variant:"destructive"})}finally{ec(!1)}},Xe=Ge=>i.filter(ur=>ur.brokerage_id===Ge),lt=Ge=>{const ur=Xe(Ge);if(!ia)return ur;const jr=ia.toLowerCase();return ur.filter(Vr=>Vr.name.toLowerCase().includes(jr)||Vr.email.toLowerCase().includes(jr))},Ct=Ge=>i.filter(ur=>ur.brokerage_id!==Ge),dt=i.filter(Ge=>{var ur;if(W){const jr=W.toLowerCase();if(!(Ge.name.toLowerCase().includes(jr)||Ge.email.toLowerCase().includes(jr)||((ur=Ge.brokerage_name)==null?void 0:ur.toLowerCase().includes(jr))))return!1}return!(K==="claimed"&&!Ge.claimed||K==="unclaimed"&&Ge.claimed||te!=="all"&&!Ge.roles.includes(te)||ie==="trial"&&!Ge.is_trial||ie==="non-trial"&&Ge.is_trial)}),St=async(Ge,ur)=>{pe(!0);try{const jr=i.find(Mi=>Mi.id===Ge);if(!jr)return;const Vr=jr.trial_expires_at?new Date(jr.trial_expires_at):new Date,cn=new Date(Vr.getTime()+ur*24*60*60*1e3),{error:Ns}=await ae.from("profiles").update({trial_expires_at:cn.toISOString()}).eq("id",Ge);if(Ns)throw Ns;n({title:"Trial Extended",description:`Trial extended by ${ur} days`}),xa()}catch(jr){console.error("Error extending trial:",jr),n({title:"Error",description:jr.message||"Failed to extend trial",variant:"destructive"})}finally{pe(!1)}},sr=async Ge=>{ge(!0);try{const{error:ur}=await ae.from("profiles").update({is_trial:!1,trial_expires_at:null,trial_started_at:null,trial_claimed_at:null}).eq("id",Ge);if(ur)throw ur;n({title:"Account Converted",description:"User has been converted to a full account"}),xa(),Ir()}catch(ur){console.error("Error converting trial:",ur),n({title:"Error",description:ur.message||"Failed to convert account",variant:"destructive"})}finally{ge(!1)}},Ut=Ge=>{je(Ge),Ye({name:Ge.name,email:Ge.email,brokerage_id:Ge.brokerage_id||""}),bt(!0)},Ir=()=>{je(null),bt(!1),Ye({name:"",email:"",brokerage_id:""})},en=async()=>{Se&&(await La(Se.id),Ir())};return _?s.jsx(Jr,{title:"Members",children:s.jsx("div",{className:"flex items-center justify-center py-20",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):s.jsxs(Jr,{title:"Members",children:[s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("h1",{className:"text-2xl font-semibold",children:"Members"}),s.jsxs("div",{className:"flex gap-2",children:[s.jsxs(de,{size:"sm",variant:"outline",onClick:()=>tc(!0),children:[s.jsx(JR,{className:"mr-2 h-4 w-4"}),"Import CSV"]}),s.jsxs(mn,{open:R,onOpenChange:z,children:[s.jsx(Do,{asChild:!0,children:s.jsxs(de,{size:"sm",children:[s.jsx(yM,{className:"mr-2 h-4 w-4"}),"Add Member"]})}),s.jsxs(pn,{children:[s.jsxs(xn,{children:[s.jsx(gn,{children:"Create New User"}),s.jsx(fi,{children:"Add a new user to the system. They'll be able to sign in immediately."})]}),s.jsxs("div",{className:"space-y-4 py-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"name",children:"Name"}),s.jsx(Et,{id:"name",placeholder:"John Doe",value:I.name,onChange:Ge=>O({...I,name:Ge.target.value})})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"email",children:"Email"}),s.jsx(Et,{id:"email",type:"email",placeholder:"john@example.com",value:I.email,onChange:Ge=>O({...I,email:Ge.target.value})})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"password",children:"Password"}),s.jsx(Et,{id:"password",type:"password",placeholder:"Min 6 characters",value:I.password,onChange:Ge=>O({...I,password:Ge.target.value})})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"brokerage",children:"Brokerage"}),s.jsxs(Kn,{value:I.brokerage_id||"none",onValueChange:Ge=>O({...I,brokerage_id:Ge==="none"?"":Ge}),children:[s.jsx(qn,{id:"brokerage",children:s.jsx(Zn,{placeholder:"Select brokerage (optional)"})}),s.jsxs(Hn,{children:[s.jsx(_r,{value:"none",children:"None"}),m.map(Ge=>s.jsx(_r,{value:Ge.id,children:Ge.name},Ge.id))]})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"role",children:"Role"}),s.jsxs(Kn,{value:I.role,onValueChange:Ge=>O({...I,role:Ge}),children:[s.jsx(qn,{id:"role",children:s.jsx(Zn,{placeholder:"Select role"})}),s.jsxs(Hn,{children:[s.jsx(_r,{value:"user",children:"User"}),s.jsx(_r,{value:"moderator",children:"Moderator"}),s.jsx(_r,{value:"brokerage_manager",children:"Brokerage Manager"}),s.jsx(_r,{value:"admin",children:"Admin"})]})]})]})]}),s.jsxs(zi,{children:[s.jsx(de,{variant:"outline",onClick:()=>z(!1),children:"Cancel"}),s.jsx(de,{onClick:ki,disabled:P,children:P?"Creating...":"Create User"})]})]})]})]})]}),s.jsxs(go,{defaultValue:"members",className:"space-y-6",children:[s.jsxs(ao,{children:[s.jsx(Bn,{value:"members",children:"Members"}),s.jsx(Bn,{value:"brokerages",children:"Brokerages"}),s.jsx(Bn,{value:"access",children:"Access Matrix"})]}),s.jsxs(xs,{value:"members",className:"space-y-4",children:[s.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[s.jsxs("div",{className:"relative flex-1 min-w-[200px] max-w-md",children:[s.jsx(ba,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),s.jsx(Et,{placeholder:"Search members...",value:W,onChange:Ge=>V(Ge.target.value),className:"pl-10 h-9"})]}),s.jsxs(Kn,{value:K,onValueChange:Ge=>Q(Ge),children:[s.jsx(qn,{className:"w-[130px] h-9",children:s.jsx(Zn,{})}),s.jsxs(Hn,{children:[s.jsx(_r,{value:"all",children:"All Status"}),s.jsx(_r,{value:"claimed",children:"Active"}),s.jsx(_r,{value:"unclaimed",children:"Pending"})]})]}),s.jsxs(Kn,{value:te,onValueChange:X,children:[s.jsx(qn,{className:"w-[130px] h-9",children:s.jsx(Zn,{})}),s.jsxs(Hn,{children:[s.jsx(_r,{value:"all",children:"All Roles"}),s.jsx(_r,{value:"admin",children:"Admin"}),s.jsx(_r,{value:"brokerage_manager",children:"Manager"}),s.jsx(_r,{value:"user",children:"User"})]})]}),s.jsxs(Kn,{value:ie,onValueChange:Ge=>he(Ge),children:[s.jsx(qn,{className:"w-[130px] h-9",children:s.jsx(Zn,{})}),s.jsxs(Hn,{children:[s.jsx(_r,{value:"all",children:"All Users"}),s.jsx(_r,{value:"trial",children:"Trial Only"}),s.jsx(_r,{value:"non-trial",children:"Full Only"})]})]}),(W||K!=="all"||te!=="all"||ie!=="all")&&s.jsxs(de,{variant:"ghost",size:"sm",className:"h-9",onClick:()=>{V(""),Q("all"),X("all"),he("all")},children:[s.jsx(Ni,{className:"h-4 w-4 mr-1"}),"Clear"]}),s.jsxs("span",{className:"text-sm text-muted-foreground ml-auto",children:[dt.length," members"]})]}),s.jsx("div",{className:"border rounded-lg bg-card overflow-hidden",children:s.jsxs(ni,{children:[s.jsx(si,{children:s.jsxs(Dr,{className:"bg-muted/30 hover:bg-muted/30",children:[s.jsx(Nt,{className:"font-semibold",children:"Name"}),s.jsx(Nt,{className:"font-semibold",children:"Brokerage"}),s.jsx(Nt,{className:"font-semibold",children:"Status"}),s.jsx(Nt,{className:"font-semibold",children:"Role"}),s.jsx(Nt,{className:"font-semibold",children:"Last Login"}),s.jsx(Nt,{className:"w-[100px]"})]})}),s.jsx(ii,{children:dt.length===0?s.jsx(Dr,{children:s.jsx(xt,{colSpan:6,className:"text-center py-12 text-muted-foreground",children:"No members found"})}):dt.map(Ge=>s.jsxs(Dr,{className:"hover:bg-muted/30",children:[s.jsx(xt,{children:s.jsxs("div",{children:[s.jsx("button",{onClick:()=>Ut(Ge),className:"text-primary hover:underline font-medium text-left",children:Ge.name}),s.jsx("div",{className:"text-xs text-muted-foreground",children:Ge.email})]})}),s.jsx(xt,{className:"text-muted-foreground",children:Ge.brokerage_name||"—"}),s.jsx(xt,{children:s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx(ir,{variant:Ge.claimed?"default":"secondary",className:Ge.claimed?"bg-primary text-primary-foreground w-fit":"w-fit",children:Ge.claimed?"Active":"Pending"}),Ge.is_trial&&Ge.trial_expires_at&&s.jsx(gQ,{expiresAt:Ge.trial_expires_at,className:"w-fit"})]})}),s.jsx(xt,{children:Ge.roles.length>0?s.jsx("span",{className:"text-sm capitalize",children:Ge.roles[0]}):s.jsx("span",{className:"text-muted-foreground",children:"—"})}),s.jsx(xt,{className:"text-muted-foreground",children:Ge.last_sign_in_at?new Date(Ge.last_sign_in_at).toLocaleDateString():"—"}),s.jsx(xt,{children:s.jsxs("div",{className:"flex gap-1 justify-end",children:[s.jsx(de,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Ut(Ge),title:"Edit member",children:s.jsx(io,{className:"h-4 w-4"})}),s.jsx(de,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Ss(Ge.id),title:"Resend welcome email",children:s.jsx(Fo,{className:"h-4 w-4"})}),s.jsx(de,{size:"icon",variant:"ghost",className:"h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:()=>bi(Ge.id,Ge.name),title:"Delete user",children:s.jsx(oi,{className:"h-4 w-4"})})]})})]},Ge.id))})]})})]}),s.jsx(mn,{open:et,onOpenChange:bt,children:s.jsxs(pn,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[s.jsxs(xn,{children:[s.jsx(gn,{children:"Edit Member"}),s.jsx(fi,{children:"Update member details, roles, and app access"})]}),Se&&s.jsxs("div",{className:"space-y-6 py-4",children:[s.jsxs("div",{className:"space-y-4",children:[s.jsx("h3",{className:"text-sm font-semibold",children:"Basic Information"}),s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"edit-name",children:"Name"}),s.jsx(Et,{id:"edit-name",value:_e.name,onChange:Ge=>Ye({..._e,name:Ge.target.value}),maxLength:100})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"edit-email",children:"Email"}),s.jsx(Et,{id:"edit-email",type:"email",value:_e.email,onChange:Ge=>Ye({..._e,email:Ge.target.value}),maxLength:255})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"edit-brokerage",children:"Brokerage"}),s.jsxs(Kn,{value:_e.brokerage_id||"none",onValueChange:Ge=>Ye({..._e,brokerage_id:Ge==="none"?"":Ge}),children:[s.jsx(qn,{id:"edit-brokerage",children:s.jsx(Zn,{placeholder:"Select brokerage"})}),s.jsxs(Hn,{children:[s.jsx(_r,{value:"none",children:"None"}),m.map(Ge=>s.jsx(_r,{value:Ge.id,children:Ge.name},Ge.id))]})]})]})]}),s.jsxs("div",{className:"space-y-3",children:[s.jsx("h3",{className:"text-sm font-semibold",children:"Roles"}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[Se.roles.map(Ge=>s.jsxs(ir,{variant:"default",className:"gap-1",children:[s.jsx(n2,{className:"h-3 w-3"}),Ge,s.jsx("button",{onClick:()=>yo(Se.id,Ge,"remove"),className:"ml-1 rounded-full hover:bg-destructive/20",title:"Remove role",children:s.jsx(Ni,{className:"h-3 w-3"})})]},Ge)),Se.roles.length===0&&s.jsx("span",{className:"text-sm text-muted-foreground",children:"No roles assigned"})]}),s.jsxs(Kn,{onValueChange:Ge=>yo(Se.id,Ge,"add"),children:[s.jsx(qn,{className:"w-[200px]",children:s.jsx(Zn,{placeholder:"Add role..."})}),s.jsxs(Hn,{children:[!Se.roles.includes("admin")&&s.jsx(_r,{value:"admin",children:"Admin"}),!Se.roles.includes("brokerage_manager")&&s.jsx(_r,{value:"brokerage_manager",children:"Brokerage Manager"}),!Se.roles.includes("user")&&s.jsx(_r,{value:"user",children:"User"})]})]})]}),s.jsxs("div",{className:"space-y-3",children:[s.jsx("h3",{className:"text-sm font-semibold",children:"App Access"}),s.jsx("p",{className:"text-sm text-muted-foreground",children:"Toggle which apps this member can access"}),s.jsx("div",{className:"grid gap-3",children:c.map(Ge=>{const ur=Wt(Se.tags,Ge.required_tags),jr=`${Se.id}-${Ge.id}`,Vr=pt===jr,cn=Ge.required_tags.length===0;return s.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border bg-muted/30",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"text-xl",children:Ge.icon}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-sm",children:Ge.name}),cn&&s.jsx("span",{className:"text-xs text-muted-foreground",children:"Available to all members"})]})]}),s.jsx("div",{className:"flex items-center gap-2",children:Vr?s.jsx(Ps,{className:"h-4 w-4 animate-spin text-muted-foreground"}):cn?s.jsx(ir,{variant:"secondary",className:"text-xs",children:"Always On"}):s.jsx(ri,{checked:ur,onCheckedChange:()=>xo(Se.id,Ge,ur)})})]},Ge.id)})})]}),Se.is_trial&&s.jsxs("div",{className:"space-y-3 pt-4 border-t",children:[s.jsxs("h3",{className:"text-sm font-semibold flex items-center gap-2",children:[s.jsx(No,{className:"h-4 w-4"}),"Trial Status"]}),s.jsxs("div",{className:"p-4 rounded-lg border bg-amber-50 dark:bg-amber-950/20 border-amber-200 dark:border-amber-800",children:[s.jsxs("div",{className:"flex items-center justify-between mb-3",children:[s.jsx("div",{children:Se.trial_expires_at&&s.jsx(gQ,{expiresAt:Se.trial_expires_at})}),Se.trial_expires_at&&s.jsxs("span",{className:"text-sm text-muted-foreground",children:["Expires: ",new Date(Se.trial_expires_at).toLocaleDateString()]})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsxs(de,{size:"sm",variant:"outline",onClick:()=>St(Se.id,7),disabled:xe,children:[s.jsx(OF,{className:"h-4 w-4 mr-1"}),"+7 Days"]}),s.jsxs(de,{size:"sm",variant:"outline",onClick:()=>St(Se.id,14),disabled:xe,children:[s.jsx(OF,{className:"h-4 w-4 mr-1"}),"+14 Days"]}),s.jsxs(de,{size:"sm",variant:"outline",onClick:()=>St(Se.id,30),disabled:xe,children:[s.jsx(OF,{className:"h-4 w-4 mr-1"}),"+30 Days"]}),s.jsxs(de,{size:"sm",variant:"default",onClick:()=>sr(Se.id),disabled:ve,className:"bg-green-600 hover:bg-green-700",children:[s.jsx(Coe,{className:"h-4 w-4 mr-1"}),"Convert to Full Account"]})]}),Se.trial_started_at&&s.jsxs("div",{className:"mt-3 text-xs text-muted-foreground",children:["Trial started: ",new Date(Se.trial_started_at).toLocaleDateString(),Se.trial_claimed_at&&s.jsxs("span",{children:[" • Claimed: ",new Date(Se.trial_claimed_at).toLocaleDateString()]})]})]})]}),s.jsxs("div",{className:"space-y-2 pt-4 border-t",children:[s.jsx("h3",{className:"text-sm font-semibold",children:"Account Information"}),s.jsxs("div",{className:"text-sm space-y-1 text-muted-foreground",children:[Se.email_confirmed_at&&s.jsxs("div",{children:["Claimed: ",new Date(Se.email_confirmed_at).toLocaleString()]}),Se.last_sign_in_at&&s.jsxs("div",{children:["Last login: ",new Date(Se.last_sign_in_at).toLocaleString()]}),s.jsxs("div",{children:["Created: ",new Date(Se.created_at).toLocaleString()]})]})]})]}),s.jsxs(zi,{children:[s.jsx(de,{variant:"outline",onClick:Ir,children:"Cancel"}),s.jsx(de,{onClick:en,children:"Save Changes"})]})]})}),s.jsxs(xs,{value:"access",children:[c.length===0?s.jsx(at,{children:s.jsxs(ct,{className:"py-12 text-center",children:[s.jsx("p",{className:"text-muted-foreground mb-4",children:"No apps configured yet"}),s.jsx(de,{onClick:()=>t("/admin/apps"),children:"Configure Apps"})]})}):s.jsxs(at,{children:[s.jsxs(xr,{children:[s.jsx(wr,{children:"Member Access Matrix"}),s.jsx(us,{children:"Toggle switches to grant or revoke app access for each member"})]}),s.jsx(ct,{children:s.jsx("div",{className:"overflow-x-auto",children:s.jsxs("table",{className:"w-full",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"border-b",children:[s.jsx("th",{className:"text-left p-4 font-semibold sticky left-0 bg-card z-10",children:"Member"}),c.map(Ge=>s.jsx("th",{className:"text-center p-4 font-semibold min-w-[120px]",children:s.jsxs("div",{className:"flex flex-col items-center gap-1",children:[s.jsx("span",{className:"text-2xl",children:Ge.icon}),s.jsx("span",{className:"text-sm",children:Ge.name})]})},Ge.id))]})}),s.jsxs("tbody",{children:[dt.map(Ge=>s.jsxs("tr",{className:"border-b hover:bg-muted/50",children:[s.jsx("td",{className:"p-4 sticky left-0 bg-card z-10",children:s.jsxs("div",{children:[s.jsx("div",{className:"font-medium",children:Ge.name}),s.jsx("div",{className:"text-sm text-muted-foreground",children:Ge.email})]})}),c.map(ur=>{const jr=Wt(Ge.tags,ur.required_tags),Vr=`${Ge.id}-${ur.id}`,cn=pt===Vr;return s.jsx("td",{className:"p-4 text-center",children:s.jsx("div",{className:"flex items-center justify-center",children:cn?s.jsx(Ps,{className:"h-5 w-5 animate-spin text-muted-foreground"}):s.jsx(ri,{checked:jr,onCheckedChange:()=>xo(Ge.id,ur,jr),disabled:ur.required_tags.length===0})})},ur.id)})]},Ge.id)),dt.length===0&&s.jsx("tr",{children:s.jsx("td",{colSpan:c.length+1,className:"p-8 text-center text-muted-foreground",children:"No members found"})})]})]})})})]}),s.jsx("div",{className:"mt-6",children:s.jsx(de,{variant:"outline",onClick:()=>t("/admin/apps"),children:"Manage Apps"})})]}),s.jsxs(xs,{value:"brokerages",className:"space-y-4",children:[s.jsxs("div",{className:"flex items-center justify-between gap-4",children:[s.jsxs("div",{className:"relative flex-1 max-w-sm",children:[s.jsx(ba,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),s.jsx(Et,{placeholder:"Search brokerages...",value:Jo,onChange:Ge=>wh(Ge.target.value),className:"pl-10"})]}),s.jsxs(mn,{open:Qt,onOpenChange:gt,children:[s.jsx(Do,{asChild:!0,children:s.jsxs(de,{size:"sm",children:[s.jsx(yc,{className:"mr-2 h-4 w-4"}),"Add Brokerage"]})}),s.jsxs(pn,{children:[s.jsxs(xn,{children:[s.jsx(gn,{children:"Create New Brokerage"}),s.jsx(fi,{children:"Add a new brokerage to the system."})]}),s.jsx("div",{className:"space-y-4 py-4",children:s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"brokerage-name",children:"Brokerage Name"}),s.jsx(Et,{id:"brokerage-name",placeholder:"Enter brokerage name",value:Me,onChange:Ge=>Oe(Ge.target.value),maxLength:100})]})}),s.jsxs(zi,{children:[s.jsx(de,{variant:"outline",onClick:()=>gt(!1),children:"Cancel"}),s.jsx(de,{onClick:zc,disabled:Ie,children:Ie?"Creating...":"Create Brokerage"})]})]})]})]}),s.jsx("div",{className:"border rounded-lg bg-card overflow-hidden",children:s.jsxs(ni,{children:[s.jsx(si,{children:s.jsxs(Dr,{className:"bg-muted/30 hover:bg-muted/30",children:[s.jsx(Nt,{className:"font-semibold",children:"Brokerage Name"}),s.jsx(Nt,{className:"font-semibold",children:"Manager(s)"}),s.jsx(Nt,{className:"font-semibold",children:"Agents"}),s.jsx(Nt,{className:"w-[150px]"})]})}),s.jsx(ii,{children:(()=>{const Ge=m.filter(ur=>ur.name.toLowerCase().includes(Jo.toLowerCase()));return Ge.length===0?s.jsx(Dr,{children:s.jsx(xt,{colSpan:4,className:"text-center py-12 text-muted-foreground",children:Jo?"No brokerages match your search":"No brokerages found"})}):Ge.map(ur=>{const jr=i.filter(Ns=>Ns.brokerage_id===ur.id),Vr=jr.filter(Ns=>Ns.roles.includes("brokerage_manager")),cn=jr.length;return s.jsxs(Dr,{className:"hover:bg-muted/30",children:[s.jsx(xt,{children:s.jsx("button",{onClick:()=>oo(ur),className:"text-primary hover:underline font-medium",children:ur.name})}),s.jsx(xt,{children:Vr.length>0?s.jsx("div",{className:"flex flex-wrap gap-1",children:Vr.map(Ns=>s.jsx(ir,{variant:"secondary",className:"text-xs",children:Ns.name},Ns.id))}):s.jsx("span",{className:"text-muted-foreground text-sm",children:"No manager"})}),s.jsxs(xt,{children:[cn," member",cn!==1?"s":""]}),s.jsx(xt,{children:s.jsxs("div",{className:"flex gap-1 justify-end",children:[s.jsxs(de,{size:"sm",variant:"outline",className:"h-8",onClick:()=>vt(ur),children:[s.jsx(_i,{className:"h-4 w-4 mr-1"}),"Manage"]}),s.jsx(de,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>oo(ur),title:"Edit brokerage",children:s.jsx(io,{className:"h-4 w-4"})}),s.jsx(de,{size:"icon",variant:"ghost",className:"h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:()=>jh(ur),title:"Delete brokerage",children:s.jsx(oi,{className:"h-4 w-4"})})]})})]},ur.id)})})()})]})}),s.jsx(mn,{open:Pe,onOpenChange:ut,children:s.jsxs(pn,{className:"max-w-lg",children:[s.jsxs(xn,{children:[s.jsx(gn,{children:"Edit Brokerage"}),s.jsx(fi,{children:"Update brokerage details and manage managers"})]}),jt&&s.jsxs("div",{className:"space-y-6 py-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"edit-brokerage-name",children:"Brokerage Name"}),s.jsx(Et,{id:"edit-brokerage-name",value:Ht,onChange:Ge=>Lt(Ge.target.value),maxLength:100})]}),s.jsxs("div",{className:"space-y-3",children:[s.jsx(mt,{children:"Managers"}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Click × to remove manager role (keeps them as a member)"}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[i.filter(Ge=>Ge.brokerage_id===jt.id&&Ge.roles.includes("brokerage_manager")).map(Ge=>s.jsxs(ir,{variant:"default",className:"gap-1",children:[s.jsx(n2,{className:"h-3 w-3"}),Ge.name,s.jsx("button",{onClick:()=>yo(Ge.id,"brokerage_manager","remove"),className:"ml-1 rounded-full hover:bg-destructive/20",title:"Remove manager role",children:s.jsx(Ni,{className:"h-3 w-3"})})]},Ge.id)),i.filter(Ge=>Ge.brokerage_id===jt.id&&Ge.roles.includes("brokerage_manager")).length===0&&s.jsx("span",{className:"text-sm text-muted-foreground",children:"No managers assigned"})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{className:"text-sm text-muted-foreground",children:"Assign manager from existing members:"}),s.jsxs(Kn,{onValueChange:Ge=>Px(Ge,jt.id),children:[s.jsx(qn,{children:s.jsx(Zn,{placeholder:"Select a member..."})}),s.jsx(Hn,{children:i.filter(Ge=>!Ge.roles.includes("brokerage_manager")||Ge.brokerage_id!==jt.id).map(Ge=>s.jsxs(_r,{value:Ge.id,children:[Ge.name," (",Ge.email,")"]},Ge.id))})]})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Members in this Brokerage"}),s.jsx("div",{className:"max-h-32 overflow-y-auto border rounded p-2",children:i.filter(Ge=>Ge.brokerage_id===jt.id).length===0?s.jsx("span",{className:"text-sm text-muted-foreground",children:"No members"}):i.filter(Ge=>Ge.brokerage_id===jt.id).map(Ge=>s.jsxs("div",{className:"text-sm py-1 flex items-center justify-between",children:[s.jsx("span",{children:Ge.name}),Ge.roles.includes("brokerage_manager")&&s.jsx(ir,{variant:"outline",className:"text-xs",children:"Manager"})]},Ge.id))})]})]}),s.jsxs(zi,{children:[s.jsx(de,{variant:"outline",onClick:Xn,children:"Cancel"}),s.jsx(de,{onClick:Bo,disabled:Kt,children:Kt?"Saving...":"Save Changes"})]})]})}),s.jsx(mn,{open:rt,onOpenChange:We,children:s.jsxs(pn,{children:[s.jsxs(xn,{children:[s.jsx(gn,{className:"text-destructive",children:"Delete Brokerage"}),s.jsxs(fi,{children:['Are you sure you want to delete "',_t==null?void 0:_t.name,'"?']})]}),s.jsx("div",{className:"py-4",children:s.jsxs("div",{className:"bg-destructive/10 border border-destructive/20 rounded-lg p-4 space-y-2",children:[s.jsx("p",{className:"text-sm font-medium text-destructive",children:"Warning: This action cannot be undone!"}),s.jsx("p",{className:"text-sm text-muted-foreground",children:"This will permanently delete:"}),s.jsxs("ul",{className:"text-sm text-muted-foreground list-disc list-inside",children:[s.jsxs("li",{children:['The brokerage "',_t==null?void 0:_t.name,'"']}),s.jsxs("li",{children:["All ",i.filter(Ge=>Ge.brokerage_id===(_t==null?void 0:_t.id)).length," member(s) assigned to this brokerage"]}),s.jsx("li",{children:"All their data, roles, and access"})]})]})}),s.jsxs(zi,{children:[s.jsx(de,{variant:"outline",onClick:()=>We(!1),children:"Cancel"}),s.jsx(de,{variant:"destructive",onClick:Fp,disabled:rr,children:rr?"Deleting...":"Yes, Delete Brokerage"})]})]})}),s.jsx(mn,{open:kr,onOpenChange:Hr,children:s.jsxs(pn,{className:"max-w-4xl max-h-[85vh] overflow-hidden flex flex-col",children:[s.jsxs(xn,{children:[s.jsxs(gn,{className:"flex items-center gap-2",children:[s.jsx(yc,{className:"h-5 w-5"}),"Manage ",Fn==null?void 0:Fn.name]}),s.jsx(fi,{children:"Add, remove, or manage users in this brokerage"})]}),Fn&&s.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col space-y-4",children:[s.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[s.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[s.jsx(ba,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),s.jsx(Et,{placeholder:"Search members...",value:ia,onChange:Ge=>pa(Ge.target.value),className:"pl-10 h-9"})]}),s.jsxs(mn,{open:zo,onOpenChange:Xo,children:[s.jsx(Do,{asChild:!0,children:s.jsxs(de,{size:"sm",children:[s.jsx(yM,{className:"h-4 w-4 mr-1"}),"Add New Agent"]})}),s.jsxs(pn,{children:[s.jsxs(xn,{children:[s.jsx(gn,{children:"Add New Agent"}),s.jsxs(fi,{children:["Create a new agent for ",Fn.name]})]}),s.jsxs("div",{className:"space-y-4 py-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"agent-name",children:"Name"}),s.jsx(Et,{id:"agent-name",placeholder:"John Doe",value:Xs.name,onChange:Ge=>Ma({...Xs,name:Ge.target.value})})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"agent-email",children:"Email"}),s.jsx(Et,{id:"agent-email",type:"email",placeholder:"john@example.com",value:Xs.email,onChange:Ge=>Ma({...Xs,email:Ge.target.value})})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"agent-password",children:"Password"}),s.jsx(Et,{id:"agent-password",type:"password",placeholder:"Min 6 characters",value:Xs.password,onChange:Ge=>Ma({...Xs,password:Ge.target.value})})]})]}),s.jsxs(zi,{children:[s.jsx(de,{variant:"outline",onClick:()=>Xo(!1),children:"Cancel"}),s.jsx(de,{onClick:tt,disabled:Qo,children:Qo?"Creating...":"Create Agent"})]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(mt,{className:"text-sm text-muted-foreground whitespace-nowrap",children:"Add existing user:"}),s.jsxs(Kn,{onValueChange:Ge=>Re(Ge,Fn.id),children:[s.jsx(qn,{className:"w-[300px]",children:s.jsx(Zn,{placeholder:"Select a user to add..."})}),s.jsx(Hn,{children:Ct(Fn.id).length===0?s.jsx(_r,{value:"none",disabled:!0,children:"No available users"}):Ct(Fn.id).map(Ge=>s.jsxs(_r,{value:Ge.id,children:[Ge.name," (",Ge.email,")"]},Ge.id))})]})]}),s.jsx("div",{className:"flex-1 overflow-auto border rounded-lg",children:s.jsxs(ni,{children:[s.jsx(si,{children:s.jsxs(Dr,{className:"bg-muted/30 hover:bg-muted/30",children:[s.jsx(Nt,{className:"font-semibold",children:"Name"}),s.jsx(Nt,{className:"font-semibold",children:"Email"}),s.jsx(Nt,{className:"font-semibold",children:"Status"}),s.jsx(Nt,{className:"font-semibold",children:"Role"}),s.jsx(Nt,{className:"w-[120px]"})]})}),s.jsx(ii,{children:lt(Fn.id).length===0?s.jsx(Dr,{children:s.jsx(xt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:ia?"No matching members found":"No members in this brokerage"})}):lt(Fn.id).map(Ge=>s.jsxs(Dr,{className:"hover:bg-muted/30",children:[s.jsx(xt,{className:"font-medium",children:Ge.name}),s.jsx(xt,{className:"text-muted-foreground",children:Ge.email}),s.jsx(xt,{children:Ge.claimed?s.jsx(ir,{variant:"default",className:"bg-green-500/10 text-green-600 hover:bg-green-500/20",children:"Active"}):s.jsx(ir,{variant:"secondary",children:"Pending"})}),s.jsx(xt,{children:Ge.roles.includes("brokerage_manager")?s.jsxs(ir,{variant:"outline",className:"gap-1",children:[s.jsx(n2,{className:"h-3 w-3"}),"Manager"]}):s.jsx("span",{className:"text-muted-foreground text-sm",children:"Agent"})}),s.jsx(xt,{children:s.jsxs("div",{className:"flex gap-1 justify-end",children:[!Ge.claimed&&s.jsx(de,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Ss(Ge.id),title:"Resend welcome email",children:s.jsx(Fo,{className:"h-4 w-4"})}),s.jsx(de,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>be(Ge.id),title:"Remove from brokerage",children:s.jsx(Ni,{className:"h-4 w-4"})}),s.jsx(de,{size:"icon",variant:"ghost",className:"h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:()=>bi(Ge.id,Ge.name),title:"Delete user",children:s.jsx(oi,{className:"h-4 w-4"})})]})})]},Ge.id))})]})}),s.jsxs("div",{className:"text-sm text-muted-foreground",children:[Xe(Fn.id).length," total member",Xe(Fn.id).length!==1?"s":""," •",Xe(Fn.id).filter(Ge=>Ge.roles.includes("brokerage_manager")).length," manager",Xe(Fn.id).filter(Ge=>Ge.roles.includes("brokerage_manager")).length!==1?"s":""]})]}),s.jsx(zi,{children:s.jsx(de,{variant:"outline",onClick:ue,children:"Close"})})]})})]})]})]}),s.jsx(gme,{open:yl,onOpenChange:tc,brokerages:m,onSuccess:xa})]})},T$e=()=>{const[t,e]=D.useState([]),[r,n]=D.useState(!0),[i,o]=D.useState(!1),[c,a]=D.useState(""),[m,g]=D.useState(""),[_,j]=D.useState("");D.useEffect(()=>{N()},[]);const N=async()=>{const{data:z,error:W}=await ae.from("invite_codes").select("*").order("created_at",{ascending:!1});W?(Dt.error("Failed to load invite codes"),console.error(W)):e(z||[]),n(!1)},C=async z=>{if(z.preventDefault(),!c.trim()){Dt.error("Please enter a code");return}o(!0);const{error:W}=await ae.from("invite_codes").insert({code:c.trim().toUpperCase(),description:m.trim()||null,max_uses:_?parseInt(_):null});W?W.code==="23505"?Dt.error("This code already exists"):(Dt.error("Failed to create invite code"),console.error(W)):(Dt.success("Invite code created"),a(""),g(""),j(""),N()),o(!1)},P=async(z,W)=>{const{error:V}=await ae.from("invite_codes").update({is_active:!W}).eq("id",z);V?Dt.error("Failed to update code"):e(t.map(K=>K.id===z?{...K,is_active:!W}:K))},A=async z=>{const{error:W}=await ae.from("invite_codes").delete().eq("id",z);W?Dt.error("Failed to delete code"):(Dt.success("Code deleted"),e(t.filter(V=>V.id!==z)))},I="https://dashboard.relevelup.com",O=z=>{const W=`${I}/join?code=${z}`;navigator.clipboard.writeText(W),Dt.success("Link copied to clipboard")},R=`${I}/join`;return s.jsx(Jr,{title:"Invite Codes",children:s.jsxs("div",{className:"space-y-6",children:[s.jsxs(at,{children:[s.jsxs(xr,{children:[s.jsx(wr,{children:"Create New Code"}),s.jsxs(us,{children:["Share link: ",s.jsx("code",{className:"bg-muted px-2 py-1 rounded text-sm",children:R})]})]}),s.jsx(ct,{children:s.jsxs("form",{onSubmit:C,className:"flex flex-wrap gap-4 items-end",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"code",children:"Code"}),s.jsx(Et,{id:"code",placeholder:"WELCOME2024",value:c,onChange:z=>a(z.target.value),className:"w-40"})]}),s.jsxs("div",{className:"space-y-2 flex-1 min-w-[200px]",children:[s.jsx(mt,{htmlFor:"description",children:"Description (optional)"}),s.jsx(Et,{id:"description",placeholder:"For marketing campaign",value:m,onChange:z=>g(z.target.value)})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"maxUses",children:"Max Uses"}),s.jsx(Et,{id:"maxUses",type:"number",placeholder:"Unlimited",value:_,onChange:z=>j(z.target.value),className:"w-28"})]}),s.jsxs(de,{type:"submit",disabled:i,children:[i?s.jsx(Ps,{className:"h-4 w-4 animate-spin"}):s.jsx(Qn,{className:"h-4 w-4 mr-2"}),"Create"]})]})})]}),s.jsxs(at,{children:[s.jsx(xr,{children:s.jsx(wr,{children:"Active Codes"})}),s.jsx(ct,{children:r?s.jsx("div",{className:"flex justify-center py-8",children:s.jsx(Ps,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):t.length===0?s.jsx("p",{className:"text-center py-8 text-muted-foreground",children:"No invite codes yet"}):s.jsxs(ni,{children:[s.jsx(si,{children:s.jsxs(Dr,{children:[s.jsx(Nt,{children:"Code"}),s.jsx(Nt,{children:"Description"}),s.jsx(Nt,{children:"Uses"}),s.jsx(Nt,{children:"Created"}),s.jsx(Nt,{children:"Active"}),s.jsx(Nt,{className:"w-24",children:"Actions"})]})}),s.jsx(ii,{children:t.map(z=>s.jsxs(Dr,{children:[s.jsx(xt,{className:"font-mono font-medium",children:z.code}),s.jsx(xt,{className:"text-muted-foreground",children:z.description||"—"}),s.jsxs(xt,{children:[z.uses_count,z.max_uses&&` / ${z.max_uses}`]}),s.jsx(xt,{className:"text-muted-foreground",children:Vn(new Date(z.created_at),"MMM d, yyyy")}),s.jsx(xt,{children:s.jsx(ri,{checked:z.is_active,onCheckedChange:()=>P(z.id,z.is_active)})}),s.jsx(xt,{children:s.jsxs("div",{className:"flex gap-1",children:[s.jsx(de,{variant:"ghost",size:"icon",onClick:()=>O(z.code),title:"Copy invite link",children:s.jsx(ix,{className:"h-4 w-4"})}),s.jsx(de,{variant:"ghost",size:"icon",onClick:()=>A(z.id),className:"text-destructive hover:text-destructive",title:"Delete code",children:s.jsx(oi,{className:"h-4 w-4"})})]})})]},z.id))})]})})]})]})})};function dc(t){this.content=t}dc.prototype={constructor:dc,find:function(t){for(var e=0;e>1}};dc.from=function(t){if(t instanceof dc)return t;var e=[];if(t)for(var r in t)e.push(r,t[r]);return new dc(e)};function yme(t,e,r){for(let n=0;;n++){if(n==t.childCount||n==e.childCount)return t.childCount==e.childCount?null:r;let i=t.child(n),o=e.child(n);if(i==o){r+=i.nodeSize;continue}if(!i.sameMarkup(o))return r;if(i.isText&&i.text!=o.text){for(let c=0;i.text[c]==o.text[c];c++)r++;return r}if(i.content.size||o.content.size){let c=yme(i.content,o.content,r+1);if(c!=null)return c}r+=i.nodeSize}}function xme(t,e,r,n){for(let i=t.childCount,o=e.childCount;;){if(i==0||o==0)return i==o?null:{a:r,b:n};let c=t.child(--i),a=e.child(--o),m=c.nodeSize;if(c==a){r-=m,n-=m;continue}if(!c.sameMarkup(a))return{a:r,b:n};if(c.isText&&c.text!=a.text){let g=0,_=Math.min(c.text.length,a.text.length);for(;g<_&&c.text[c.text.length-g-1]==a.text[a.text.length-g-1];)g++,r--,n--;return{a:r,b:n}}if(c.content.size||a.content.size){let g=xme(c.content,a.content,r-1,n-1);if(g)return g}r-=m,n-=m}}class Qr{constructor(e,r){if(this.content=e,this.size=r||0,r==null)for(let n=0;ne&&n(m,i+a,o||null,c)!==!1&&m.content.size){let _=a+1;m.nodesBetween(Math.max(0,e-_),Math.min(m.content.size,r-_),n,i+_)}a=g}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,r,n,i){let o="",c=!0;return this.nodesBetween(e,r,(a,m)=>{let g=a.isText?a.text.slice(Math.max(e,m)-m,r-m):a.isLeaf?i?typeof i=="function"?i(a):i:a.type.spec.leafText?a.type.spec.leafText(a):"":"";a.isBlock&&(a.isLeaf&&g||a.isTextblock)&&n&&(c?c=!1:o+=n),o+=g},0),o}append(e){if(!e.size)return this;if(!this.size)return e;let r=this.lastChild,n=e.firstChild,i=this.content.slice(),o=0;for(r.isText&&r.sameMarkup(n)&&(i[i.length-1]=r.withText(r.text+n.text),o=1);oe)for(let o=0,c=0;ce&&((cr)&&(a.isText?a=a.cut(Math.max(0,e-c),Math.min(a.text.length,r-c)):a=a.cut(Math.max(0,e-c-1),Math.min(a.content.size,r-c-1))),n.push(a),i+=a.nodeSize),c=m}return new Qr(n,i)}cutByIndex(e,r){return e==r?Qr.empty:e==0&&r==this.content.length?this:new Qr(this.content.slice(e,r))}replaceChild(e,r){let n=this.content[e];if(n==r)return this;let i=this.content.slice(),o=this.size+r.nodeSize-n.nodeSize;return i[e]=r,new Qr(i,o)}addToStart(e){return new Qr([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new Qr(this.content.concat(e),this.size+e.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let r=0;rthis.size||e<0)throw new RangeError(`Position ${e} outside of fragment (${this})`);for(let r=0,n=0;;r++){let i=this.child(r),o=n+i.nodeSize;if(o>=e)return o==e?MP(r+1,o):MP(r,n);n=o}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(e=>e.toJSON()):null}static fromJSON(e,r){if(!r)return Qr.empty;if(!Array.isArray(r))throw new RangeError("Invalid input for Fragment.fromJSON");return new Qr(r.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return Qr.empty;let r,n=0;for(let i=0;ithis.type.rank&&(r||(r=e.slice(0,i)),r.push(this),n=!0),r&&r.push(o)}}return r||(r=e.slice()),n||r.push(this),r}removeFromSet(e){for(let r=0;rn.type.rank-i.type.rank),r}};Ra.none=[];class YM extends Error{}class Ln{constructor(e,r,n){this.content=e,this.openStart=r,this.openEnd=n}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(e,r){let n=_me(this.content,e+this.openStart,r);return n&&new Ln(n,this.openStart,this.openEnd)}removeBetween(e,r){return new Ln(vme(this.content,e+this.openStart,r+this.openStart),this.openStart,this.openEnd)}eq(e){return this.content.eq(e.content)&&this.openStart==e.openStart&&this.openEnd==e.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let e={content:this.content.toJSON()};return this.openStart>0&&(e.openStart=this.openStart),this.openEnd>0&&(e.openEnd=this.openEnd),e}static fromJSON(e,r){if(!r)return Ln.empty;let n=r.openStart||0,i=r.openEnd||0;if(typeof n!="number"||typeof i!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new Ln(Qr.fromJSON(e,r.content),n,i)}static maxOpen(e,r=!0){let n=0,i=0;for(let o=e.firstChild;o&&!o.isLeaf&&(r||!o.type.spec.isolating);o=o.firstChild)n++;for(let o=e.lastChild;o&&!o.isLeaf&&(r||!o.type.spec.isolating);o=o.lastChild)i++;return new Ln(e,n,i)}}Ln.empty=new Ln(Qr.empty,0,0);function vme(t,e,r){let{index:n,offset:i}=t.findIndex(e),o=t.maybeChild(n),{index:c,offset:a}=t.findIndex(r);if(i==e||o.isText){if(a!=r&&!t.child(c).isText)throw new RangeError("Removing non-flat range");return t.cut(0,e).append(t.cut(r))}if(n!=c)throw new RangeError("Removing non-flat range");return t.replaceChild(n,o.copy(vme(o.content,e-i-1,r-i-1)))}function _me(t,e,r,n){let{index:i,offset:o}=t.findIndex(e),c=t.maybeChild(i);if(o==e||c.isText)return n&&!n.canReplace(i,i,r)?null:t.cut(0,e).append(r).append(t.cut(e));let a=_me(c.content,e-o-1,r,c);return a&&t.replaceChild(i,c.copy(a))}function E$e(t,e,r){if(r.openStart>t.depth)throw new YM("Inserted content deeper than insertion position");if(t.depth-r.openStart!=e.depth-r.openEnd)throw new YM("Inconsistent open depths");return bme(t,e,r,0)}function bme(t,e,r,n){let i=t.index(n),o=t.node(n);if(i==e.index(n)&&n=0&&t.isText&&t.sameMarkup(e[r])?e[r]=t.withText(e[r].text+t.text):e.push(t)}function d2(t,e,r,n){let i=(e||t).node(r),o=0,c=e?e.index(r):i.childCount;t&&(o=t.index(r),t.depth>r?o++:t.textOffset&&(y_(t.nodeAfter,n),o++));for(let a=o;ai&&B$(t,e,i+1),c=n.depth>i&&B$(r,n,i+1),a=[];return d2(null,t,i,a),o&&c&&e.index(i)==r.index(i)?(wme(o,c),y_(x_(o,jme(t,e,r,n,i+1)),a)):(o&&y_(x_(o,XM(t,e,i+1)),a),d2(e,r,i,a),c&&y_(x_(c,XM(r,n,i+1)),a)),d2(n,null,i,a),new Qr(a)}function XM(t,e,r){let n=[];if(d2(null,t,r,n),t.depth>r){let i=B$(t,e,r+1);y_(x_(i,XM(t,e,r+1)),n)}return d2(e,null,r,n),new Qr(n)}function A$e(t,e){let r=e.depth-t.openStart,i=e.node(r).copy(t.content);for(let o=r-1;o>=0;o--)i=e.node(o).copy(Qr.from(i));return{start:i.resolveNoCache(t.openStart+r),end:i.resolveNoCache(i.content.size-t.openEnd-r)}}class uk{constructor(e,r,n){this.pos=e,this.path=r,this.parentOffset=n,this.depth=r.length/3-1}resolveDepth(e){return e==null?this.depth:e<0?this.depth+e:e}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(e){return this.path[this.resolveDepth(e)*3]}index(e){return this.path[this.resolveDepth(e)*3+1]}indexAfter(e){return e=this.resolveDepth(e),this.index(e)+(e==this.depth&&!this.textOffset?0:1)}start(e){return e=this.resolveDepth(e),e==0?0:this.path[e*3-1]+1}end(e){return e=this.resolveDepth(e),this.start(e)+this.node(e).content.size}before(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position before the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]}after(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position after the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]+this.path[e*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let e=this.parent,r=this.index(this.depth);if(r==e.childCount)return null;let n=this.pos-this.path[this.path.length-1],i=e.child(r);return n?e.child(r).cut(n):i}get nodeBefore(){let e=this.index(this.depth),r=this.pos-this.path[this.path.length-1];return r?this.parent.child(e).cut(0,r):e==0?null:this.parent.child(e-1)}posAtIndex(e,r){r=this.resolveDepth(r);let n=this.path[r*3],i=r==0?0:this.path[r*3-1]+1;for(let o=0;o0;r--)if(this.start(r)<=e&&this.end(r)>=e)return r;return 0}blockRange(e=this,r){if(e.pos=0;n--)if(e.pos<=this.end(n)&&(!r||r(this.node(n))))return new QM(this,e,n);return null}sameParent(e){return this.pos-this.parentOffset==e.pos-e.parentOffset}max(e){return e.pos>this.pos?e:this}min(e){return e.pos=0&&r<=e.content.size))throw new RangeError("Position "+r+" out of range");let n=[],i=0,o=r;for(let c=e;;){let{index:a,offset:m}=c.content.findIndex(o),g=o-m;if(n.push(c,a,i+m),!g||(c=c.child(a),c.isText))break;o=g-1,i+=m+1}return new uk(r,n,o)}static resolveCached(e,r){let n=yQ.get(e);if(n)for(let o=0;oe&&this.nodesBetween(e,r,o=>(n.isInSet(o.marks)&&(i=!0),!i)),i}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let e=this.type.name;return this.content.size&&(e+="("+this.content.toStringInner()+")"),Sme(this.marks,e)}contentMatchAt(e){let r=this.type.contentMatch.matchFragment(this.content,0,e);if(!r)throw new Error("Called contentMatchAt on a node with invalid content");return r}canReplace(e,r,n=Qr.empty,i=0,o=n.childCount){let c=this.contentMatchAt(e).matchFragment(n,i,o),a=c&&c.matchFragment(this.content,r);if(!a||!a.validEnd)return!1;for(let m=i;mr.type.name)}`);this.content.forEach(r=>r.check())}toJSON(){let e={type:this.type.name};for(let r in this.attrs){e.attrs=this.attrs;break}return this.content.size&&(e.content=this.content.toJSON()),this.marks.length&&(e.marks=this.marks.map(r=>r.toJSON())),e}static fromJSON(e,r){if(!r)throw new RangeError("Invalid input for Node.fromJSON");let n;if(r.marks){if(!Array.isArray(r.marks))throw new RangeError("Invalid mark data for Node.fromJSON");n=r.marks.map(e.markFromJSON)}if(r.type=="text"){if(typeof r.text!="string")throw new RangeError("Invalid text node in JSON");return e.text(r.text,n)}let i=Qr.fromJSON(e,r.content),o=e.nodeType(r.type).create(r.attrs,i,n);return o.type.checkAttrs(o.attrs),o}};Zy.prototype.text=void 0;class JM extends Zy{constructor(e,r,n,i){if(super(e,r,null,i),!n)throw new RangeError("Empty text nodes are not allowed");this.text=n}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):Sme(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(e,r){return this.text.slice(e,r)}get nodeSize(){return this.text.length}mark(e){return e==this.marks?this:new JM(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new JM(this.type,this.attrs,e,this.marks)}cut(e=0,r=this.text.length){return e==0&&r==this.text.length?this:this.withText(this.text.slice(e,r))}eq(e){return this.sameMarkup(e)&&this.text==e.text}toJSON(){let e=super.toJSON();return e.text=this.text,e}}function Sme(t,e){for(let r=t.length-1;r>=0;r--)e=t[r].type.name+"("+e+")";return e}class $_{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,r){let n=new O$e(e,r);if(n.next==null)return $_.empty;let i=Nme(n);n.next&&n.err("Unexpected trailing text");let o=$$e(B$e(i));return U$e(o,n),o}matchType(e){for(let r=0;rg.createAndFill()));for(let g=0;g=this.next.length)throw new RangeError(`There's no ${e}th edge in this content match`);return this.next[e]}toString(){let e=[];function r(n){e.push(n);for(let i=0;i{let o=i+(n.validEnd?"*":" ")+" ";for(let c=0;c"+e.indexOf(n.next[c].next);return o}).join(` `)}}$_.empty=new $_(!0);class O$e{constructor(e,r){this.string=e,this.nodeTypes=r,this.inline=null,this.pos=0,this.tokens=e.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]==""&&this.tokens.pop(),this.tokens[0]==""&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(e){return this.next==e&&(this.pos++||!0)}err(e){throw new SyntaxError(e+" (in content expression '"+this.string+"')")}}function Nme(t){let e=[];do e.push(R$e(t));while(t.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function R$e(t){let e=[];do e.push(D$e(t));while(t.next&&t.next!=")"&&t.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function D$e(t){let e=z$e(t);for(;;)if(t.eat("+"))e={type:"plus",expr:e};else if(t.eat("*"))e={type:"star",expr:e};else if(t.eat("?"))e={type:"opt",expr:e};else if(t.eat("{"))e=L$e(t,e);else break;return e}function xQ(t){/\D/.test(t.next)&&t.err("Expected number, got '"+t.next+"'");let e=Number(t.next);return t.pos++,e}function L$e(t,e){let r=xQ(t),n=r;return t.eat(",")&&(t.next!="}"?n=xQ(t):n=-1),t.eat("}")||t.err("Unclosed braced range"),{type:"range",min:r,max:n,expr:e}}function F$e(t,e){let r=t.nodeTypes,n=r[e];if(n)return[n];let i=[];for(let o in r){let c=r[o];c.isInGroup(e)&&i.push(c)}return i.length==0&&t.err("No node type or group '"+e+"' found"),i}function z$e(t){if(t.eat("(")){let e=Nme(t);return t.eat(")")||t.err("Missing closing paren"),e}else if(/\W/.test(t.next))t.err("Unexpected token '"+t.next+"'");else{let e=F$e(t,t.next).map(r=>(t.inline==null?t.inline=r.isInline:t.inline!=r.isInline&&t.err("Mixing inline and block content"),{type:"name",value:r}));return t.pos++,e.length==1?e[0]:{type:"choice",exprs:e}}}function B$e(t){let e=[[]];return i(o(t,0),r()),e;function r(){return e.push([])-1}function n(c,a,m){let g={term:m,to:a};return e[c].push(g),g}function i(c,a){c.forEach(m=>m.to=a)}function o(c,a){if(c.type=="choice")return c.exprs.reduce((m,g)=>m.concat(o(g,a)),[]);if(c.type=="seq")for(let m=0;;m++){let g=o(c.exprs[m],a);if(m==c.exprs.length-1)return g;i(g,a=r())}else if(c.type=="star"){let m=r();return n(a,m),i(o(c.expr,m),m),[n(m)]}else if(c.type=="plus"){let m=r();return i(o(c.expr,a),m),i(o(c.expr,m),m),[n(m)]}else{if(c.type=="opt")return[n(a)].concat(o(c.expr,a));if(c.type=="range"){let m=a;for(let g=0;g{t[c].forEach(({term:a,to:m})=>{if(!a)return;let g;for(let _=0;_{g||i.push([a,g=[]]),g.indexOf(_)==-1&&g.push(_)})})});let o=e[n.join(",")]=new $_(n.indexOf(t.length-1)>-1);for(let c=0;c-1}get whitespace(){return this.spec.whitespace||(this.spec.code?"pre":"normal")}hasRequiredAttrs(){for(let e in this.attrs)if(this.attrs[e].isRequired)return!0;return!1}compatibleContent(e){return this==e||this.contentMatch.compatible(e.contentMatch)}computeAttrs(e){return!e&&this.defaultAttrs?this.defaultAttrs:Tme(this.attrs,e)}create(e=null,r,n){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new Zy(this,this.computeAttrs(e),Qr.from(r),Ra.setFrom(n))}createChecked(e=null,r,n){return r=Qr.from(r),this.checkContent(r),new Zy(this,this.computeAttrs(e),r,Ra.setFrom(n))}createAndFill(e=null,r,n){if(e=this.computeAttrs(e),r=Qr.from(r),r.size){let c=this.contentMatch.fillBefore(r);if(!c)return null;r=c.append(r)}let i=this.contentMatch.matchFragment(r),o=i&&i.fillBefore(Qr.empty,!0);return o?new Zy(this,e,r.append(o),Ra.setFrom(n)):null}validContent(e){let r=this.contentMatch.matchFragment(e);if(!r||!r.validEnd)return!1;for(let n=0;n-1}allowsMarks(e){if(this.markSet==null)return!0;for(let r=0;rn[o]=new Pme(o,r,c));let i=r.spec.topNode||"doc";if(!n[i])throw new RangeError("Schema is missing its top node type ('"+i+"')");if(!n.text)throw new RangeError("Every schema needs a 'text' type");for(let o in n.text.attrs)throw new RangeError("The text node type should not have attributes");return n}};function V$e(t,e,r){let n=r.split("|");return i=>{let o=i===null?"null":typeof i;if(n.indexOf(o)<0)throw new RangeError(`Expected value of type ${n} for attribute ${e} on type ${t}, got ${o}`)}}class q$e{constructor(e,r,n){this.hasDefault=Object.prototype.hasOwnProperty.call(n,"default"),this.default=n.default,this.validate=typeof n.validate=="string"?V$e(e,r,n.validate):n.validate}get isRequired(){return!this.hasDefault}}class GD{constructor(e,r,n,i){this.name=e,this.rank=r,this.schema=n,this.spec=i,this.attrs=Ame(e,i.attrs),this.excluded=null;let o=kme(this.attrs);this.instance=o?new Ra(this,o):null}create(e=null){return!e&&this.instance?this.instance:new Ra(this,Tme(this.attrs,e))}static compile(e,r){let n=Object.create(null),i=0;return e.forEach((o,c)=>n[o]=new GD(o,i++,r,c)),n}removeFromSet(e){for(var r=0;r-1}}class Ime{constructor(e){this.linebreakReplacement=null,this.cached=Object.create(null);let r=this.spec={};for(let i in e)r[i]=e[i];r.nodes=dc.from(e.nodes),r.marks=dc.from(e.marks||{}),this.nodes=_Q.compile(this.spec.nodes,this),this.marks=GD.compile(this.spec.marks,this);let n=Object.create(null);for(let i in this.nodes){if(i in this.marks)throw new RangeError(i+" can not be both a node and a mark");let o=this.nodes[i],c=o.spec.content||"",a=o.spec.marks;if(o.contentMatch=n[c]||(n[c]=$_.parse(c,this.nodes)),o.inlineContent=o.contentMatch.inlineContent,o.spec.linebreakReplacement){if(this.linebreakReplacement)throw new RangeError("Multiple linebreak nodes defined");if(!o.isInline||!o.isLeaf)throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");this.linebreakReplacement=o}o.markSet=a=="_"?null:a?bQ(this,a.split(" ")):a==""||!o.inlineContent?[]:null}for(let i in this.marks){let o=this.marks[i],c=o.spec.excludes;o.excluded=c==null?[o]:c==""?[]:bQ(this,c.split(" "))}this.nodeFromJSON=i=>Zy.fromJSON(this,i),this.markFromJSON=i=>Ra.fromJSON(this,i),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(e,r=null,n,i){if(typeof e=="string")e=this.nodeType(e);else if(e instanceof _Q){if(e.schema!=this)throw new RangeError("Node type from different schema used ("+e.name+")")}else throw new RangeError("Invalid node type: "+e);return e.createChecked(r,n,i)}text(e,r){let n=this.nodes.text;return new JM(n,n.defaultAttrs,e,Ra.setFrom(r))}mark(e,r){return typeof e=="string"&&(e=this.marks[e]),e.create(r)}nodeType(e){let r=this.nodes[e];if(!r)throw new RangeError("Unknown node type: "+e);return r}}function bQ(t,e){let r=[];for(let n=0;n-1)&&r.push(c=m)}if(!c)throw new SyntaxError("Unknown mark type: '"+e[n]+"'")}return r}function H$e(t){return t.tag!=null}function W$e(t){return t.style!=null}let h2=class U${constructor(e,r){this.schema=e,this.rules=r,this.tags=[],this.styles=[];let n=this.matchedStyles=[];r.forEach(i=>{if(H$e(i))this.tags.push(i);else if(W$e(i)){let o=/[^=]*/.exec(i.style)[0];n.indexOf(o)<0&&n.push(o),this.styles.push(i)}}),this.normalizeLists=!this.tags.some(i=>{if(!/^(ul|ol)\b/.test(i.tag)||!i.node)return!1;let o=e.nodes[i.node];return o.contentMatch.matchType(o)})}parse(e,r={}){let n=new jQ(this,r,!1);return n.addAll(e,Ra.none,r.from,r.to),n.finish()}parseSlice(e,r={}){let n=new jQ(this,r,!0);return n.addAll(e,Ra.none,r.from,r.to),Ln.maxOpen(n.finish())}matchTag(e,r,n){for(let i=n?this.tags.indexOf(n)+1:0;ie.length&&(a.charCodeAt(e.length)!=61||a.slice(e.length+1)!=r))){if(c.getAttrs){let m=c.getAttrs(r);if(m===!1)continue;c.attrs=m||void 0}return c}}}static schemaRules(e){let r=[];function n(i){let o=i.priority==null?50:i.priority,c=0;for(;c{n(c=SQ(c)),c.mark||c.ignore||c.clearMark||(c.mark=i)})}for(let i in e.nodes){let o=e.nodes[i].spec.parseDOM;o&&o.forEach(c=>{n(c=SQ(c)),c.node||c.ignore||c.mark||(c.node=i)})}return r}static fromSchema(e){return e.cached.domParser||(e.cached.domParser=new U$(e,U$.schemaRules(e)))}};const Mme={address:!0,article:!0,aside:!0,blockquote:!0,canvas:!0,dd:!0,div:!0,dl:!0,fieldset:!0,figcaption:!0,figure:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,li:!0,noscript:!0,ol:!0,output:!0,p:!0,pre:!0,section:!0,table:!0,tfoot:!0,ul:!0},G$e={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},Ome={ol:!0,ul:!0},dk=1,V$=2,f2=4;function wQ(t,e,r){return e!=null?(e?dk:0)|(e==="full"?V$:0):t&&t.whitespace=="pre"?dk|V$:r&~f2}class OP{constructor(e,r,n,i,o,c){this.type=e,this.attrs=r,this.marks=n,this.solid=i,this.options=c,this.content=[],this.activeMarks=Ra.none,this.match=o||(c&f2?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let r=this.type.contentMatch.fillBefore(Qr.from(e));if(r)this.match=this.type.contentMatch.matchFragment(r);else{let n=this.type.contentMatch,i;return(i=n.findWrapping(e.type))?(this.match=n,i):null}}return this.match.findWrapping(e.type)}finish(e){if(!(this.options&dk)){let n=this.content[this.content.length-1],i;if(n&&n.isText&&(i=/[ \t\r\n\u000c]+$/.exec(n.text))){let o=n;n.text.length==i[0].length?this.content.pop():this.content[this.content.length-1]=o.withText(o.text.slice(0,o.text.length-i[0].length))}}let r=Qr.from(this.content);return!e&&this.match&&(r=r.append(this.match.fillBefore(Qr.empty,!0))),this.type?this.type.create(this.attrs,r,this.marks):r}inlineContext(e){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:e.parentNode&&!Mme.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}}class jQ{constructor(e,r,n){this.parser=e,this.options=r,this.isOpen=n,this.open=0,this.localPreserveWS=!1;let i=r.topNode,o,c=wQ(null,r.preserveWhitespace,0)|(n?f2:0);i?o=new OP(i.type,i.attrs,Ra.none,!0,r.topMatch||i.type.contentMatch,c):n?o=new OP(null,null,Ra.none,!0,null,c):o=new OP(e.schema.topNodeType,null,Ra.none,!0,null,c),this.nodes=[o],this.find=r.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(e,r){e.nodeType==3?this.addTextNode(e,r):e.nodeType==1&&this.addElement(e,r)}addTextNode(e,r){let n=e.nodeValue,i=this.top,o=i.options&V$?"full":this.localPreserveWS||(i.options&dk)>0,{schema:c}=this.parser;if(o==="full"||i.inlineContext(e)||/[^ \t\r\n\u000c]/.test(n)){if(o)if(o==="full")n=n.replace(/\r\n?/g,` `);else if(c.linebreakReplacement&&/[\r\n]/.test(n)&&this.top.findWrapping(c.linebreakReplacement.create())){let a=n.split(/\r?\n|\r/);for(let m=0;m!m.clearMark(g)):r=r.concat(this.parser.schema.marks[m.mark].create(m.attrs)),m.consuming===!1)a=m;else break}}return r}addElementByRule(e,r,n,i){let o,c;if(r.node)if(c=this.parser.schema.nodes[r.node],c.isLeaf)this.insertNode(c.create(r.attrs),n,e.nodeName=="BR")||this.leafFallback(e,n);else{let m=this.enter(c,r.attrs||null,n,r.preserveWhitespace);m&&(o=!0,n=m)}else{let m=this.parser.schema.marks[r.mark];n=n.concat(m.create(r.attrs))}let a=this.top;if(c&&c.isLeaf)this.findInside(e);else if(i)this.addElement(e,n,i);else if(r.getContent)this.findInside(e),r.getContent(e,this.parser.schema).forEach(m=>this.insertNode(m,n,!1));else{let m=e;typeof r.contentElement=="string"?m=e.querySelector(r.contentElement):typeof r.contentElement=="function"?m=r.contentElement(e):r.contentElement&&(m=r.contentElement),this.findAround(e,m,!0),this.addAll(m,n),this.findAround(e,m,!1)}o&&this.sync(a)&&this.open--}addAll(e,r,n,i){let o=n||0;for(let c=n?e.childNodes[n]:e.firstChild,a=i==null?null:e.childNodes[i];c!=a;c=c.nextSibling,++o)this.findAtPoint(e,o),this.addDOM(c,r);this.findAtPoint(e,o)}findPlace(e,r,n){let i,o;for(let c=this.open,a=0;c>=0;c--){let m=this.nodes[c],g=m.findWrapping(e);if(g&&(!i||i.length>g.length+a)&&(i=g,o=m,!g.length))break;if(m.solid){if(n)break;a+=2}}if(!i)return null;this.sync(o);for(let c=0;c(c.type?c.type.allowsMarkType(g.type):NQ(g.type,e))?(m=g.addToSet(m),!1):!0),this.nodes.push(new OP(e,r,m,i,null,a)),this.open++,n}closeExtra(e=!1){let r=this.nodes.length-1;if(r>this.open){for(;r>this.open;r--)this.nodes[r-1].content.push(this.nodes[r].finish(e));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(!!(this.isOpen||this.options.topOpen))}sync(e){for(let r=this.open;r>=0;r--){if(this.nodes[r]==e)return this.open=r,!0;this.localPreserveWS&&(this.nodes[r].options|=dk)}return!1}get currentPos(){this.closeExtra();let e=0;for(let r=this.open;r>=0;r--){let n=this.nodes[r].content;for(let i=n.length-1;i>=0;i--)e+=n[i].nodeSize;r&&e++}return e}findAtPoint(e,r){if(this.find)for(let n=0;n-1)return e.split(/\s*\|\s*/).some(this.matchesContext,this);let r=e.split("/"),n=this.options.context,i=!this.isOpen&&(!n||n.parent.type==this.nodes[0].type),o=-(n?n.depth+1:0)+(i?0:1),c=(a,m)=>{for(;a>=0;a--){let g=r[a];if(g==""){if(a==r.length-1||a==0)continue;for(;m>=o;m--)if(c(a-1,m))return!0;return!1}else{let _=m>0||m==0&&i?this.nodes[m].type:n&&m>=o?n.node(m-o).type:null;if(!_||_.name!=g&&!_.isInGroup(g))return!1;m--}}return!0};return c(r.length-1,this.open)}textblockFromContext(){let e=this.options.context;if(e)for(let r=e.depth;r>=0;r--){let n=e.node(r).contentMatchAt(e.indexAfter(r)).defaultType;if(n&&n.isTextblock&&n.defaultAttrs)return n}for(let r in this.parser.schema.nodes){let n=this.parser.schema.nodes[r];if(n.isTextblock&&n.defaultAttrs)return n}}}function K$e(t){for(let e=t.firstChild,r=null;e;e=e.nextSibling){let n=e.nodeType==1?e.nodeName.toLowerCase():null;n&&Ome.hasOwnProperty(n)&&r?(r.appendChild(e),e=r):n=="li"?r=e:n&&(r=null)}}function Z$e(t,e){return(t.matches||t.msMatchesSelector||t.webkitMatchesSelector||t.mozMatchesSelector).call(t,e)}function SQ(t){let e={};for(let r in t)e[r]=t[r];return e}function NQ(t,e){let r=e.schema.nodes;for(let n in r){let i=r[n];if(!i.allowsMarkType(t))continue;let o=[],c=a=>{o.push(a);for(let m=0;m{if(o.length||c.marks.length){let a=0,m=0;for(;a=0;i--){let o=this.serializeMark(e.marks[i],e.isInline,r);o&&((o.contentDOM||o.dom).appendChild(n),n=o.dom)}return n}serializeMark(e,r,n={}){let i=this.marks[e.type.name];return i&&MI(xz(n),i(e,r),null,e.attrs)}static renderSpec(e,r,n=null,i){return MI(e,r,n,i)}static fromSchema(e){return e.cached.domSerializer||(e.cached.domSerializer=new l0(this.nodesFromSchema(e),this.marksFromSchema(e)))}static nodesFromSchema(e){let r=CQ(e.nodes);return r.text||(r.text=n=>n.text),r}static marksFromSchema(e){return CQ(e.marks)}}function CQ(t){let e={};for(let r in t){let n=t[r].spec.toDOM;n&&(e[r]=n)}return e}function xz(t){return t.document||window.document}const kQ=new WeakMap;function Y$e(t){let e=kQ.get(t);return e===void 0&&kQ.set(t,e=X$e(t)),e}function X$e(t){let e=null;function r(n){if(n&&typeof n=="object")if(Array.isArray(n))if(typeof n[0]=="string")e||(e=[]),e.push(n);else for(let i=0;i-1)throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");let c=i.indexOf(" ");c>0&&(r=i.slice(0,c),i=i.slice(c+1));let a,m=r?t.createElementNS(r,i):t.createElement(i),g=e[1],_=1;if(g&&typeof g=="object"&&g.nodeType==null&&!Array.isArray(g)){_=2;for(let j in g)if(g[j]!=null){let N=j.indexOf(" ");N>0?m.setAttributeNS(j.slice(0,N),j.slice(N+1),g[j]):j=="style"&&m.style?m.style.cssText=g[j]:m.setAttribute(j,g[j])}}for(let j=_;j_)throw new RangeError("Content hole must be the only child of its parent node");return{dom:m,contentDOM:m}}else{let{dom:C,contentDOM:P}=MI(t,N,r,n);if(m.appendChild(C),P){if(a)throw new RangeError("Multiple content holes");a=P}}}return{dom:m,contentDOM:a}}const Rme=65535,Dme=Math.pow(2,16);function Q$e(t,e){return t+e*Dme}function TQ(t){return t&Rme}function J$e(t){return(t-(t&Rme))/Dme}const Lme=1,Fme=2,OI=4,zme=8;class q${constructor(e,r,n){this.pos=e,this.delInfo=r,this.recover=n}get deleted(){return(this.delInfo&zme)>0}get deletedBefore(){return(this.delInfo&(Lme|OI))>0}get deletedAfter(){return(this.delInfo&(Fme|OI))>0}get deletedAcross(){return(this.delInfo&OI)>0}}class fd{constructor(e,r=!1){if(this.ranges=e,this.inverted=r,!e.length&&fd.empty)return fd.empty}recover(e){let r=0,n=TQ(e);if(!this.inverted)for(let i=0;ie)break;let g=this.ranges[a+o],_=this.ranges[a+c],j=m+g;if(e<=j){let N=g?e==m?-1:e==j?1:r:r,C=m+i+(N<0?0:_);if(n)return C;let P=e==(r<0?m:j)?null:Q$e(a/3,e-m),A=e==m?Fme:e==j?Lme:OI;return(r<0?e!=m:e!=j)&&(A|=zme),new q$(C,A,P)}i+=_-g}return n?e+i:new q$(e+i,0,null)}touches(e,r){let n=0,i=TQ(r),o=this.inverted?2:1,c=this.inverted?1:2;for(let a=0;ae)break;let g=this.ranges[a+o],_=m+g;if(e<=_&&a==i*3)return!0;n+=this.ranges[a+c]-g}return!1}forEach(e){let r=this.inverted?2:1,n=this.inverted?1:2;for(let i=0,o=0;i=0;r--){let i=e.getMirror(r);this.appendMap(e._maps[r].invert(),i!=null&&i>r?n-i-1:void 0)}}invert(){let e=new hk;return e.appendMappingInverted(this),e}map(e,r=1){if(this.mirror)return this._map(e,r,!0);for(let n=this.from;no&&m!c.isAtom||!a.type.allowsMarkType(this.mark.type)?c:c.mark(this.mark.addToSet(c.marks)),i),r.openStart,r.openEnd);return pl.fromReplace(e,this.from,this.to,o)}invert(){return new hp(this.from,this.to,this.mark)}map(e){let r=e.mapResult(this.from,1),n=e.mapResult(this.to,-1);return r.deleted&&n.deleted||r.pos>=n.pos?null:new My(r.pos,n.pos,this.mark)}merge(e){return e instanceof My&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new My(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,r){if(typeof r.from!="number"||typeof r.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new My(r.from,r.to,e.markFromJSON(r.mark))}}Fc.jsonID("addMark",My);class hp extends Fc{constructor(e,r,n){super(),this.from=e,this.to=r,this.mark=n}apply(e){let r=e.slice(this.from,this.to),n=new Ln(Mq(r.content,i=>i.mark(this.mark.removeFromSet(i.marks)),e),r.openStart,r.openEnd);return pl.fromReplace(e,this.from,this.to,n)}invert(){return new My(this.from,this.to,this.mark)}map(e){let r=e.mapResult(this.from,1),n=e.mapResult(this.to,-1);return r.deleted&&n.deleted||r.pos>=n.pos?null:new hp(r.pos,n.pos,this.mark)}merge(e){return e instanceof hp&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new hp(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,r){if(typeof r.from!="number"||typeof r.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new hp(r.from,r.to,e.markFromJSON(r.mark))}}Fc.jsonID("removeMark",hp);class Oy extends Fc{constructor(e,r){super(),this.pos=e,this.mark=r}apply(e){let r=e.nodeAt(this.pos);if(!r)return pl.fail("No node at mark step's position");let n=r.type.create(r.attrs,null,this.mark.addToSet(r.marks));return pl.fromReplace(e,this.pos,this.pos+1,new Ln(Qr.from(n),0,r.isLeaf?0:1))}invert(e){let r=e.nodeAt(this.pos);if(r){let n=this.mark.addToSet(r.marks);if(n.length==r.marks.length){for(let i=0;in.pos?null:new Kl(r.pos,n.pos,i,o,this.slice,this.insert,this.structure)}toJSON(){let e={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(e,r){if(typeof r.from!="number"||typeof r.to!="number"||typeof r.gapFrom!="number"||typeof r.gapTo!="number"||typeof r.insert!="number")throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new Kl(r.from,r.to,r.gapFrom,r.gapTo,Ln.fromJSON(e,r.slice),r.insert,!!r.structure)}}Fc.jsonID("replaceAround",Kl);function H$(t,e,r){let n=t.resolve(e),i=r-e,o=n.depth;for(;i>0&&o>0&&n.indexAfter(o)==n.node(o).childCount;)o--,i--;if(i>0){let c=n.node(o).maybeChild(n.indexAfter(o));for(;i>0;){if(!c||c.isLeaf)return!0;c=c.firstChild,i--}}return!1}function eUe(t,e,r,n){let i=[],o=[],c,a;t.doc.nodesBetween(e,r,(m,g,_)=>{if(!m.isInline)return;let j=m.marks;if(!n.isInSet(j)&&_.type.allowsMarkType(n.type)){let N=Math.max(g,e),C=Math.min(g+m.nodeSize,r),P=n.addToSet(j);for(let A=0;At.step(m)),o.forEach(m=>t.step(m))}function tUe(t,e,r,n){let i=[],o=0;t.doc.nodesBetween(e,r,(c,a)=>{if(!c.isInline)return;o++;let m=null;if(n instanceof GD){let g=c.marks,_;for(;_=n.isInSet(g);)(m||(m=[])).push(_),g=_.removeFromSet(g)}else n?n.isInSet(c.marks)&&(m=[n]):m=c.marks;if(m&&m.length){let g=Math.min(a+c.nodeSize,r);for(let _=0;_t.step(new hp(c.from,c.to,c.style)))}function Oq(t,e,r,n=r.contentMatch,i=!0){let o=t.doc.nodeAt(e),c=[],a=e+1;for(let m=0;m=0;m--)t.step(c[m])}function rUe(t,e,r){return(e==0||t.canReplace(e,t.childCount))&&(r==t.childCount||t.canReplace(0,r))}function Gj(t){let r=t.parent.content.cutByIndex(t.startIndex,t.endIndex);for(let n=t.depth,i=0,o=0;;--n){let c=t.$from.node(n),a=t.$from.index(n)+i,m=t.$to.indexAfter(n)-o;if(nr;P--)A||n.index(P)>0?(A=!0,_=Qr.from(n.node(P).copy(_)),j++):m--;let N=Qr.empty,C=0;for(let P=o,A=!1;P>r;P--)A||i.after(P+1)=0;c--){if(n.size){let a=r[c].type.contentMatch.matchFragment(n);if(!a||!a.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}n=Qr.from(r[c].type.create(r[c].attrs,n))}let i=e.start,o=e.end;t.step(new Kl(i,o,i,o,new Ln(n,0,0),r.length,!0))}function oUe(t,e,r,n,i){if(!n.isTextblock)throw new RangeError("Type given to setBlockType should be a textblock");let o=t.steps.length;t.doc.nodesBetween(e,r,(c,a)=>{let m=typeof i=="function"?i(c):i;if(c.isTextblock&&!c.hasMarkup(n,m)&&lUe(t.doc,t.mapping.slice(o).map(a),n)){let g=null;if(n.schema.linebreakReplacement){let C=n.whitespace=="pre",P=!!n.contentMatch.matchType(n.schema.linebreakReplacement);C&&!P?g=!1:!C&&P&&(g=!0)}g===!1&&$me(t,c,a,o),Oq(t,t.mapping.slice(o).map(a,1),n,void 0,g===null);let _=t.mapping.slice(o),j=_.map(a,1),N=_.map(a+c.nodeSize,1);return t.step(new Kl(j,N,j+1,N-1,new Ln(Qr.from(n.create(m,null,c.marks)),0,0),1,!0)),g===!0&&Bme(t,c,a,o),!1}})}function Bme(t,e,r,n){e.forEach((i,o)=>{if(i.isText){let c,a=/\r?\n|\r/g;for(;c=a.exec(i.text);){let m=t.mapping.slice(n).map(r+1+o+c.index);t.replaceWith(m,m+1,e.type.schema.linebreakReplacement.create())}}})}function $me(t,e,r,n){e.forEach((i,o)=>{if(i.type==i.type.schema.linebreakReplacement){let c=t.mapping.slice(n).map(r+1+o);t.replaceWith(c,c+1,e.type.schema.text(` `))}})}function lUe(t,e,r){let n=t.resolve(e),i=n.index();return n.parent.canReplaceWith(i,i+1,r)}function cUe(t,e,r,n,i){let o=t.doc.nodeAt(e);if(!o)throw new RangeError("No node at given position");r||(r=o.type);let c=r.create(n,null,i||o.marks);if(o.isLeaf)return t.replaceWith(e,e+o.nodeSize,c);if(!r.validContent(o.content))throw new RangeError("Invalid content for node type "+r.name);t.step(new Kl(e,e+o.nodeSize,e+1,e+o.nodeSize-1,new Ln(Qr.from(c),0,0),1,!0))}function Rm(t,e,r=1,n){let i=t.resolve(e),o=i.depth-r,c=n&&n[n.length-1]||i.parent;if(o<0||i.parent.type.spec.isolating||!i.parent.canReplace(i.index(),i.parent.childCount)||!c.type.validContent(i.parent.content.cutByIndex(i.index(),i.parent.childCount)))return!1;for(let g=i.depth-1,_=r-2;g>o;g--,_--){let j=i.node(g),N=i.index(g);if(j.type.spec.isolating)return!1;let C=j.content.cutByIndex(N,j.childCount),P=n&&n[_+1];P&&(C=C.replaceChild(0,P.type.create(P.attrs)));let A=n&&n[_]||j;if(!j.canReplace(N+1,j.childCount)||!A.type.validContent(C))return!1}let a=i.indexAfter(o),m=n&&n[0];return i.node(o).canReplaceWith(a,a,m?m.type:i.node(o+1).type)}function uUe(t,e,r=1,n){let i=t.doc.resolve(e),o=Qr.empty,c=Qr.empty;for(let a=i.depth,m=i.depth-r,g=r-1;a>m;a--,g--){o=Qr.from(i.node(a).copy(o));let _=n&&n[g];c=Qr.from(_?_.type.create(_.attrs,c):i.node(a).copy(c))}t.step(new Ul(e,e,new Ln(o.append(c),r,r),!0))}function Sx(t,e){let r=t.resolve(e),n=r.index();return Ume(r.nodeBefore,r.nodeAfter)&&r.parent.canReplace(n,n+1)}function dUe(t,e){e.content.size||t.type.compatibleContent(e.type);let r=t.contentMatchAt(t.childCount),{linebreakReplacement:n}=t.type.schema;for(let i=0;i0?(o=n.node(i+1),a++,c=n.node(i).maybeChild(a)):(o=n.node(i).maybeChild(a-1),c=n.node(i+1)),o&&!o.isTextblock&&Ume(o,c)&&n.node(i).canReplace(a,a+1))return e;if(i==0)break;e=r<0?n.before(i):n.after(i)}}function hUe(t,e,r){let n=null,{linebreakReplacement:i}=t.doc.type.schema,o=t.doc.resolve(e-r),c=o.node().type;if(i&&c.inlineContent){let _=c.whitespace=="pre",j=!!c.contentMatch.matchType(i);_&&!j?n=!1:!_&&j&&(n=!0)}let a=t.steps.length;if(n===!1){let _=t.doc.resolve(e+r);$me(t,_.node(),_.before(),a)}c.inlineContent&&Oq(t,e+r-1,c,o.node().contentMatchAt(o.index()),n==null);let m=t.mapping.slice(a),g=m.map(e-r);if(t.step(new Ul(g,m.map(e+r,-1),Ln.empty,!0)),n===!0){let _=t.doc.resolve(g);Bme(t,_.node(),_.before(),t.steps.length)}return t}function fUe(t,e,r){let n=t.resolve(e);if(n.parent.canReplaceWith(n.index(),n.index(),r))return e;if(n.parentOffset==0)for(let i=n.depth-1;i>=0;i--){let o=n.index(i);if(n.node(i).canReplaceWith(o,o,r))return n.before(i+1);if(o>0)return null}if(n.parentOffset==n.parent.content.size)for(let i=n.depth-1;i>=0;i--){let o=n.indexAfter(i);if(n.node(i).canReplaceWith(o,o,r))return n.after(i+1);if(o=0;c--){let a=c==n.depth?0:n.pos<=(n.start(c+1)+n.end(c+1))/2?-1:1,m=n.index(c)+(a>0?1:0),g=n.node(c),_=!1;if(o==1)_=g.canReplace(m,m,i);else{let j=g.contentMatchAt(m).findWrapping(i.firstChild.type);_=j&&g.canReplaceWith(m,m,j[0])}if(_)return a==0?n.pos:a<0?n.before(c+1):n.after(c+1)}return null}function ZD(t,e,r=e,n=Ln.empty){if(e==r&&!n.size)return null;let i=t.resolve(e),o=t.resolve(r);return qme(i,o,n)?new Ul(e,r,n):new pUe(i,o,n).fit()}function qme(t,e,r){return!r.openStart&&!r.openEnd&&t.start()==e.start()&&t.parent.canReplace(t.index(),e.index(),r.content)}class pUe{constructor(e,r,n){this.$from=e,this.$to=r,this.unplaced=n,this.frontier=[],this.placed=Qr.empty;for(let i=0;i<=e.depth;i++){let o=e.node(i);this.frontier.push({type:o.type,match:o.contentMatchAt(e.indexAfter(i))})}for(let i=e.depth;i>0;i--)this.placed=Qr.from(e.node(i).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){for(;this.unplaced.size;){let g=this.findFittable();g?this.placeNodes(g):this.openMore()||this.dropNode()}let e=this.mustMoveInline(),r=this.placed.size-this.depth-this.$from.depth,n=this.$from,i=this.close(e<0?this.$to:n.doc.resolve(e));if(!i)return null;let o=this.placed,c=n.depth,a=i.depth;for(;c&&a&&o.childCount==1;)o=o.firstChild.content,c--,a--;let m=new Ln(o,c,a);return e>-1?new Kl(n.pos,e,this.$to.pos,this.$to.end(),m,r):m.size||n.pos!=this.$to.pos?new Ul(n.pos,i.pos,m):null}findFittable(){let e=this.unplaced.openStart;for(let r=this.unplaced.content,n=0,i=this.unplaced.openEnd;n1&&(i=0),o.type.spec.isolating&&i<=n){e=n;break}r=o.content}for(let r=1;r<=2;r++)for(let n=r==1?e:this.unplaced.openStart;n>=0;n--){let i,o=null;n?(o=_z(this.unplaced.content,n-1).firstChild,i=o.content):i=this.unplaced.content;let c=i.firstChild;for(let a=this.depth;a>=0;a--){let{type:m,match:g}=this.frontier[a],_,j=null;if(r==1&&(c?g.matchType(c.type)||(j=g.fillBefore(Qr.from(c),!1)):o&&m.compatibleContent(o.type)))return{sliceDepth:n,frontierDepth:a,parent:o,inject:j};if(r==2&&c&&(_=g.findWrapping(c.type)))return{sliceDepth:n,frontierDepth:a,parent:o,wrap:_};if(o&&g.matchType(o.type))break}}}openMore(){let{content:e,openStart:r,openEnd:n}=this.unplaced,i=_z(e,r);return!i.childCount||i.firstChild.isLeaf?!1:(this.unplaced=new Ln(e,r+1,Math.max(n,i.size+r>=e.size-n?r+1:0)),!0)}dropNode(){let{content:e,openStart:r,openEnd:n}=this.unplaced,i=_z(e,r);if(i.childCount<=1&&r>0){let o=e.size-r<=r+i.size;this.unplaced=new Ln(UC(e,r-1,1),r-1,o?r-1:n)}else this.unplaced=new Ln(UC(e,r,1),r,n)}placeNodes({sliceDepth:e,frontierDepth:r,parent:n,inject:i,wrap:o}){for(;this.depth>r;)this.closeFrontierNode();if(o)for(let A=0;A1||m==0||A.content.size)&&(j=I,_.push(Hme(A.mark(N.allowedMarks(A.marks)),g==1?m:0,g==a.childCount?C:-1)))}let P=g==a.childCount;P||(C=-1),this.placed=VC(this.placed,r,Qr.from(_)),this.frontier[r].match=j,P&&C<0&&n&&n.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let A=0,I=a;A1&&i==this.$to.end(--n);)++i;return i}findCloseLevel(e){e:for(let r=Math.min(this.depth,e.depth);r>=0;r--){let{match:n,type:i}=this.frontier[r],o=r=0;a--){let{match:m,type:g}=this.frontier[a],_=bz(e,a,g,m,!0);if(!_||_.childCount)continue e}return{depth:r,fit:c,move:o?e.doc.resolve(e.after(r+1)):e}}}}close(e){let r=this.findCloseLevel(e);if(!r)return null;for(;this.depth>r.depth;)this.closeFrontierNode();r.fit.childCount&&(this.placed=VC(this.placed,r.depth,r.fit)),e=r.move;for(let n=r.depth+1;n<=e.depth;n++){let i=e.node(n),o=i.type.contentMatch.fillBefore(i.content,!0,e.index(n));this.openFrontierNode(i.type,i.attrs,o)}return e}openFrontierNode(e,r=null,n){let i=this.frontier[this.depth];i.match=i.match.matchType(e),this.placed=VC(this.placed,this.depth,Qr.from(e.create(r,n))),this.frontier.push({type:e,match:e.contentMatch})}closeFrontierNode(){let r=this.frontier.pop().match.fillBefore(Qr.empty,!0);r.childCount&&(this.placed=VC(this.placed,this.frontier.length,r))}}function UC(t,e,r){return e==0?t.cutByIndex(r,t.childCount):t.replaceChild(0,t.firstChild.copy(UC(t.firstChild.content,e-1,r)))}function VC(t,e,r){return e==0?t.append(r):t.replaceChild(t.childCount-1,t.lastChild.copy(VC(t.lastChild.content,e-1,r)))}function _z(t,e){for(let r=0;r1&&(n=n.replaceChild(0,Hme(n.firstChild,e-1,n.childCount==1?r-1:0))),e>0&&(n=t.type.contentMatch.fillBefore(n).append(n),r<=0&&(n=n.append(t.type.contentMatch.matchFragment(n).fillBefore(Qr.empty,!0)))),t.copy(n)}function bz(t,e,r,n,i){let o=t.node(e),c=i?t.indexAfter(e):t.index(e);if(c==o.childCount&&!r.compatibleContent(o.type))return null;let a=n.fillBefore(o.content,!0,c);return a&&!mUe(r,o.content,c)?a:null}function mUe(t,e,r){for(let n=r;n0;N--,C--){let P=i.node(N).type.spec;if(P.defining||P.definingAsContext||P.isolating)break;c.indexOf(N)>-1?a=N:i.before(N)==C&&c.splice(1,0,-N)}let m=c.indexOf(a),g=[],_=n.openStart;for(let N=n.content,C=0;;C++){let P=N.firstChild;if(g.push(P),C==n.openStart)break;N=P.content}for(let N=_-1;N>=0;N--){let C=g[N],P=gUe(C.type);if(P&&!C.sameMarkup(i.node(Math.abs(a)-1)))_=N;else if(P||!C.type.isTextblock)break}for(let N=n.openStart;N>=0;N--){let C=(N+_+1)%(n.openStart+1),P=g[C];if(P)for(let A=0;A=0&&(t.replace(e,r,n),!(t.steps.length>j));N--){let C=c[N];C<0||(e=i.before(C),r=o.after(C))}}function Wme(t,e,r,n,i){if(en){let o=i.contentMatchAt(0),c=o.fillBefore(t).append(t);t=c.append(o.matchFragment(c).fillBefore(Qr.empty,!0))}return t}function xUe(t,e,r,n){if(!n.isInline&&e==r&&t.doc.resolve(e).parent.content.size){let i=fUe(t.doc,e,n.type);i!=null&&(e=r=i)}t.replaceRange(e,r,new Ln(Qr.from(n),0,0))}function vUe(t,e,r){let n=t.doc.resolve(e),i=t.doc.resolve(r),o=Gme(n,i);for(let c=0;c0&&(m||n.node(a-1).canReplace(n.index(a-1),i.indexAfter(a-1))))return t.delete(n.before(a),i.after(a))}for(let c=1;c<=n.depth&&c<=i.depth;c++)if(e-n.start(c)==n.depth-c&&r>n.end(c)&&i.end(c)-r!=i.depth-c&&n.start(c-1)==i.start(c-1)&&n.node(c-1).canReplace(n.index(c-1),i.index(c-1)))return t.delete(n.before(c),r);t.delete(e,r)}function Gme(t,e){let r=[],n=Math.min(t.depth,e.depth);for(let i=n;i>=0;i--){let o=t.start(i);if(oe.pos+(e.depth-i)||t.node(i).type.spec.isolating||e.node(i).type.spec.isolating)break;(o==e.start(i)||i==t.depth&&i==e.depth&&t.parent.inlineContent&&e.parent.inlineContent&&i&&e.start(i-1)==o-1)&&r.push(i)}return r}class a1 extends Fc{constructor(e,r,n){super(),this.pos=e,this.attr=r,this.value=n}apply(e){let r=e.nodeAt(this.pos);if(!r)return pl.fail("No node at attribute step's position");let n=Object.create(null);for(let o in r.attrs)n[o]=r.attrs[o];n[this.attr]=this.value;let i=r.type.create(n,null,r.marks);return pl.fromReplace(e,this.pos,this.pos+1,new Ln(Qr.from(i),0,r.isLeaf?0:1))}getMap(){return fd.empty}invert(e){return new a1(this.pos,this.attr,e.nodeAt(this.pos).attrs[this.attr])}map(e){let r=e.mapResult(this.pos,1);return r.deletedAfter?null:new a1(r.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(e,r){if(typeof r.pos!="number"||typeof r.attr!="string")throw new RangeError("Invalid input for AttrStep.fromJSON");return new a1(r.pos,r.attr,r.value)}}Fc.jsonID("attr",a1);class fk extends Fc{constructor(e,r){super(),this.attr=e,this.value=r}apply(e){let r=Object.create(null);for(let i in e.attrs)r[i]=e.attrs[i];r[this.attr]=this.value;let n=e.type.create(r,e.content,e.marks);return pl.ok(n)}getMap(){return fd.empty}invert(e){return new fk(this.attr,e.attrs[this.attr])}map(e){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(e,r){if(typeof r.attr!="string")throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new fk(r.attr,r.value)}}Fc.jsonID("docAttr",fk);let Y1=class extends Error{};Y1=function t(e){let r=Error.call(this,e);return r.__proto__=t.prototype,r};Y1.prototype=Object.create(Error.prototype);Y1.prototype.constructor=Y1;Y1.prototype.name="TransformError";class Kme{constructor(e){this.doc=e,this.steps=[],this.docs=[],this.mapping=new hk}get before(){return this.docs.length?this.docs[0]:this.doc}step(e){let r=this.maybeStep(e);if(r.failed)throw new Y1(r.failed);return this}maybeStep(e){let r=e.apply(this.doc);return r.failed||this.addStep(e,r.doc),r}get docChanged(){return this.steps.length>0}addStep(e,r){this.docs.push(this.doc),this.steps.push(e),this.mapping.appendMap(e.getMap()),this.doc=r}replace(e,r=e,n=Ln.empty){let i=ZD(this.doc,e,r,n);return i&&this.step(i),this}replaceWith(e,r,n){return this.replace(e,r,new Ln(Qr.from(n),0,0))}delete(e,r){return this.replace(e,r,Ln.empty)}insert(e,r){return this.replaceWith(e,e,r)}replaceRange(e,r,n){return yUe(this,e,r,n),this}replaceRangeWith(e,r,n){return xUe(this,e,r,n),this}deleteRange(e,r){return vUe(this,e,r),this}lift(e,r){return nUe(this,e,r),this}join(e,r=1){return hUe(this,e,r),this}wrap(e,r){return aUe(this,e,r),this}setBlockType(e,r=e,n,i=null){return oUe(this,e,r,n,i),this}setNodeMarkup(e,r,n=null,i){return cUe(this,e,r,n,i),this}setNodeAttribute(e,r,n){return this.step(new a1(e,r,n)),this}setDocAttribute(e,r){return this.step(new fk(e,r)),this}addNodeMark(e,r){return this.step(new Oy(e,r)),this}removeNodeMark(e,r){let n=this.doc.nodeAt(e);if(!n)throw new RangeError("No node at position "+e);if(r instanceof Ra)r.isInSet(n.marks)&&this.step(new U_(e,r));else{let i=n.marks,o,c=[];for(;o=r.isInSet(i);)c.push(new U_(e,o)),i=o.removeFromSet(i);for(let a=c.length-1;a>=0;a--)this.step(c[a])}return this}split(e,r=1,n){return uUe(this,e,r,n),this}addMark(e,r,n){return eUe(this,e,r,n),this}removeMark(e,r,n){return tUe(this,e,r,n),this}clearIncompatible(e,r,n){return Oq(this,e,r,n),this}}const wz=Object.create(null);class Pi{constructor(e,r,n){this.$anchor=e,this.$head=r,this.ranges=n||[new _Ue(e.min(r),e.max(r))]}get anchor(){return this.$anchor.pos}get head(){return this.$head.pos}get from(){return this.$from.pos}get to(){return this.$to.pos}get $from(){return this.ranges[0].$from}get $to(){return this.ranges[0].$to}get empty(){let e=this.ranges;for(let r=0;r=0;o--){let c=r<0?Sw(e.node(0),e.node(o),e.before(o+1),e.index(o),r,n):Sw(e.node(0),e.node(o),e.after(o+1),e.index(o)+1,r,n);if(c)return c}return null}static near(e,r=1){return this.findFrom(e,r)||this.findFrom(e,-r)||new vd(e.node(0))}static atStart(e){return Sw(e,e,0,0,1)||new vd(e)}static atEnd(e){return Sw(e,e,e.content.size,e.childCount,-1)||new vd(e)}static fromJSON(e,r){if(!r||!r.type)throw new RangeError("Invalid input for Selection.fromJSON");let n=wz[r.type];if(!n)throw new RangeError(`No selection type ${r.type} defined`);return n.fromJSON(e,r)}static jsonID(e,r){if(e in wz)throw new RangeError("Duplicate use of selection JSON ID "+e);return wz[e]=r,r.prototype.jsonID=e,r}getBookmark(){return li.between(this.$anchor,this.$head).getBookmark()}}Pi.prototype.visible=!0;class _Ue{constructor(e,r){this.$from=e,this.$to=r}}let AQ=!1;function PQ(t){!AQ&&!t.parent.inlineContent&&(AQ=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+t.parent.type.name+")"))}class li extends Pi{constructor(e,r=e){PQ(e),PQ(r),super(e,r)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(e,r){let n=e.resolve(r.map(this.head));if(!n.parent.inlineContent)return Pi.near(n);let i=e.resolve(r.map(this.anchor));return new li(i.parent.inlineContent?i:n,n)}replace(e,r=Ln.empty){if(super.replace(e,r),r==Ln.empty){let n=this.$from.marksAcross(this.$to);n&&e.ensureMarks(n)}}eq(e){return e instanceof li&&e.anchor==this.anchor&&e.head==this.head}getBookmark(){return new YD(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(e,r){if(typeof r.anchor!="number"||typeof r.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new li(e.resolve(r.anchor),e.resolve(r.head))}static create(e,r,n=r){let i=e.resolve(r);return new this(i,n==r?i:e.resolve(n))}static between(e,r,n){let i=e.pos-r.pos;if((!n||i)&&(n=i>=0?1:-1),!r.parent.inlineContent){let o=Pi.findFrom(r,n,!0)||Pi.findFrom(r,-n,!0);if(o)r=o.$head;else return Pi.near(r,n)}return e.parent.inlineContent||(i==0?e=r:(e=(Pi.findFrom(e,-n,!0)||Pi.findFrom(e,n,!0)).$anchor,e.pos0?0:1);i>0?c=0;c+=i){let a=e.child(c);if(a.isAtom){if(!o&&js.isSelectable(a))return js.create(t,r-(i<0?a.nodeSize:0))}else{let m=Sw(t,a,r+i,i<0?a.childCount:0,i,o);if(m)return m}r+=a.nodeSize*i}return null}function IQ(t,e,r){let n=t.steps.length-1;if(n{c==null&&(c=_)}),t.setSelection(Pi.near(t.doc.resolve(c),r))}const MQ=1,RP=2,OQ=4;class wUe extends Kme{constructor(e){super(e.doc),this.curSelectionFor=0,this.updated=0,this.meta=Object.create(null),this.time=Date.now(),this.curSelection=e.selection,this.storedMarks=e.storedMarks}get selection(){return this.curSelectionFor0}setStoredMarks(e){return this.storedMarks=e,this.updated|=RP,this}ensureMarks(e){return Ra.sameSet(this.storedMarks||this.selection.$from.marks(),e)||this.setStoredMarks(e),this}addStoredMark(e){return this.ensureMarks(e.addToSet(this.storedMarks||this.selection.$head.marks()))}removeStoredMark(e){return this.ensureMarks(e.removeFromSet(this.storedMarks||this.selection.$head.marks()))}get storedMarksSet(){return(this.updated&RP)>0}addStep(e,r){super.addStep(e,r),this.updated=this.updated&~RP,this.storedMarks=null}setTime(e){return this.time=e,this}replaceSelection(e){return this.selection.replace(this,e),this}replaceSelectionWith(e,r=!0){let n=this.selection;return r&&(e=e.mark(this.storedMarks||(n.empty?n.$from.marks():n.$from.marksAcross(n.$to)||Ra.none))),n.replaceWith(this,e),this}deleteSelection(){return this.selection.replace(this),this}insertText(e,r,n){let i=this.doc.type.schema;if(r==null)return e?this.replaceSelectionWith(i.text(e),!0):this.deleteSelection();{if(n==null&&(n=r),!e)return this.deleteRange(r,n);let o=this.storedMarks;if(!o){let c=this.doc.resolve(r);o=n==r?c.marks():c.marksAcross(this.doc.resolve(n))}return this.replaceRangeWith(r,n,i.text(e,o)),!this.selection.empty&&this.selection.to==r+e.length&&this.setSelection(Pi.near(this.selection.$to)),this}}setMeta(e,r){return this.meta[typeof e=="string"?e:e.key]=r,this}getMeta(e){return this.meta[typeof e=="string"?e:e.key]}get isGeneric(){for(let e in this.meta)return!1;return!0}scrollIntoView(){return this.updated|=OQ,this}get scrolledIntoView(){return(this.updated&OQ)>0}}function RQ(t,e){return!e||!t?t:t.bind(e)}class qC{constructor(e,r,n){this.name=e,this.init=RQ(r.init,n),this.apply=RQ(r.apply,n)}}const jUe=[new qC("doc",{init(t){return t.doc||t.schema.topNodeType.createAndFill()},apply(t){return t.doc}}),new qC("selection",{init(t,e){return t.selection||Pi.atStart(e.doc)},apply(t){return t.selection}}),new qC("storedMarks",{init(t){return t.storedMarks||null},apply(t,e,r,n){return n.selection.$cursor?t.storedMarks:null}}),new qC("scrollToSelection",{init(){return 0},apply(t,e){return t.scrolledIntoView?e+1:e}})];class jz{constructor(e,r){this.schema=e,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=jUe.slice(),r&&r.forEach(n=>{if(this.pluginsByKey[n.key])throw new RangeError("Adding different instances of a keyed plugin ("+n.key+")");this.plugins.push(n),this.pluginsByKey[n.key]=n,n.spec.state&&this.fields.push(new qC(n.key,n.spec.state,n))})}}class zw{constructor(e){this.config=e}get schema(){return this.config.schema}get plugins(){return this.config.plugins}apply(e){return this.applyTransaction(e).state}filterTransaction(e,r=-1){for(let n=0;nn.toJSON())),e&&typeof e=="object")for(let n in e){if(n=="doc"||n=="selection")throw new RangeError("The JSON fields `doc` and `selection` are reserved");let i=e[n],o=i.spec.state;o&&o.toJSON&&(r[n]=o.toJSON.call(i,this[i.key]))}return r}static fromJSON(e,r,n){if(!r)throw new RangeError("Invalid input for EditorState.fromJSON");if(!e.schema)throw new RangeError("Required config field 'schema' missing");let i=new jz(e.schema,e.plugins),o=new zw(i);return i.fields.forEach(c=>{if(c.name=="doc")o.doc=Zy.fromJSON(e.schema,r.doc);else if(c.name=="selection")o.selection=Pi.fromJSON(o.doc,r.selection);else if(c.name=="storedMarks")r.storedMarks&&(o.storedMarks=r.storedMarks.map(e.schema.markFromJSON));else{if(n)for(let a in n){let m=n[a],g=m.spec.state;if(m.key==c.name&&g&&g.fromJSON&&Object.prototype.hasOwnProperty.call(r,a)){o[c.name]=g.fromJSON.call(m,e,r[a],o);return}}o[c.name]=c.init(e,o)}}),o}}function Zme(t,e,r){for(let n in t){let i=t[n];i instanceof Function?i=i.bind(e):n=="handleDOMEvents"&&(i=Zme(i,e,{})),r[n]=i}return r}class wc{constructor(e){this.spec=e,this.props={},e.props&&Zme(e.props,this,this.props),this.key=e.key?e.key.key:Yme("plugin")}getState(e){return e[this.key]}}const Sz=Object.create(null);function Yme(t){return t in Sz?t+"$"+ ++Sz[t]:(Sz[t]=0,t+"$")}class kd{constructor(e="key"){this.key=Yme(e)}get(e){return e.config.pluginsByKey[this.key]}getState(e){return e[this.key]}}const pc=function(t){for(var e=0;;e++)if(t=t.previousSibling,!t)return e},X1=function(t){let e=t.assignedSlot||t.parentNode;return e&&e.nodeType==11?e.host:e};let W$=null;const wm=function(t,e,r){let n=W$||(W$=document.createRange());return n.setEnd(t,r??t.nodeValue.length),n.setStart(t,e||0),n},SUe=function(){W$=null},V_=function(t,e,r,n){return r&&(DQ(t,e,r,n,-1)||DQ(t,e,r,n,1))},NUe=/^(img|br|input|textarea|hr)$/i;function DQ(t,e,r,n,i){for(var o;;){if(t==r&&e==n)return!0;if(e==(i<0?0:rh(t))){let c=t.parentNode;if(!c||c.nodeType!=1||DT(t)||NUe.test(t.nodeName)||t.contentEditable=="false")return!1;e=pc(t)+(i<0?0:1),t=c}else if(t.nodeType==1){let c=t.childNodes[e+(i<0?-1:0)];if(c.nodeType==1&&c.contentEditable=="false")if(!((o=c.pmViewDesc)===null||o===void 0)&&o.ignoreForSelection)e+=i;else return!1;else t=c,e=i<0?rh(t):0}else return!1}}function rh(t){return t.nodeType==3?t.nodeValue.length:t.childNodes.length}function CUe(t,e){for(;;){if(t.nodeType==3&&e)return t;if(t.nodeType==1&&e>0){if(t.contentEditable=="false")return null;t=t.childNodes[e-1],e=rh(t)}else if(t.parentNode&&!DT(t))e=pc(t),t=t.parentNode;else return null}}function kUe(t,e){for(;;){if(t.nodeType==3&&e2),Qd=Q1||(kp?/Mac/.test(kp.platform):!1),Jme=kp?/Win/.test(kp.platform):!1,Am=/Android \d/.test(Nx),LT=!!LQ&&"webkitFontSmoothing"in LQ.documentElement.style,PUe=LT?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function IUe(t){let e=t.defaultView&&t.defaultView.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:t.documentElement.clientWidth,top:0,bottom:t.documentElement.clientHeight}}function fm(t,e){return typeof t=="number"?t:t[e]}function MUe(t){let e=t.getBoundingClientRect(),r=e.width/t.offsetWidth||1,n=e.height/t.offsetHeight||1;return{left:e.left,right:e.left+t.clientWidth*r,top:e.top,bottom:e.top+t.clientHeight*n}}function FQ(t,e,r){let n=t.someProp("scrollThreshold")||0,i=t.someProp("scrollMargin")||5,o=t.dom.ownerDocument;for(let c=r||t.dom;c;){if(c.nodeType!=1){c=X1(c);continue}let a=c,m=a==o.body,g=m?IUe(o):MUe(a),_=0,j=0;if(e.topg.bottom-fm(n,"bottom")&&(j=e.bottom-e.top>g.bottom-g.top?e.top+fm(i,"top")-g.top:e.bottom-g.bottom+fm(i,"bottom")),e.leftg.right-fm(n,"right")&&(_=e.right-g.right+fm(i,"right")),_||j)if(m)o.defaultView.scrollBy(_,j);else{let C=a.scrollLeft,P=a.scrollTop;j&&(a.scrollTop+=j),_&&(a.scrollLeft+=_);let A=a.scrollLeft-C,I=a.scrollTop-P;e={left:e.left-A,top:e.top-I,right:e.right-A,bottom:e.bottom-I}}let N=m?"fixed":getComputedStyle(c).position;if(/^(fixed|sticky)$/.test(N))break;c=N=="absolute"?c.offsetParent:X1(c)}}function OUe(t){let e=t.dom.getBoundingClientRect(),r=Math.max(0,e.top),n,i;for(let o=(e.left+e.right)/2,c=r+1;c=r-20){n=a,i=m.top;break}}return{refDOM:n,refTop:i,stack:ege(t.dom)}}function ege(t){let e=[],r=t.ownerDocument;for(let n=t;n&&(e.push({dom:n,top:n.scrollTop,left:n.scrollLeft}),t!=r);n=X1(n));return e}function RUe({refDOM:t,refTop:e,stack:r}){let n=t?t.getBoundingClientRect().top:0;tge(r,n==0?0:n-e)}function tge(t,e){for(let r=0;r=a){c=Math.max(P.bottom,c),a=Math.min(P.top,a);let A=P.left>e.left?P.left-e.left:P.right=(P.left+P.right)/2?1:0));continue}}else P.top>e.top&&!m&&P.left<=e.left&&P.right>=e.left&&(m=_,g={left:Math.max(P.left,Math.min(P.right,e.left)),top:P.top});!r&&(e.left>=P.right&&e.top>=P.top||e.left>=P.left&&e.top>=P.bottom)&&(o=j+1)}}return!r&&m&&(r=m,i=g,n=0),r&&r.nodeType==3?LUe(r,i):!r||n&&r.nodeType==1?{node:t,offset:o}:rge(r,i)}function LUe(t,e){let r=t.nodeValue.length,n=document.createRange(),i;for(let o=0;o=(c.left+c.right)/2?1:0)};break}}return n.detach(),i||{node:t,offset:0}}function Lq(t,e){return t.left>=e.left-1&&t.left<=e.right+1&&t.top>=e.top-1&&t.top<=e.bottom+1}function FUe(t,e){let r=t.parentNode;return r&&/^li$/i.test(r.nodeName)&&e.left(c.left+c.right)/2?1:-1}return t.docView.posFromDOM(n,i,o)}function BUe(t,e,r,n){let i=-1;for(let o=e,c=!1;o!=t.dom;){let a=t.docView.nearestDesc(o,!0),m;if(!a)return null;if(a.dom.nodeType==1&&(a.node.isBlock&&a.parent||!a.contentDOM)&&((m=a.dom.getBoundingClientRect()).width||m.height)&&(a.node.isBlock&&a.parent&&!/^T(R|BODY|HEAD|FOOT)$/.test(a.dom.nodeName)&&(!c&&m.left>n.left||m.top>n.top?i=a.posBefore:(!c&&m.right-1?i:t.docView.posFromDOM(e,r,-1)}function nge(t,e,r){let n=t.childNodes.length;if(n&&r.tope.top&&i++}let g;LT&&i&&n.nodeType==1&&(g=n.childNodes[i-1]).nodeType==1&&g.contentEditable=="false"&&g.getBoundingClientRect().top>=e.top&&i--,n==t.dom&&i==n.childNodes.length-1&&n.lastChild.nodeType==1&&e.top>n.lastChild.getBoundingClientRect().bottom?a=t.state.doc.content.size:(i==0||n.nodeType!=1||n.childNodes[i-1].nodeName!="BR")&&(a=BUe(t,n,i,e))}a==null&&(a=zUe(t,c,e));let m=t.docView.nearestDesc(c,!0);return{pos:a,inside:m?m.posAtStart-m.border:-1}}function zQ(t){return t.top=0&&i==n.nodeValue.length?(m--,_=1):r<0?m--:g++,vC(ty(wm(n,m,g),_),_<0)}if(!t.state.doc.resolve(e-(o||0)).parent.inlineContent){if(o==null&&i&&(r<0||i==rh(n))){let m=n.childNodes[i-1];if(m.nodeType==1)return Nz(m.getBoundingClientRect(),!1)}if(o==null&&i=0)}if(o==null&&i&&(r<0||i==rh(n))){let m=n.childNodes[i-1],g=m.nodeType==3?wm(m,rh(m)-(c?0:1)):m.nodeType==1&&(m.nodeName!="BR"||!m.nextSibling)?m:null;if(g)return vC(ty(g,1),!1)}if(o==null&&i=0)}function vC(t,e){if(t.width==0)return t;let r=e?t.left:t.right;return{top:t.top,bottom:t.bottom,left:r,right:r}}function Nz(t,e){if(t.height==0)return t;let r=e?t.top:t.bottom;return{top:r,bottom:r,left:t.left,right:t.right}}function ige(t,e,r){let n=t.state,i=t.root.activeElement;n!=e&&t.updateState(e),i!=t.dom&&t.focus();try{return r()}finally{n!=e&&t.updateState(n),i!=t.dom&&i&&i.focus()}}function VUe(t,e,r){let n=e.selection,i=r=="up"?n.$from:n.$to;return ige(t,e,()=>{let{node:o}=t.docView.domFromPos(i.pos,r=="up"?-1:1);for(;;){let a=t.docView.nearestDesc(o,!0);if(!a)break;if(a.node.isBlock){o=a.contentDOM||a.dom;break}o=a.dom.parentNode}let c=sge(t,i.pos,1);for(let a=o.firstChild;a;a=a.nextSibling){let m;if(a.nodeType==1)m=a.getClientRects();else if(a.nodeType==3)m=wm(a,0,a.nodeValue.length).getClientRects();else continue;for(let g=0;g_.top+1&&(r=="up"?c.top-_.top>(_.bottom-c.top)*2:_.bottom-c.bottom>(c.bottom-_.top)*2))return!1}}return!0})}const qUe=/[\u0590-\u08ac]/;function HUe(t,e,r){let{$head:n}=e.selection;if(!n.parent.isTextblock)return!1;let i=n.parentOffset,o=!i,c=i==n.parent.content.size,a=t.domSelection();return a?!qUe.test(n.parent.textContent)||!a.modify?r=="left"||r=="backward"?o:c:ige(t,e,()=>{let{focusNode:m,focusOffset:g,anchorNode:_,anchorOffset:j}=t.domSelectionRange(),N=a.caretBidiLevel;a.modify("move",r,"character");let C=n.depth?t.docView.domAfterPos(n.before()):t.dom,{focusNode:P,focusOffset:A}=t.domSelectionRange(),I=P&&!C.contains(P.nodeType==1?P:P.parentNode)||m==P&&g==A;try{a.collapse(_,j),m&&(m!=_||g!=j)&&a.extend&&a.extend(m,g)}catch{}return N!=null&&(a.caretBidiLevel=N),I}):n.pos==n.start()||n.pos==n.end()}let BQ=null,$Q=null,UQ=!1;function WUe(t,e,r){return BQ==e&&$Q==r?UQ:(BQ=e,$Q=r,UQ=r=="up"||r=="down"?VUe(t,e,r):HUe(t,e,r))}const uh=0,VQ=1,Yv=2,Tp=3;class FT{constructor(e,r,n,i){this.parent=e,this.children=r,this.dom=n,this.contentDOM=i,this.dirty=uh,n.pmViewDesc=this}matchesWidget(e){return!1}matchesMark(e){return!1}matchesNode(e,r,n){return!1}matchesHack(e){return!1}parseRule(){return null}stopEvent(e){return!1}get size(){let e=0;for(let r=0;rpc(this.contentDOM);else if(this.contentDOM&&this.contentDOM!=this.dom&&this.dom.contains(this.contentDOM))i=e.compareDocumentPosition(this.contentDOM)&2;else if(this.dom.firstChild){if(r==0)for(let o=e;;o=o.parentNode){if(o==this.dom){i=!1;break}if(o.previousSibling)break}if(i==null&&r==e.childNodes.length)for(let o=e;;o=o.parentNode){if(o==this.dom){i=!0;break}if(o.nextSibling)break}}return i??n>0?this.posAtEnd:this.posAtStart}nearestDesc(e,r=!1){for(let n=!0,i=e;i;i=i.parentNode){let o=this.getDesc(i),c;if(o&&(!r||o.node))if(n&&(c=o.nodeDOM)&&!(c.nodeType==1?c.contains(e.nodeType==1?e:e.parentNode):c==e))n=!1;else return o}}getDesc(e){let r=e.pmViewDesc;for(let n=r;n;n=n.parent)if(n==this)return r}posFromDOM(e,r,n){for(let i=e;i;i=i.parentNode){let o=this.getDesc(i);if(o)return o.localPosFromDOM(e,r,n)}return-1}descAt(e){for(let r=0,n=0;re||c instanceof oge){i=e-o;break}o=a}if(i)return this.children[n].domFromPos(i-this.children[n].border,r);for(let o;n&&!(o=this.children[n-1]).size&&o instanceof age&&o.side>=0;n--);if(r<=0){let o,c=!0;for(;o=n?this.children[n-1]:null,!(!o||o.dom.parentNode==this.contentDOM);n--,c=!1);return o&&r&&c&&!o.border&&!o.domAtom?o.domFromPos(o.size,r):{node:this.contentDOM,offset:o?pc(o.dom)+1:0}}else{let o,c=!0;for(;o=n=_&&r<=g-m.border&&m.node&&m.contentDOM&&this.contentDOM.contains(m.contentDOM))return m.parseRange(e,r,_);e=c;for(let j=a;j>0;j--){let N=this.children[j-1];if(N.size&&N.dom.parentNode==this.contentDOM&&!N.emptyChildAt(1)){i=pc(N.dom)+1;break}e-=N.size}i==-1&&(i=0)}if(i>-1&&(g>r||a==this.children.length-1)){r=g;for(let _=a+1;_P&&cr){let P=a;a=m,m=P}let C=document.createRange();C.setEnd(m.node,m.offset),C.setStart(a.node,a.offset),g.removeAllRanges(),g.addRange(C)}}ignoreMutation(e){return!this.contentDOM&&e.type!="selection"}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(e,r){for(let n=0,i=0;i=n:en){let a=n+o.border,m=c-o.border;if(e>=a&&r<=m){this.dirty=e==n||r==c?Yv:VQ,e==a&&r==m&&(o.contentLost||o.dom.parentNode!=this.contentDOM)?o.dirty=Tp:o.markDirty(e-a,r-a);return}else o.dirty=o.dom==o.contentDOM&&o.dom.parentNode==this.contentDOM&&!o.children.length?Yv:Tp}n=c}this.dirty=Yv}markParentsDirty(){let e=1;for(let r=this.parent;r;r=r.parent,e++){let n=e==1?Yv:VQ;r.dirty{if(!o)return i;if(o.parent)return o.parent.posBeforeChild(o)})),!r.type.spec.raw){if(c.nodeType!=1){let a=document.createElement("span");a.appendChild(c),c=a}c.contentEditable="false",c.classList.add("ProseMirror-widget")}super(e,[],c,null),this.widget=r,this.widget=r,o=this}matchesWidget(e){return this.dirty==uh&&e.type.eq(this.widget.type)}parseRule(){return{ignore:!0}}stopEvent(e){let r=this.widget.spec.stopEvent;return r?r(e):!1}ignoreMutation(e){return e.type!="selection"||this.widget.spec.ignoreSelection}destroy(){this.widget.type.destroy(this.dom),super.destroy()}get domAtom(){return!0}get ignoreForSelection(){return!!this.widget.type.spec.relaxedSide}get side(){return this.widget.type.side}}class GUe extends FT{constructor(e,r,n,i){super(e,[],r,null),this.textDOM=n,this.text=i}get size(){return this.text.length}localPosFromDOM(e,r){return e!=this.textDOM?this.posAtStart+(r?this.size:0):this.posAtStart+r}domFromPos(e){return{node:this.textDOM,offset:e}}ignoreMutation(e){return e.type==="characterData"&&e.target.nodeValue==e.oldValue}}class q_ extends FT{constructor(e,r,n,i,o){super(e,[],n,i),this.mark=r,this.spec=o}static create(e,r,n,i){let o=i.nodeViews[r.type.name],c=o&&o(r,i,n);return(!c||!c.dom)&&(c=l0.renderSpec(document,r.type.spec.toDOM(r,n),null,r.attrs)),new q_(e,r,c.dom,c.contentDOM||c.dom,c)}parseRule(){return this.dirty&Tp||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(e){return this.dirty!=Tp&&this.mark.eq(e)}markDirty(e,r){if(super.markDirty(e,r),this.dirty!=uh){let n=this.parent;for(;!n.node;)n=n.parent;n.dirty0&&(o=X$(o,0,e,n));for(let a=0;a{if(!m)return c;if(m.parent)return m.parent.posBeforeChild(m)},n,i),_=g&&g.dom,j=g&&g.contentDOM;if(r.isText){if(!_)_=document.createTextNode(r.text);else if(_.nodeType!=3)throw new RangeError("Text must be rendered as a DOM text node")}else _||({dom:_,contentDOM:j}=l0.renderSpec(document,r.type.spec.toDOM(r),null,r.attrs));!j&&!r.isText&&_.nodeName!="BR"&&(_.hasAttribute("contenteditable")||(_.contentEditable="false"),r.type.spec.draggable&&(_.draggable=!0));let N=_;return _=uge(_,n,r),g?m=new KUe(e,r,n,i,_,j||null,N,g,o,c+1):r.isText?new QD(e,r,n,i,_,N,o):new Xy(e,r,n,i,_,j||null,N,o,c+1)}parseRule(){if(this.node.type.spec.reparseInView)return null;let e={node:this.node.type.name,attrs:this.node.attrs};if(this.node.type.whitespace=="pre"&&(e.preserveWhitespace="full"),!this.contentDOM)e.getContent=()=>this.node.content;else if(!this.contentLost)e.contentElement=this.contentDOM;else{for(let r=this.children.length-1;r>=0;r--){let n=this.children[r];if(this.dom.contains(n.dom.parentNode)){e.contentElement=n.dom.parentNode;break}}e.contentElement||(e.getContent=()=>Qr.empty)}return e}matchesNode(e,r,n){return this.dirty==uh&&e.eq(this.node)&&eO(r,this.outerDeco)&&n.eq(this.innerDeco)}get size(){return this.node.nodeSize}get border(){return this.node.isLeaf?0:1}updateChildren(e,r){let n=this.node.inlineContent,i=r,o=e.composing?this.localCompositionInfo(e,r):null,c=o&&o.pos>-1?o:null,a=o&&o.pos<0,m=new YUe(this,c&&c.node,e);JUe(this.node,this.innerDeco,(g,_,j)=>{g.spec.marks?m.syncToMarks(g.spec.marks,n,e):g.type.side>=0&&!j&&m.syncToMarks(_==this.node.childCount?Ra.none:this.node.child(_).marks,n,e),m.placeWidget(g,e,i)},(g,_,j,N)=>{m.syncToMarks(g.marks,n,e);let C;m.findNodeMatch(g,_,j,N)||a&&e.state.selection.from>i&&e.state.selection.to-1&&m.updateNodeAt(g,_,j,C,e)||m.updateNextNode(g,_,j,e,N,i)||m.addNode(g,_,j,e,i),i+=g.nodeSize}),m.syncToMarks([],n,e),this.node.isTextblock&&m.addTextblockHacks(),m.destroyRest(),(m.changed||this.dirty==Yv)&&(c&&this.protectLocalComposition(e,c),lge(this.contentDOM,this.children,e),Q1&&eVe(this.dom))}localCompositionInfo(e,r){let{from:n,to:i}=e.state.selection;if(!(e.state.selection instanceof li)||nr+this.node.content.size)return null;let o=e.input.compositionNode;if(!o||!this.dom.contains(o.parentNode))return null;if(this.node.inlineContent){let c=o.nodeValue,a=tVe(this.node.content,c,n-r,i-r);return a<0?null:{node:o,pos:a,text:c}}else return{node:o,pos:-1,text:""}}protectLocalComposition(e,{node:r,pos:n,text:i}){if(this.getDesc(r))return;let o=r;for(;o.parentNode!=this.contentDOM;o=o.parentNode){for(;o.previousSibling;)o.parentNode.removeChild(o.previousSibling);for(;o.nextSibling;)o.parentNode.removeChild(o.nextSibling);o.pmViewDesc&&(o.pmViewDesc=void 0)}let c=new GUe(this,o,r,i);e.input.compositionNodes.push(c),this.children=X$(this.children,n,n+i.length,e,c)}update(e,r,n,i){return this.dirty==Tp||!e.sameMarkup(this.node)?!1:(this.updateInner(e,r,n,i),!0)}updateInner(e,r,n,i){this.updateOuterDeco(r),this.node=e,this.innerDeco=n,this.contentDOM&&this.updateChildren(i,this.posAtStart),this.dirty=uh}updateOuterDeco(e){if(eO(e,this.outerDeco))return;let r=this.nodeDOM.nodeType!=1,n=this.dom;this.dom=cge(this.dom,this.nodeDOM,Y$(this.outerDeco,this.node,r),Y$(e,this.node,r)),this.dom!=n&&(n.pmViewDesc=void 0,this.dom.pmViewDesc=this),this.outerDeco=e}selectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.add("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&(this.nodeDOM.draggable=!0))}deselectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.remove("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&this.nodeDOM.removeAttribute("draggable"))}get domAtom(){return this.node.isAtom}}function qQ(t,e,r,n,i){uge(n,e,t);let o=new Xy(void 0,t,e,r,n,n,n,i,0);return o.contentDOM&&o.updateChildren(i,0),o}class QD extends Xy{constructor(e,r,n,i,o,c,a){super(e,r,n,i,o,null,c,a,0)}parseRule(){let e=this.nodeDOM.parentNode;for(;e&&e!=this.dom&&!e.pmIsDeco;)e=e.parentNode;return{skip:e||!0}}update(e,r,n,i){return this.dirty==Tp||this.dirty!=uh&&!this.inParent()||!e.sameMarkup(this.node)?!1:(this.updateOuterDeco(r),(this.dirty!=uh||e.text!=this.node.text)&&e.text!=this.nodeDOM.nodeValue&&(this.nodeDOM.nodeValue=e.text,i.trackWrites==this.nodeDOM&&(i.trackWrites=null)),this.node=e,this.dirty=uh,!0)}inParent(){let e=this.parent.contentDOM;for(let r=this.nodeDOM;r;r=r.parentNode)if(r==e)return!0;return!1}domFromPos(e){return{node:this.nodeDOM,offset:e}}localPosFromDOM(e,r,n){return e==this.nodeDOM?this.posAtStart+Math.min(r,this.node.text.length):super.localPosFromDOM(e,r,n)}ignoreMutation(e){return e.type!="characterData"&&e.type!="selection"}slice(e,r,n){let i=this.node.cut(e,r),o=document.createTextNode(i.text);return new QD(this.parent,i,this.outerDeco,this.innerDeco,o,o,n)}markDirty(e,r){super.markDirty(e,r),this.dom!=this.nodeDOM&&(e==0||r==this.nodeDOM.nodeValue.length)&&(this.dirty=Tp)}get domAtom(){return!1}isText(e){return this.node.text==e}}class oge extends FT{parseRule(){return{ignore:!0}}matchesHack(e){return this.dirty==uh&&this.dom.nodeName==e}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class KUe extends Xy{constructor(e,r,n,i,o,c,a,m,g,_){super(e,r,n,i,o,c,a,g,_),this.spec=m}update(e,r,n,i){if(this.dirty==Tp)return!1;if(this.spec.update&&(this.node.type==e.type||this.spec.multiType)){let o=this.spec.update(e,r,n);return o&&this.updateInner(e,r,n,i),o}else return!this.contentDOM&&!e.isLeaf?!1:super.update(e,r,n,i)}selectNode(){this.spec.selectNode?this.spec.selectNode():super.selectNode()}deselectNode(){this.spec.deselectNode?this.spec.deselectNode():super.deselectNode()}setSelection(e,r,n,i){this.spec.setSelection?this.spec.setSelection(e,r,n.root):super.setSelection(e,r,n,i)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}stopEvent(e){return this.spec.stopEvent?this.spec.stopEvent(e):!1}ignoreMutation(e){return this.spec.ignoreMutation?this.spec.ignoreMutation(e):super.ignoreMutation(e)}}function lge(t,e,r){let n=t.firstChild,i=!1;for(let o=0;o>1,c=Math.min(o,e.length);for(;i-1)a>this.index&&(this.changed=!0,this.destroyBetween(this.index,a)),this.top=this.top.children[this.index];else{let m=q_.create(this.top,e[o],r,n);this.top.children.splice(this.index,0,m),this.top=m,this.changed=!0}this.index=0,o++}}findNodeMatch(e,r,n,i){let o=-1,c;if(i>=this.preMatch.index&&(c=this.preMatch.matches[i-this.preMatch.index]).parent==this.top&&c.matchesNode(e,r,n))o=this.top.children.indexOf(c,this.index);else for(let a=this.index,m=Math.min(this.top.children.length,a+5);a0;){let a;for(;;)if(n){let g=r.children[n-1];if(g instanceof q_)r=g,n=g.children.length;else{a=g,n--;break}}else{if(r==e)break e;n=r.parent.children.indexOf(r),r=r.parent}let m=a.node;if(m){if(m!=t.child(i-1))break;--i,o.set(a,i),c.push(a)}}return{index:i,matched:o,matches:c.reverse()}}function QUe(t,e){return t.type.side-e.type.side}function JUe(t,e,r,n){let i=e.locals(t),o=0;if(i.length==0){for(let g=0;go;)a.push(i[c++]);let P=o+N.nodeSize;if(N.isText){let I=P;c!I.inline):a.slice();n(N,A,e.forChild(o,N),C),o=P}}function eVe(t){if(t.nodeName=="UL"||t.nodeName=="OL"){let e=t.style.cssText;t.style.cssText=e+"; list-style: square !important",window.getComputedStyle(t).listStyle,t.style.cssText=e}}function tVe(t,e,r,n){for(let i=0,o=0;i=r){if(o>=n&&m.slice(n-e.length-a,n-a)==e)return n-e.length;let g=a=0&&g+e.length+a>=r)return a+g;if(r==n&&m.length>=n+e.length-a&&m.slice(n-a,n-a+e.length)==e)return n}}return-1}function X$(t,e,r,n,i){let o=[];for(let c=0,a=0;c=r||_<=e?o.push(m):(gr&&o.push(m.slice(r-g,m.size,n)))}return o}function Fq(t,e=null){let r=t.domSelectionRange(),n=t.state.doc;if(!r.focusNode)return null;let i=t.docView.nearestDesc(r.focusNode),o=i&&i.size==0,c=t.docView.posFromDOM(r.focusNode,r.focusOffset,1);if(c<0)return null;let a=n.resolve(c),m,g;if(XD(r)){for(m=c;i&&!i.node;)i=i.parent;let j=i.node;if(i&&j.isAtom&&js.isSelectable(j)&&i.parent&&!(j.isInline&&TUe(r.focusNode,r.focusOffset,i.dom))){let N=i.posBefore;g=new js(c==N?a:n.resolve(N))}}else{if(r instanceof t.dom.ownerDocument.defaultView.Selection&&r.rangeCount>1){let j=c,N=c;for(let C=0;C{(r.anchorNode!=n||r.anchorOffset!=i)&&(e.removeEventListener("selectionchange",t.input.hideSelectionGuard),setTimeout(()=>{(!dge(t)||t.state.selection.visible)&&t.dom.classList.remove("ProseMirror-hideselection")},20))})}function nVe(t){let e=t.domSelection();if(!e)return;let r=t.cursorWrapper.dom,n=r.nodeName=="IMG";n?e.collapse(r.parentNode,pc(r)+1):e.collapse(r,0),!n&&!t.state.selection.visible&&$u&&Yy<=11&&(r.disabled=!0,r.disabled=!1)}function hge(t,e){if(e instanceof js){let r=t.docView.descAt(e.from);r!=t.lastSelectedViewDesc&&(ZQ(t),r&&r.selectNode(),t.lastSelectedViewDesc=r)}else ZQ(t)}function ZQ(t){t.lastSelectedViewDesc&&(t.lastSelectedViewDesc.parent&&t.lastSelectedViewDesc.deselectNode(),t.lastSelectedViewDesc=void 0)}function zq(t,e,r,n){return t.someProp("createSelectionBetween",i=>i(t,e,r))||li.between(e,r,n)}function YQ(t){return t.editable&&!t.hasFocus()?!1:fge(t)}function fge(t){let e=t.domSelectionRange();if(!e.anchorNode)return!1;try{return t.dom.contains(e.anchorNode.nodeType==3?e.anchorNode.parentNode:e.anchorNode)&&(t.editable||t.dom.contains(e.focusNode.nodeType==3?e.focusNode.parentNode:e.focusNode))}catch{return!1}}function sVe(t){let e=t.docView.domFromPos(t.state.selection.anchor,0),r=t.domSelectionRange();return V_(e.node,e.offset,r.anchorNode,r.anchorOffset)}function Q$(t,e){let{$anchor:r,$head:n}=t.selection,i=e>0?r.max(n):r.min(n),o=i.parent.inlineContent?i.depth?t.doc.resolve(e>0?i.after():i.before()):null:i;return o&&Pi.findFrom(o,e)}function oy(t,e){return t.dispatch(t.state.tr.setSelection(e).scrollIntoView()),!0}function XQ(t,e,r){let n=t.state.selection;if(n instanceof li)if(r.indexOf("s")>-1){let{$head:i}=n,o=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter;if(!o||o.isText||!o.isLeaf)return!1;let c=t.state.doc.resolve(i.pos+o.nodeSize*(e<0?-1:1));return oy(t,new li(n.$anchor,c))}else if(n.empty){if(t.endOfTextblock(e>0?"forward":"backward")){let i=Q$(t.state,e);return i&&i instanceof js?oy(t,i):!1}else if(!(Qd&&r.indexOf("m")>-1)){let i=n.$head,o=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter,c;if(!o||o.isText)return!1;let a=e<0?i.pos-o.nodeSize:i.pos;return o.isAtom||(c=t.docView.descAt(a))&&!c.contentDOM?js.isSelectable(o)?oy(t,new js(e<0?t.state.doc.resolve(i.pos-o.nodeSize):i)):LT?oy(t,new li(t.state.doc.resolve(e<0?a:a+o.nodeSize))):!1:!1}}else return!1;else{if(n instanceof js&&n.node.isInline)return oy(t,new li(e>0?n.$to:n.$from));{let i=Q$(t.state,e);return i?oy(t,i):!1}}}function tO(t){return t.nodeType==3?t.nodeValue.length:t.childNodes.length}function m2(t,e){let r=t.pmViewDesc;return r&&r.size==0&&(e<0||t.nextSibling||t.nodeName!="BR")}function mw(t,e){return e<0?iVe(t):aVe(t)}function iVe(t){let e=t.domSelectionRange(),r=e.focusNode,n=e.focusOffset;if(!r)return;let i,o,c=!1;for(ch&&r.nodeType==1&&n0){if(r.nodeType!=1)break;{let a=r.childNodes[n-1];if(m2(a,-1))i=r,o=--n;else if(a.nodeType==3)r=a,n=r.nodeValue.length;else break}}else{if(pge(r))break;{let a=r.previousSibling;for(;a&&m2(a,-1);)i=r.parentNode,o=pc(a),a=a.previousSibling;if(a)r=a,n=tO(r);else{if(r=r.parentNode,r==t.dom)break;n=0}}}c?J$(t,r,n):i&&J$(t,i,o)}function aVe(t){let e=t.domSelectionRange(),r=e.focusNode,n=e.focusOffset;if(!r)return;let i=tO(r),o,c;for(;;)if(n{t.state==i&&Dm(t)},50)}function QQ(t,e){let r=t.state.doc.resolve(e);if(!(Wl||Jme)&&r.parent.inlineContent){let i=t.coordsAtPos(e);if(e>r.start()){let o=t.coordsAtPos(e-1),c=(o.top+o.bottom)/2;if(c>i.top&&c1)return o.lefti.top&&c1)return o.left>i.left?"ltr":"rtl"}}return getComputedStyle(t.dom).direction=="rtl"?"rtl":"ltr"}function JQ(t,e,r){let n=t.state.selection;if(n instanceof li&&!n.empty||r.indexOf("s")>-1||Qd&&r.indexOf("m")>-1)return!1;let{$from:i,$to:o}=n;if(!i.parent.inlineContent||t.endOfTextblock(e<0?"up":"down")){let c=Q$(t.state,e);if(c&&c instanceof js)return oy(t,c)}if(!i.parent.inlineContent){let c=e<0?i:o,a=n instanceof vd?Pi.near(c,e):Pi.findFrom(c,e);return a?oy(t,a):!1}return!1}function eJ(t,e){if(!(t.state.selection instanceof li))return!0;let{$head:r,$anchor:n,empty:i}=t.state.selection;if(!r.sameParent(n))return!0;if(!i)return!1;if(t.endOfTextblock(e>0?"forward":"backward"))return!0;let o=!r.textOffset&&(e<0?r.nodeBefore:r.nodeAfter);if(o&&!o.isText){let c=t.state.tr;return e<0?c.delete(r.pos-o.nodeSize,r.pos):c.delete(r.pos,r.pos+o.nodeSize),t.dispatch(c),!0}return!1}function tJ(t,e,r){t.domObserver.stop(),e.contentEditable=r,t.domObserver.start()}function cVe(t){if(!Lc||t.state.selection.$head.parentOffset>0)return!1;let{focusNode:e,focusOffset:r}=t.domSelectionRange();if(e&&e.nodeType==1&&r==0&&e.firstChild&&e.firstChild.contentEditable=="false"){let n=e.firstChild;tJ(t,n,"true"),setTimeout(()=>tJ(t,n,"false"),20)}return!1}function uVe(t){let e="";return t.ctrlKey&&(e+="c"),t.metaKey&&(e+="m"),t.altKey&&(e+="a"),t.shiftKey&&(e+="s"),e}function dVe(t,e){let r=e.keyCode,n=uVe(e);if(r==8||Qd&&r==72&&n=="c")return eJ(t,-1)||mw(t,-1);if(r==46&&!e.shiftKey||Qd&&r==68&&n=="c")return eJ(t,1)||mw(t,1);if(r==13||r==27)return!0;if(r==37||Qd&&r==66&&n=="c"){let i=r==37?QQ(t,t.state.selection.from)=="ltr"?-1:1:-1;return XQ(t,i,n)||mw(t,i)}else if(r==39||Qd&&r==70&&n=="c"){let i=r==39?QQ(t,t.state.selection.from)=="ltr"?1:-1:1;return XQ(t,i,n)||mw(t,i)}else{if(r==38||Qd&&r==80&&n=="c")return JQ(t,-1,n)||mw(t,-1);if(r==40||Qd&&r==78&&n=="c")return cVe(t)||JQ(t,1,n)||mw(t,1);if(n==(Qd?"m":"c")&&(r==66||r==73||r==89||r==90))return!0}return!1}function Bq(t,e){t.someProp("transformCopied",C=>{e=C(e,t)});let r=[],{content:n,openStart:i,openEnd:o}=e;for(;i>1&&o>1&&n.childCount==1&&n.firstChild.childCount==1;){i--,o--;let C=n.firstChild;r.push(C.type.name,C.attrs!=C.type.defaultAttrs?C.attrs:null),n=C.content}let c=t.someProp("clipboardSerializer")||l0.fromSchema(t.state.schema),a=_ge(),m=a.createElement("div");m.appendChild(c.serializeFragment(n,{document:a}));let g=m.firstChild,_,j=0;for(;g&&g.nodeType==1&&(_=vge[g.nodeName.toLowerCase()]);){for(let C=_.length-1;C>=0;C--){let P=a.createElement(_[C]);for(;m.firstChild;)P.appendChild(m.firstChild);m.appendChild(P),j++}g=m.firstChild}g&&g.nodeType==1&&g.setAttribute("data-pm-slice",`${i} ${o}${j?` -${j}`:""} ${JSON.stringify(r)}`);let N=t.someProp("clipboardTextSerializer",C=>C(e,t))||e.content.textBetween(0,e.content.size,` `);return{dom:m,text:N,slice:e}}function mge(t,e,r,n,i){let o=i.parent.type.spec.code,c,a;if(!r&&!e)return null;let m=!!e&&(n||o||!r);if(m){if(t.someProp("transformPastedText",N=>{e=N(e,o||n,t)}),o)return a=new Ln(Qr.from(t.state.schema.text(e.replace(/\r\n?/g,` `))),0,0),t.someProp("transformPasted",N=>{a=N(a,t,!0)}),a;let j=t.someProp("clipboardTextParser",N=>N(e,i,n,t));if(j)a=j;else{let N=i.marks(),{schema:C}=t.state,P=l0.fromSchema(C);c=document.createElement("div"),e.split(/(?:\r\n?|\n)+/).forEach(A=>{let I=c.appendChild(document.createElement("p"));A&&I.appendChild(P.serializeNode(C.text(A,N)))})}}else t.someProp("transformPastedHTML",j=>{r=j(r,t)}),c=mVe(r),LT&&gVe(c);let g=c&&c.querySelector("[data-pm-slice]"),_=g&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(g.getAttribute("data-pm-slice")||"");if(_&&_[3])for(let j=+_[3];j>0;j--){let N=c.firstChild;for(;N&&N.nodeType!=1;)N=N.nextSibling;if(!N)break;c=N}if(a||(a=(t.someProp("clipboardParser")||t.someProp("domParser")||h2.fromSchema(t.state.schema)).parseSlice(c,{preserveWhitespace:!!(m||_),context:i,ruleFromNode(N){return N.nodeName=="BR"&&!N.nextSibling&&N.parentNode&&!hVe.test(N.parentNode.nodeName)?{ignore:!0}:null}})),_)a=yVe(rJ(a,+_[1],+_[2]),_[4]);else if(a=Ln.maxOpen(fVe(a.content,i),!0),a.openStart||a.openEnd){let j=0,N=0;for(let C=a.content.firstChild;j{a=j(a,t,m)}),a}const hVe=/^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i;function fVe(t,e){if(t.childCount<2)return t;for(let r=e.depth;r>=0;r--){let i=e.node(r).contentMatchAt(e.index(r)),o,c=[];if(t.forEach(a=>{if(!c)return;let m=i.findWrapping(a.type),g;if(!m)return c=null;if(g=c.length&&o.length&&yge(m,o,a,c[c.length-1],0))c[c.length-1]=g;else{c.length&&(c[c.length-1]=xge(c[c.length-1],o.length));let _=gge(a,m);c.push(_),i=i.matchType(_.type),o=m}}),c)return Qr.from(c)}return t}function gge(t,e,r=0){for(let n=e.length-1;n>=r;n--)t=e[n].create(null,Qr.from(t));return t}function yge(t,e,r,n,i){if(i1&&(o=0),i=r&&(a=e<0?c.contentMatchAt(0).fillBefore(a,o<=i).append(a):a.append(c.contentMatchAt(c.childCount).fillBefore(Qr.empty,!0))),t.replaceChild(e<0?0:t.childCount-1,c.copy(a))}function rJ(t,e,r){return er})),kz.createHTML(t)):t}function mVe(t){let e=/^(\s*]*>)*/.exec(t);e&&(t=t.slice(e[0].length));let r=_ge().createElement("div"),n=/<([a-z][^>\s]+)/i.exec(t),i;if((i=n&&vge[n[1].toLowerCase()])&&(t=i.map(o=>"<"+o+">").join("")+t+i.map(o=>"").reverse().join("")),r.innerHTML=pVe(t),i)for(let o=0;o=0;a-=2){let m=r.nodes[n[a]];if(!m||m.hasRequiredAttrs())break;i=Qr.from(m.create(n[a+1],i)),o++,c++}return new Ln(i,o,c)}const du={},hu={},xVe={touchstart:!0,touchmove:!0};class vVe{constructor(){this.shiftKey=!1,this.mouseDown=null,this.lastKeyCode=null,this.lastKeyCodeTime=0,this.lastClick={time:0,x:0,y:0,type:"",button:0},this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastIOSEnter=0,this.lastIOSEnterFallbackTimeout=-1,this.lastFocus=0,this.lastTouch=0,this.lastChromeDelete=0,this.composing=!1,this.compositionNode=null,this.composingTimeout=-1,this.compositionNodes=[],this.compositionEndedAt=-2e8,this.compositionID=1,this.compositionPendingChanges=0,this.domChangeCount=0,this.eventHandlers=Object.create(null),this.hideSelectionGuard=null}}function _Ve(t){for(let e in du){let r=du[e];t.dom.addEventListener(e,t.input.eventHandlers[e]=n=>{wVe(t,n)&&!$q(t,n)&&(t.editable||!(n.type in hu))&&r(t,n)},xVe[e]?{passive:!0}:void 0)}Lc&&t.dom.addEventListener("input",()=>null),tU(t)}function Ry(t,e){t.input.lastSelectionOrigin=e,t.input.lastSelectionTime=Date.now()}function bVe(t){t.domObserver.stop();for(let e in t.input.eventHandlers)t.dom.removeEventListener(e,t.input.eventHandlers[e]);clearTimeout(t.input.composingTimeout),clearTimeout(t.input.lastIOSEnterFallbackTimeout)}function tU(t){t.someProp("handleDOMEvents",e=>{for(let r in e)t.input.eventHandlers[r]||t.dom.addEventListener(r,t.input.eventHandlers[r]=n=>$q(t,n))})}function $q(t,e){return t.someProp("handleDOMEvents",r=>{let n=r[e.type];return n?n(t,e)||e.defaultPrevented:!1})}function wVe(t,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let r=e.target;r!=t.dom;r=r.parentNode)if(!r||r.nodeType==11||r.pmViewDesc&&r.pmViewDesc.stopEvent(e))return!1;return!0}function jVe(t,e){!$q(t,e)&&du[e.type]&&(t.editable||!(e.type in hu))&&du[e.type](t,e)}hu.keydown=(t,e)=>{let r=e;if(t.input.shiftKey=r.keyCode==16||r.shiftKey,!wge(t,r)&&(t.input.lastKeyCode=r.keyCode,t.input.lastKeyCodeTime=Date.now(),!(Am&&Wl&&r.keyCode==13)))if(r.keyCode!=229&&t.domObserver.forceFlush(),Q1&&r.keyCode==13&&!r.ctrlKey&&!r.altKey&&!r.metaKey){let n=Date.now();t.input.lastIOSEnter=n,t.input.lastIOSEnterFallbackTimeout=setTimeout(()=>{t.input.lastIOSEnter==n&&(t.someProp("handleKeyDown",i=>i(t,$v(13,"Enter"))),t.input.lastIOSEnter=0)},200)}else t.someProp("handleKeyDown",n=>n(t,r))||dVe(t,r)?r.preventDefault():Ry(t,"key")};hu.keyup=(t,e)=>{e.keyCode==16&&(t.input.shiftKey=!1)};hu.keypress=(t,e)=>{let r=e;if(wge(t,r)||!r.charCode||r.ctrlKey&&!r.altKey||Qd&&r.metaKey)return;if(t.someProp("handleKeyPress",i=>i(t,r))){r.preventDefault();return}let n=t.state.selection;if(!(n instanceof li)||!n.$from.sameParent(n.$to)){let i=String.fromCharCode(r.charCode),o=()=>t.state.tr.insertText(i).scrollIntoView();!/[\r\n]/.test(i)&&!t.someProp("handleTextInput",c=>c(t,n.$from.pos,n.$to.pos,i,o))&&t.dispatch(o()),r.preventDefault()}};function JD(t){return{left:t.clientX,top:t.clientY}}function SVe(t,e){let r=e.x-t.clientX,n=e.y-t.clientY;return r*r+n*n<100}function Uq(t,e,r,n,i){if(n==-1)return!1;let o=t.state.doc.resolve(n);for(let c=o.depth+1;c>0;c--)if(t.someProp(e,a=>c>o.depth?a(t,r,o.nodeAfter,o.before(c),i,!0):a(t,r,o.node(c),o.before(c),i,!1)))return!0;return!1}function o1(t,e,r){if(t.focused||t.focus(),t.state.selection.eq(e))return;let n=t.state.tr.setSelection(e);n.setMeta("pointer",!0),t.dispatch(n)}function NVe(t,e){if(e==-1)return!1;let r=t.state.doc.resolve(e),n=r.nodeAfter;return n&&n.isAtom&&js.isSelectable(n)?(o1(t,new js(r)),!0):!1}function CVe(t,e){if(e==-1)return!1;let r=t.state.selection,n,i;r instanceof js&&(n=r.node);let o=t.state.doc.resolve(e);for(let c=o.depth+1;c>0;c--){let a=c>o.depth?o.nodeAfter:o.node(c);if(js.isSelectable(a)){n&&r.$from.depth>0&&c>=r.$from.depth&&o.before(r.$from.depth+1)==r.$from.pos?i=o.before(r.$from.depth):i=o.before(c);break}}return i!=null?(o1(t,js.create(t.state.doc,i)),!0):!1}function kVe(t,e,r,n,i){return Uq(t,"handleClickOn",e,r,n)||t.someProp("handleClick",o=>o(t,e,n))||(i?CVe(t,r):NVe(t,r))}function TVe(t,e,r,n){return Uq(t,"handleDoubleClickOn",e,r,n)||t.someProp("handleDoubleClick",i=>i(t,e,n))}function EVe(t,e,r,n){return Uq(t,"handleTripleClickOn",e,r,n)||t.someProp("handleTripleClick",i=>i(t,e,n))||AVe(t,r,n)}function AVe(t,e,r){if(r.button!=0)return!1;let n=t.state.doc;if(e==-1)return n.inlineContent?(o1(t,li.create(n,0,n.content.size)),!0):!1;let i=n.resolve(e);for(let o=i.depth+1;o>0;o--){let c=o>i.depth?i.nodeAfter:i.node(o),a=i.before(o);if(c.inlineContent)o1(t,li.create(n,a+1,a+1+c.content.size));else if(js.isSelectable(c))o1(t,js.create(n,a));else continue;return!0}}function Vq(t){return rO(t)}const bge=Qd?"metaKey":"ctrlKey";du.mousedown=(t,e)=>{let r=e;t.input.shiftKey=r.shiftKey;let n=Vq(t),i=Date.now(),o="singleClick";i-t.input.lastClick.time<500&&SVe(r,t.input.lastClick)&&!r[bge]&&t.input.lastClick.button==r.button&&(t.input.lastClick.type=="singleClick"?o="doubleClick":t.input.lastClick.type=="doubleClick"&&(o="tripleClick")),t.input.lastClick={time:i,x:r.clientX,y:r.clientY,type:o,button:r.button};let c=t.posAtCoords(JD(r));c&&(o=="singleClick"?(t.input.mouseDown&&t.input.mouseDown.done(),t.input.mouseDown=new PVe(t,c,r,!!n)):(o=="doubleClick"?TVe:EVe)(t,c.pos,c.inside,r)?r.preventDefault():Ry(t,"pointer"))};class PVe{constructor(e,r,n,i){this.view=e,this.pos=r,this.event=n,this.flushed=i,this.delayedSelectionSync=!1,this.mightDrag=null,this.startDoc=e.state.doc,this.selectNode=!!n[bge],this.allowDefault=n.shiftKey;let o,c;if(r.inside>-1)o=e.state.doc.nodeAt(r.inside),c=r.inside;else{let _=e.state.doc.resolve(r.pos);o=_.parent,c=_.depth?_.before():0}const a=i?null:n.target,m=a?e.docView.nearestDesc(a,!0):null;this.target=m&&m.nodeDOM.nodeType==1?m.nodeDOM:null;let{selection:g}=e.state;(n.button==0&&o.type.spec.draggable&&o.type.spec.selectable!==!1||g instanceof js&&g.from<=c&&g.to>c)&&(this.mightDrag={node:o,pos:c,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&ch&&!this.target.hasAttribute("contentEditable"))}),this.target&&this.mightDrag&&(this.mightDrag.addAttr||this.mightDrag.setUneditable)&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&(this.target.draggable=!0),this.mightDrag.setUneditable&&setTimeout(()=>{this.view.input.mouseDown==this&&this.target.setAttribute("contentEditable","false")},20),this.view.domObserver.start()),e.root.addEventListener("mouseup",this.up=this.up.bind(this)),e.root.addEventListener("mousemove",this.move=this.move.bind(this)),Ry(e,"pointer")}done(){this.view.root.removeEventListener("mouseup",this.up),this.view.root.removeEventListener("mousemove",this.move),this.mightDrag&&this.target&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&this.target.removeAttribute("draggable"),this.mightDrag.setUneditable&&this.target.removeAttribute("contentEditable"),this.view.domObserver.start()),this.delayedSelectionSync&&setTimeout(()=>Dm(this.view)),this.view.input.mouseDown=null}up(e){if(this.done(),!this.view.dom.contains(e.target))return;let r=this.pos;this.view.state.doc!=this.startDoc&&(r=this.view.posAtCoords(JD(e))),this.updateAllowDefault(e),this.allowDefault||!r?Ry(this.view,"pointer"):kVe(this.view,r.pos,r.inside,e,this.selectNode)?e.preventDefault():e.button==0&&(this.flushed||Lc&&this.mightDrag&&!this.mightDrag.node.isAtom||Wl&&!this.view.state.selection.visible&&Math.min(Math.abs(r.pos-this.view.state.selection.from),Math.abs(r.pos-this.view.state.selection.to))<=2)?(o1(this.view,Pi.near(this.view.state.doc.resolve(r.pos))),e.preventDefault()):Ry(this.view,"pointer")}move(e){this.updateAllowDefault(e),Ry(this.view,"pointer"),e.buttons==0&&this.done()}updateAllowDefault(e){!this.allowDefault&&(Math.abs(this.event.x-e.clientX)>4||Math.abs(this.event.y-e.clientY)>4)&&(this.allowDefault=!0)}}du.touchstart=t=>{t.input.lastTouch=Date.now(),Vq(t),Ry(t,"pointer")};du.touchmove=t=>{t.input.lastTouch=Date.now(),Ry(t,"pointer")};du.contextmenu=t=>Vq(t);function wge(t,e){return t.composing?!0:Lc&&Math.abs(e.timeStamp-t.input.compositionEndedAt)<500?(t.input.compositionEndedAt=-2e8,!0):!1}const IVe=Am?5e3:-1;hu.compositionstart=hu.compositionupdate=t=>{if(!t.composing){t.domObserver.flush();let{state:e}=t,r=e.selection.$to;if(e.selection instanceof li&&(e.storedMarks||!r.textOffset&&r.parentOffset&&r.nodeBefore.marks.some(n=>n.type.spec.inclusive===!1)||Wl&&Jme&&MVe(t)))t.markCursor=t.state.storedMarks||r.marks(),rO(t,!0),t.markCursor=null;else if(rO(t,!e.selection.empty),ch&&e.selection.empty&&r.parentOffset&&!r.textOffset&&r.nodeBefore.marks.length){let n=t.domSelectionRange();for(let i=n.focusNode,o=n.focusOffset;i&&i.nodeType==1&&o!=0;){let c=o<0?i.lastChild:i.childNodes[o-1];if(!c)break;if(c.nodeType==3){let a=t.domSelection();a&&a.collapse(c,c.nodeValue.length);break}else i=c,o=-1}}t.input.composing=!0}jge(t,IVe)};function MVe(t){let{focusNode:e,focusOffset:r}=t.domSelectionRange();if(!e||e.nodeType!=1||r>=e.childNodes.length)return!1;let n=e.childNodes[r];return n.nodeType==1&&n.contentEditable=="false"}hu.compositionend=(t,e)=>{t.composing&&(t.input.composing=!1,t.input.compositionEndedAt=e.timeStamp,t.input.compositionPendingChanges=t.domObserver.pendingRecords().length?t.input.compositionID:0,t.input.compositionNode=null,t.input.compositionPendingChanges&&Promise.resolve().then(()=>t.domObserver.flush()),t.input.compositionID++,jge(t,20))};function jge(t,e){clearTimeout(t.input.composingTimeout),e>-1&&(t.input.composingTimeout=setTimeout(()=>rO(t),e))}function Sge(t){for(t.composing&&(t.input.composing=!1,t.input.compositionEndedAt=RVe());t.input.compositionNodes.length>0;)t.input.compositionNodes.pop().markParentsDirty()}function OVe(t){let e=t.domSelectionRange();if(!e.focusNode)return null;let r=CUe(e.focusNode,e.focusOffset),n=kUe(e.focusNode,e.focusOffset);if(r&&n&&r!=n){let i=n.pmViewDesc,o=t.domObserver.lastChangedTextNode;if(r==o||n==o)return o;if(!i||!i.isText(n.nodeValue))return n;if(t.input.compositionNode==n){let c=r.pmViewDesc;if(!(!c||!c.isText(r.nodeValue)))return n}}return r||n}function RVe(){let t=document.createEvent("Event");return t.initEvent("event",!0,!0),t.timeStamp}function rO(t,e=!1){if(!(Am&&t.domObserver.flushingSoon>=0)){if(t.domObserver.forceFlush(),Sge(t),e||t.docView&&t.docView.dirty){let r=Fq(t),n=t.state.selection;return r&&!r.eq(n)?t.dispatch(t.state.tr.setSelection(r)):(t.markCursor||e)&&!n.$from.node(n.$from.sharedDepth(n.to)).inlineContent?t.dispatch(t.state.tr.deleteSelection()):t.updateState(t.state),!0}return!1}}function DVe(t,e){if(!t.dom.parentNode)return;let r=t.dom.parentNode.appendChild(document.createElement("div"));r.appendChild(e),r.style.cssText="position: fixed; left: -10000px; top: 10px";let n=getSelection(),i=document.createRange();i.selectNodeContents(e),t.dom.blur(),n.removeAllRanges(),n.addRange(i),setTimeout(()=>{r.parentNode&&r.parentNode.removeChild(r),t.focus()},50)}const pk=$u&&Yy<15||Q1&&PUe<604;du.copy=hu.cut=(t,e)=>{let r=e,n=t.state.selection,i=r.type=="cut";if(n.empty)return;let o=pk?null:r.clipboardData,c=n.content(),{dom:a,text:m}=Bq(t,c);o?(r.preventDefault(),o.clearData(),o.setData("text/html",a.innerHTML),o.setData("text/plain",m)):DVe(t,a),i&&t.dispatch(t.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function LVe(t){return t.openStart==0&&t.openEnd==0&&t.content.childCount==1?t.content.firstChild:null}function FVe(t,e){if(!t.dom.parentNode)return;let r=t.input.shiftKey||t.state.selection.$from.parent.type.spec.code,n=t.dom.parentNode.appendChild(document.createElement(r?"textarea":"div"));r||(n.contentEditable="true"),n.style.cssText="position: fixed; left: -10000px; top: 10px",n.focus();let i=t.input.shiftKey&&t.input.lastKeyCode!=45;setTimeout(()=>{t.focus(),n.parentNode&&n.parentNode.removeChild(n),r?mk(t,n.value,null,i,e):mk(t,n.textContent,n.innerHTML,i,e)},50)}function mk(t,e,r,n,i){let o=mge(t,e,r,n,t.state.selection.$from);if(t.someProp("handlePaste",m=>m(t,i,o||Ln.empty)))return!0;if(!o)return!1;let c=LVe(o),a=c?t.state.tr.replaceSelectionWith(c,n):t.state.tr.replaceSelection(o);return t.dispatch(a.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste")),!0}function Nge(t){let e=t.getData("text/plain")||t.getData("Text");if(e)return e;let r=t.getData("text/uri-list");return r?r.replace(/\r?\n/g," "):""}hu.paste=(t,e)=>{let r=e;if(t.composing&&!Am)return;let n=pk?null:r.clipboardData,i=t.input.shiftKey&&t.input.lastKeyCode!=45;n&&mk(t,Nge(n),n.getData("text/html"),i,r)?r.preventDefault():FVe(t,r)};class Cge{constructor(e,r,n){this.slice=e,this.move=r,this.node=n}}const zVe=Qd?"altKey":"ctrlKey";function kge(t,e){let r=t.someProp("dragCopies",n=>!n(e));return r??!e[zVe]}du.dragstart=(t,e)=>{let r=e,n=t.input.mouseDown;if(n&&n.done(),!r.dataTransfer)return;let i=t.state.selection,o=i.empty?null:t.posAtCoords(JD(r)),c;if(!(o&&o.pos>=i.from&&o.pos<=(i instanceof js?i.to-1:i.to))){if(n&&n.mightDrag)c=js.create(t.state.doc,n.mightDrag.pos);else if(r.target&&r.target.nodeType==1){let j=t.docView.nearestDesc(r.target,!0);j&&j.node.type.spec.draggable&&j!=t.docView&&(c=js.create(t.state.doc,j.posBefore))}}let a=(c||t.state.selection).content(),{dom:m,text:g,slice:_}=Bq(t,a);(!r.dataTransfer.files.length||!Wl||Qme>120)&&r.dataTransfer.clearData(),r.dataTransfer.setData(pk?"Text":"text/html",m.innerHTML),r.dataTransfer.effectAllowed="copyMove",pk||r.dataTransfer.setData("text/plain",g),t.dragging=new Cge(_,kge(t,r),c)};du.dragend=t=>{let e=t.dragging;window.setTimeout(()=>{t.dragging==e&&(t.dragging=null)},50)};hu.dragover=hu.dragenter=(t,e)=>e.preventDefault();hu.drop=(t,e)=>{try{BVe(t,e,t.dragging)}finally{t.dragging=null}};function BVe(t,e,r){if(!e.dataTransfer)return;let n=t.posAtCoords(JD(e));if(!n)return;let i=t.state.doc.resolve(n.pos),o=r&&r.slice;o?t.someProp("transformPasted",C=>{o=C(o,t,!1)}):o=mge(t,Nge(e.dataTransfer),pk?null:e.dataTransfer.getData("text/html"),!1,i);let c=!!(r&&kge(t,e));if(t.someProp("handleDrop",C=>C(t,e,o||Ln.empty,c))){e.preventDefault();return}if(!o)return;e.preventDefault();let a=o?Vme(t.state.doc,i.pos,o):i.pos;a==null&&(a=i.pos);let m=t.state.tr;if(c){let{node:C}=r;C?C.replace(m):m.deleteSelection()}let g=m.mapping.map(a),_=o.openStart==0&&o.openEnd==0&&o.content.childCount==1,j=m.doc;if(_?m.replaceRangeWith(g,g,o.content.firstChild):m.replaceRange(g,g,o),m.doc.eq(j))return;let N=m.doc.resolve(g);if(_&&js.isSelectable(o.content.firstChild)&&N.nodeAfter&&N.nodeAfter.sameMarkup(o.content.firstChild))m.setSelection(new js(N));else{let C=m.mapping.map(a);m.mapping.maps[m.mapping.maps.length-1].forEach((P,A,I,O)=>C=O),m.setSelection(zq(t,N,m.doc.resolve(C)))}t.focus(),t.dispatch(m.setMeta("uiEvent","drop"))}du.focus=t=>{t.input.lastFocus=Date.now(),t.focused||(t.domObserver.stop(),t.dom.classList.add("ProseMirror-focused"),t.domObserver.start(),t.focused=!0,setTimeout(()=>{t.docView&&t.hasFocus()&&!t.domObserver.currentSelection.eq(t.domSelectionRange())&&Dm(t)},20))};du.blur=(t,e)=>{let r=e;t.focused&&(t.domObserver.stop(),t.dom.classList.remove("ProseMirror-focused"),t.domObserver.start(),r.relatedTarget&&t.dom.contains(r.relatedTarget)&&t.domObserver.currentSelection.clear(),t.focused=!1)};du.beforeinput=(t,e)=>{if(Wl&&Am&&e.inputType=="deleteContentBackward"){t.domObserver.flushSoon();let{domChangeCount:n}=t.input;setTimeout(()=>{if(t.input.domChangeCount!=n||(t.dom.blur(),t.focus(),t.someProp("handleKeyDown",o=>o(t,$v(8,"Backspace")))))return;let{$cursor:i}=t.state.selection;i&&i.pos>0&&t.dispatch(t.state.tr.delete(i.pos-1,i.pos).scrollIntoView())},50)}};for(let t in hu)du[t]=hu[t];function gk(t,e){if(t==e)return!0;for(let r in t)if(t[r]!==e[r])return!1;for(let r in e)if(!(r in t))return!1;return!0}class nO{constructor(e,r){this.toDOM=e,this.spec=r||v_,this.side=this.spec.side||0}map(e,r,n,i){let{pos:o,deleted:c}=e.mapResult(r.from+i,this.side<0?-1:1);return c?null:new ih(o-n,o-n,this)}valid(){return!0}eq(e){return this==e||e instanceof nO&&(this.spec.key&&this.spec.key==e.spec.key||this.toDOM==e.toDOM&&gk(this.spec,e.spec))}destroy(e){this.spec.destroy&&this.spec.destroy(e)}}class Qy{constructor(e,r){this.attrs=e,this.spec=r||v_}map(e,r,n,i){let o=e.map(r.from+i,this.spec.inclusiveStart?-1:1)-n,c=e.map(r.to+i,this.spec.inclusiveEnd?1:-1)-n;return o>=c?null:new ih(o,c,this)}valid(e,r){return r.from=e&&(!o||o(a.spec))&&n.push(a.copy(a.from+i,a.to+i))}for(let c=0;ce){let a=this.children[c]+1;this.children[c+2].findInner(e-a,r-a,n,i+a,o)}}map(e,r,n){return this==Ec||e.maps.length==0?this:this.mapInner(e,r,0,0,n||v_)}mapInner(e,r,n,i,o){let c;for(let a=0;a{let g=m+n,_;if(_=Ege(r,a,g)){for(i||(i=this.children.slice());oa&&j.to=e){this.children[a]==e&&(n=this.children[a+2]);break}let o=e+1,c=o+r.content.size;for(let a=0;ao&&m.type instanceof Qy){let g=Math.max(o,m.from)-o,_=Math.min(c,m.to)-o;g<_&&(i||(i=[])).push(m.copy(g,_))}}if(i){let a=new Cl(i.sort(__),Nw);return n?new my([a,n]):a}return n||Ec}eq(e){if(this==e)return!0;if(!(e instanceof Cl)||this.local.length!=e.local.length||this.children.length!=e.children.length)return!1;for(let r=0;ri.map(e,r,v_));return my.from(n)}forChild(e,r){if(r.isLeaf)return Cl.empty;let n=[];for(let i=0;ir instanceof Cl)?e:e.reduce((r,n)=>r.concat(n instanceof Cl?n:n.members),[]))}}forEachSet(e){for(let r=0;r{let I=A-P-(C-N);for(let O=0;OR+_-j)continue;let z=a[O]+_-j;C>=z?a[O+1]=N<=z?-2:-1:N>=_&&I&&(a[O]+=I,a[O+1]+=I)}j+=I}),_=r.maps[g].map(_,-1)}let m=!1;for(let g=0;g=n.content.size){m=!0;continue}let N=r.map(t[g+1]+o,-1),C=N-i,{index:P,offset:A}=n.content.findIndex(j),I=n.maybeChild(P);if(I&&A==j&&A+I.nodeSize==C){let O=a[g+2].mapInner(r,I,_+1,t[g]+o+1,c);O!=Ec?(a[g]=j,a[g+1]=C,a[g+2]=O):(a[g+1]=-2,m=!0)}else m=!0}if(m){let g=UVe(a,t,e,r,i,o,c),_=sO(g,n,0,c);e=_.local;for(let j=0;jr&&c.to{let g=Ege(t,a,m+r);if(g){o=!0;let _=sO(g,a,r+m+1,n);_!=Ec&&i.push(m,m+a.nodeSize,_)}});let c=Tge(o?Age(t):t,-r).sort(__);for(let a=0;a0;)e++;t.splice(e,0,r)}function Tz(t){let e=[];return t.someProp("decorations",r=>{let n=r(t.state);n&&n!=Ec&&e.push(n)}),t.cursorWrapper&&e.push(Cl.create(t.state.doc,[t.cursorWrapper.deco])),my.from(e)}const VVe={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},qVe=$u&&Yy<=11;class HVe{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}set(e){this.anchorNode=e.anchorNode,this.anchorOffset=e.anchorOffset,this.focusNode=e.focusNode,this.focusOffset=e.focusOffset}clear(){this.anchorNode=this.focusNode=null}eq(e){return e.anchorNode==this.anchorNode&&e.anchorOffset==this.anchorOffset&&e.focusNode==this.focusNode&&e.focusOffset==this.focusOffset}}class WVe{constructor(e,r){this.view=e,this.handleDOMChange=r,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new HVe,this.onCharData=null,this.suppressingSelectionUpdates=!1,this.lastChangedTextNode=null,this.observer=window.MutationObserver&&new window.MutationObserver(n=>{for(let i=0;ii.type=="childList"&&i.removedNodes.length||i.type=="characterData"&&i.oldValue.length>i.target.nodeValue.length)?this.flushSoon():this.flush()}),qVe&&(this.onCharData=n=>{this.queue.push({target:n.target,type:"characterData",oldValue:n.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this)}flushSoon(){this.flushingSoon<0&&(this.flushingSoon=window.setTimeout(()=>{this.flushingSoon=-1,this.flush()},20))}forceFlush(){this.flushingSoon>-1&&(window.clearTimeout(this.flushingSoon),this.flushingSoon=-1,this.flush())}start(){this.observer&&(this.observer.takeRecords(),this.observer.observe(this.view.dom,VVe)),this.onCharData&&this.view.dom.addEventListener("DOMCharacterDataModified",this.onCharData),this.connectSelection()}stop(){if(this.observer){let e=this.observer.takeRecords();if(e.length){for(let r=0;rthis.flush(),20)}this.observer.disconnect()}this.onCharData&&this.view.dom.removeEventListener("DOMCharacterDataModified",this.onCharData),this.disconnectSelection()}connectSelection(){this.view.dom.ownerDocument.addEventListener("selectionchange",this.onSelectionChange)}disconnectSelection(){this.view.dom.ownerDocument.removeEventListener("selectionchange",this.onSelectionChange)}suppressSelectionUpdates(){this.suppressingSelectionUpdates=!0,setTimeout(()=>this.suppressingSelectionUpdates=!1,50)}onSelectionChange(){if(YQ(this.view)){if(this.suppressingSelectionUpdates)return Dm(this.view);if($u&&Yy<=11&&!this.view.state.selection.empty){let e=this.view.domSelectionRange();if(e.focusNode&&V_(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset))return this.flushSoon()}this.flush()}}setCurSelection(){this.currentSelection.set(this.view.domSelectionRange())}ignoreSelectionChange(e){if(!e.focusNode)return!0;let r=new Set,n;for(let o=e.focusNode;o;o=X1(o))r.add(o);for(let o=e.anchorNode;o;o=X1(o))if(r.has(o)){n=o;break}let i=n&&this.view.docView.nearestDesc(n);if(i&&i.ignoreMutation({type:"selection",target:n.nodeType==3?n.parentNode:n}))return this.setCurSelection(),!0}pendingRecords(){if(this.observer)for(let e of this.observer.takeRecords())this.queue.push(e);return this.queue}flush(){let{view:e}=this;if(!e.docView||this.flushingSoon>-1)return;let r=this.pendingRecords();r.length&&(this.queue=[]);let n=e.domSelectionRange(),i=!this.suppressingSelectionUpdates&&!this.currentSelection.eq(n)&&YQ(e)&&!this.ignoreSelectionChange(n),o=-1,c=-1,a=!1,m=[];if(e.editable)for(let _=0;_j.nodeName=="BR");if(_.length==2){let[j,N]=_;j.parentNode&&j.parentNode.parentNode==N.parentNode?N.remove():j.remove()}else{let{focusNode:j}=this.currentSelection;for(let N of _){let C=N.parentNode;C&&C.nodeName=="LI"&&(!j||ZVe(e,j)!=C)&&N.remove()}}}else if((Wl||Lc)&&m.some(_=>_.nodeName=="BR")&&(e.input.lastKeyCode==8||e.input.lastKeyCode==46)){for(let _ of m)if(_.nodeName=="BR"&&_.parentNode){let j=_.nextSibling;j&&j.nodeType==1&&j.contentEditable=="false"&&_.parentNode.removeChild(_)}}let g=null;o<0&&i&&e.input.lastFocus>Date.now()-200&&Math.max(e.input.lastTouch,e.input.lastClick.time)-1||i)&&(o>-1&&(e.docView.markDirty(o,c),GVe(e)),this.handleDOMChange(o,c,a,m),e.docView&&e.docView.dirty?e.updateState(e.state):this.currentSelection.eq(n)||Dm(e),this.currentSelection.set(n))}registerMutation(e,r){if(r.indexOf(e.target)>-1)return null;let n=this.view.docView.nearestDesc(e.target);if(e.type=="attributes"&&(n==this.view.docView||e.attributeName=="contenteditable"||e.attributeName=="style"&&!e.oldValue&&!e.target.getAttribute("style"))||!n||n.ignoreMutation(e))return null;if(e.type=="childList"){for(let _=0;_i;I--){let O=n.childNodes[I-1],R=O.pmViewDesc;if(O.nodeName=="BR"&&!R){o=I;break}if(!R||R.size)break}let j=t.state.doc,N=t.someProp("domParser")||h2.fromSchema(t.state.schema),C=j.resolve(c),P=null,A=N.parse(n,{topNode:C.parent,topMatch:C.parent.contentMatchAt(C.index()),topOpen:!0,from:i,to:o,preserveWhitespace:C.parent.type.whitespace=="pre"?"full":!0,findPositions:g,ruleFromNode:XVe,context:C});if(g&&g[0].pos!=null){let I=g[0].pos,O=g[1]&&g[1].pos;O==null&&(O=I),P={anchor:I+c,head:O+c}}return{doc:A,sel:P,from:c,to:a}}function XVe(t){let e=t.pmViewDesc;if(e)return e.parseRule();if(t.nodeName=="BR"&&t.parentNode){if(Lc&&/^(ul|ol)$/i.test(t.parentNode.nodeName)){let r=document.createElement("div");return r.appendChild(document.createElement("li")),{skip:r}}else if(t.parentNode.lastChild==t||Lc&&/^(tr|table)$/i.test(t.parentNode.nodeName))return{ignore:!0}}else if(t.nodeName=="IMG"&&t.getAttribute("mark-placeholder"))return{ignore:!0};return null}const QVe=/^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|img|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i;function JVe(t,e,r,n,i){let o=t.input.compositionPendingChanges||(t.composing?t.input.compositionID:0);if(t.input.compositionPendingChanges=0,e<0){let Q=t.input.lastSelectionTime>Date.now()-50?t.input.lastSelectionOrigin:null,te=Fq(t,Q);if(te&&!t.state.selection.eq(te)){if(Wl&&Am&&t.input.lastKeyCode===13&&Date.now()-100ie(t,$v(13,"Enter"))))return;let X=t.state.tr.setSelection(te);Q=="pointer"?X.setMeta("pointer",!0):Q=="key"&&X.scrollIntoView(),o&&X.setMeta("composition",o),t.dispatch(X)}return}let c=t.state.doc.resolve(e),a=c.sharedDepth(r);e=c.before(a+1),r=t.state.doc.resolve(r).after(a+1);let m=t.state.selection,g=YVe(t,e,r),_=t.state.doc,j=_.slice(g.from,g.to),N,C;t.input.lastKeyCode===8&&Date.now()-100Date.now()-225||Am)&&i.some(Q=>Q.nodeType==1&&!QVe.test(Q.nodeName))&&(!P||P.endA>=P.endB)&&t.someProp("handleKeyDown",Q=>Q(t,$v(13,"Enter")))){t.input.lastIOSEnter=0;return}if(!P)if(n&&m instanceof li&&!m.empty&&m.$head.sameParent(m.$anchor)&&!t.composing&&!(g.sel&&g.sel.anchor!=g.sel.head))P={start:m.from,endA:m.to,endB:m.to};else{if(g.sel){let Q=lJ(t,t.state.doc,g.sel);if(Q&&!Q.eq(t.state.selection)){let te=t.state.tr.setSelection(Q);o&&te.setMeta("composition",o),t.dispatch(te)}}return}t.state.selection.fromt.state.selection.from&&P.start<=t.state.selection.from+2&&t.state.selection.from>=g.from?P.start=t.state.selection.from:P.endA=t.state.selection.to-2&&t.state.selection.to<=g.to&&(P.endB+=t.state.selection.to-P.endA,P.endA=t.state.selection.to)),$u&&Yy<=11&&P.endB==P.start+1&&P.endA==P.start&&P.start>g.from&&g.doc.textBetween(P.start-g.from-1,P.start-g.from+1)=="  "&&(P.start--,P.endA--,P.endB--);let A=g.doc.resolveNoCache(P.start-g.from),I=g.doc.resolveNoCache(P.endB-g.from),O=_.resolve(P.start),R=A.sameParent(I)&&A.parent.inlineContent&&O.end()>=P.endA;if((Q1&&t.input.lastIOSEnter>Date.now()-225&&(!R||i.some(Q=>Q.nodeName=="DIV"||Q.nodeName=="P"))||!R&&A.posQ(t,$v(13,"Enter")))){t.input.lastIOSEnter=0;return}if(t.state.selection.anchor>P.start&&t6e(_,P.start,P.endA,A,I)&&t.someProp("handleKeyDown",Q=>Q(t,$v(8,"Backspace")))){Am&&Wl&&t.domObserver.suppressSelectionUpdates();return}Wl&&P.endB==P.start&&(t.input.lastChromeDelete=Date.now()),Am&&!R&&A.start()!=I.start()&&I.parentOffset==0&&A.depth==I.depth&&g.sel&&g.sel.anchor==g.sel.head&&g.sel.head==P.endA&&(P.endB-=2,I=g.doc.resolveNoCache(P.endB-g.from),setTimeout(()=>{t.someProp("handleKeyDown",function(Q){return Q(t,$v(13,"Enter"))})},20));let z=P.start,W=P.endA,V=Q=>{let te=Q||t.state.tr.replace(z,W,g.doc.slice(P.start-g.from,P.endB-g.from));if(g.sel){let X=lJ(t,te.doc,g.sel);X&&!(Wl&&t.composing&&X.empty&&(P.start!=P.endB||t.input.lastChromeDeleteDm(t),20));let Q=V(t.state.tr.delete(z,W)),te=_.resolve(P.start).marksAcross(_.resolve(P.endA));te&&Q.ensureMarks(te),t.dispatch(Q)}else if(P.endA==P.endB&&(K=e6e(A.parent.content.cut(A.parentOffset,I.parentOffset),O.parent.content.cut(O.parentOffset,P.endA-O.start())))){let Q=V(t.state.tr);K.type=="add"?Q.addMark(z,W,K.mark):Q.removeMark(z,W,K.mark),t.dispatch(Q)}else if(A.parent.child(A.index()).isText&&A.index()==I.index()-(I.textOffset?0:1)){let Q=A.parent.textBetween(A.parentOffset,I.parentOffset),te=()=>V(t.state.tr.insertText(Q,z,W));t.someProp("handleTextInput",X=>X(t,z,W,Q,te))||t.dispatch(te())}else t.dispatch(V());else t.dispatch(V())}function lJ(t,e,r){return Math.max(r.anchor,r.head)>e.content.size?null:zq(t,e.resolve(r.anchor),e.resolve(r.head))}function e6e(t,e){let r=t.firstChild.marks,n=e.firstChild.marks,i=r,o=n,c,a,m;for(let _=0;__.mark(a.addToSet(_.marks));else if(i.length==0&&o.length==1)a=o[0],c="remove",m=_=>_.mark(a.removeFromSet(_.marks));else return null;let g=[];for(let _=0;_r||Ez(c,!0,!1)0&&(e||t.indexAfter(n)==t.node(n).childCount);)n--,i++,e=!1;if(r){let o=t.node(n).maybeChild(t.indexAfter(n));for(;o&&!o.isLeaf;)o=o.firstChild,i++}return i}function r6e(t,e,r,n,i){let o=t.findDiffStart(e,r);if(o==null)return null;let{a:c,b:a}=t.findDiffEnd(e,r+t.size,r+e.size);if(i=="end"){let m=Math.max(0,o-Math.min(c,a));n-=c+m-o}if(c=c?o-n:0;o-=m,o&&o=a?o-n:0;o-=m,o&&o=56320&&e<=57343&&r>=55296&&r<=56319}class Pge{constructor(e,r){this._root=null,this.focused=!1,this.trackWrites=null,this.mounted=!1,this.markCursor=null,this.cursorWrapper=null,this.lastSelectedViewDesc=void 0,this.input=new vVe,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=r,this.state=r.state,this.directPlugins=r.plugins||[],this.directPlugins.forEach(pJ),this.dispatch=this.dispatch.bind(this),this.dom=e&&e.mount||document.createElement("div"),e&&(e.appendChild?e.appendChild(this.dom):typeof e=="function"?e(this.dom):e.mount&&(this.mounted=!0)),this.editable=hJ(this),dJ(this),this.nodeViews=fJ(this),this.docView=qQ(this.state.doc,uJ(this),Tz(this),this.dom,this),this.domObserver=new WVe(this,(n,i,o,c)=>JVe(this,n,i,o,c)),this.domObserver.start(),_Ve(this),this.updatePluginViews()}get composing(){return this.input.composing}get props(){if(this._props.state!=this.state){let e=this._props;this._props={};for(let r in e)this._props[r]=e[r];this._props.state=this.state}return this._props}update(e){e.handleDOMEvents!=this._props.handleDOMEvents&&tU(this);let r=this._props;this._props=e,e.plugins&&(e.plugins.forEach(pJ),this.directPlugins=e.plugins),this.updateStateInner(e.state,r)}setProps(e){let r={};for(let n in this._props)r[n]=this._props[n];r.state=this.state;for(let n in e)r[n]=e[n];this.update(r)}updateState(e){this.updateStateInner(e,this._props)}updateStateInner(e,r){var n;let i=this.state,o=!1,c=!1;e.storedMarks&&this.composing&&(Sge(this),c=!0),this.state=e;let a=i.plugins!=e.plugins||this._props.plugins!=r.plugins;if(a||this._props.plugins!=r.plugins||this._props.nodeViews!=r.nodeViews){let C=fJ(this);s6e(C,this.nodeViews)&&(this.nodeViews=C,o=!0)}(a||r.handleDOMEvents!=this._props.handleDOMEvents)&&tU(this),this.editable=hJ(this),dJ(this);let m=Tz(this),g=uJ(this),_=i.plugins!=e.plugins&&!i.doc.eq(e.doc)?"reset":e.scrollToSelection>i.scrollToSelection?"to selection":"preserve",j=o||!this.docView.matchesNode(e.doc,g,m);(j||!e.selection.eq(i.selection))&&(c=!0);let N=_=="preserve"&&c&&this.dom.style.overflowAnchor==null&&OUe(this);if(c){this.domObserver.stop();let C=j&&($u||Wl)&&!this.composing&&!i.selection.empty&&!e.selection.empty&&n6e(i.selection,e.selection);if(j){let P=Wl?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=OVe(this)),(o||!this.docView.update(e.doc,g,m,this))&&(this.docView.updateOuterDeco(g),this.docView.destroy(),this.docView=qQ(e.doc,g,m,this.dom,this)),P&&!this.trackWrites&&(C=!0)}C||!(this.input.mouseDown&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&sVe(this))?Dm(this,C):(hge(this,e.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(i),!((n=this.dragging)===null||n===void 0)&&n.node&&!i.doc.eq(e.doc)&&this.updateDraggedNode(this.dragging,i),_=="reset"?this.dom.scrollTop=0:_=="to selection"?this.scrollToSelection():N&&RUe(N)}scrollToSelection(){let e=this.domSelectionRange().focusNode;if(!(!e||!this.dom.contains(e.nodeType==1?e:e.parentNode))){if(!this.someProp("handleScrollToSelection",r=>r(this)))if(this.state.selection instanceof js){let r=this.docView.domAfterPos(this.state.selection.from);r.nodeType==1&&FQ(this,r.getBoundingClientRect(),e)}else FQ(this,this.coordsAtPos(this.state.selection.head,1),e)}}destroyPluginViews(){let e;for(;e=this.pluginViews.pop();)e.destroy&&e.destroy()}updatePluginViews(e){if(!e||e.plugins!=this.state.plugins||this.directPlugins!=this.prevDirectPlugins){this.prevDirectPlugins=this.directPlugins,this.destroyPluginViews();for(let r=0;r0&&this.state.doc.nodeAt(o))==n.node&&(i=o)}this.dragging=new Cge(e.slice,e.move,i<0?void 0:js.create(this.state.doc,i))}someProp(e,r){let n=this._props&&this._props[e],i;if(n!=null&&(i=r?r(n):n))return i;for(let c=0;cr.ownerDocument.getSelection()),this._root=r}return e||document}updateRoot(){this._root=null}posAtCoords(e){return $Ue(this,e)}coordsAtPos(e,r=1){return sge(this,e,r)}domAtPos(e,r=0){return this.docView.domFromPos(e,r)}nodeDOM(e){let r=this.docView.descAt(e);return r?r.nodeDOM:null}posAtDOM(e,r,n=-1){let i=this.docView.posFromDOM(e,r,n);if(i==null)throw new RangeError("DOM position not inside the editor");return i}endOfTextblock(e,r){return WUe(this,r||this.state,e)}pasteHTML(e,r){return mk(this,"",e,!1,r||new ClipboardEvent("paste"))}pasteText(e,r){return mk(this,e,null,!0,r||new ClipboardEvent("paste"))}serializeForClipboard(e){return Bq(this,e)}destroy(){this.docView&&(bVe(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],Tz(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,SUe())}get isDestroyed(){return this.docView==null}dispatchEvent(e){return jVe(this,e)}domSelectionRange(){let e=this.domSelection();return e?Lc&&this.root.nodeType===11&&EUe(this.dom.ownerDocument)==this.dom&&KVe(this,e)||e:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}Pge.prototype.dispatch=function(t){let e=this._props.dispatchTransaction;e?e.call(this,t):this.updateState(this.state.apply(t))};function uJ(t){let e=Object.create(null);return e.class="ProseMirror",e.contenteditable=String(t.editable),t.someProp("attributes",r=>{if(typeof r=="function"&&(r=r(t.state)),r)for(let n in r)n=="class"?e.class+=" "+r[n]:n=="style"?e.style=(e.style?e.style+";":"")+r[n]:!e[n]&&n!="contenteditable"&&n!="nodeName"&&(e[n]=String(r[n]))}),e.translate||(e.translate="no"),[ih.node(0,t.state.doc.content.size,e)]}function dJ(t){if(t.markCursor){let e=document.createElement("img");e.className="ProseMirror-separator",e.setAttribute("mark-placeholder","true"),e.setAttribute("alt",""),t.cursorWrapper={dom:e,deco:ih.widget(t.state.selection.from,e,{raw:!0,marks:t.markCursor})}}else t.cursorWrapper=null}function hJ(t){return!t.someProp("editable",e=>e(t.state)===!1)}function n6e(t,e){let r=Math.min(t.$anchor.sharedDepth(t.head),e.$anchor.sharedDepth(e.head));return t.$anchor.start(r)!=e.$anchor.start(r)}function fJ(t){let e=Object.create(null);function r(n){for(let i in n)Object.prototype.hasOwnProperty.call(e,i)||(e[i]=n[i])}return t.someProp("nodeViews",r),t.someProp("markViews",r),e}function s6e(t,e){let r=0,n=0;for(let i in t){if(t[i]!=e[i])return!0;r++}for(let i in e)n++;return r!=n}function pJ(t){if(t.spec.state||t.spec.filterTransaction||t.spec.appendTransaction)throw new RangeError("Plugins passed directly to the view must not have a state component")}var hx={8:"Backspace",9:"Tab",10:"Enter",12:"NumLock",13:"Enter",16:"Shift",17:"Control",18:"Alt",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",44:"PrintScreen",45:"Insert",46:"Delete",59:";",61:"=",91:"Meta",92:"Meta",106:"*",107:"+",108:",",109:"-",110:".",111:"/",144:"NumLock",145:"ScrollLock",160:"Shift",161:"Shift",162:"Control",163:"Control",164:"Alt",165:"Alt",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"},iO={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},i6e=typeof navigator<"u"&&/Mac/.test(navigator.platform),a6e=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(var mc=0;mc<10;mc++)hx[48+mc]=hx[96+mc]=String(mc);for(var mc=1;mc<=24;mc++)hx[mc+111]="F"+mc;for(var mc=65;mc<=90;mc++)hx[mc]=String.fromCharCode(mc+32),iO[mc]=String.fromCharCode(mc);for(var Az in hx)iO.hasOwnProperty(Az)||(iO[Az]=hx[Az]);function o6e(t){var e=i6e&&t.metaKey&&t.shiftKey&&!t.ctrlKey&&!t.altKey||a6e&&t.shiftKey&&t.key&&t.key.length==1||t.key=="Unidentified",r=!e&&t.key||(t.shiftKey?iO:hx)[t.keyCode]||t.key||"Unidentified";return r=="Esc"&&(r="Escape"),r=="Del"&&(r="Delete"),r=="Left"&&(r="ArrowLeft"),r=="Up"&&(r="ArrowUp"),r=="Right"&&(r="ArrowRight"),r=="Down"&&(r="ArrowDown"),r}const l6e=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),c6e=typeof navigator<"u"&&/Win/.test(navigator.platform);function u6e(t){let e=t.split(/-(?!$)/),r=e[e.length-1];r=="Space"&&(r=" ");let n,i,o,c;for(let a=0;at.selection.empty?!1:(e&&e(t.tr.deleteSelection().scrollIntoView()),!0);function Mge(t,e){let{$cursor:r}=t.selection;return!r||(e?!e.endOfTextblock("backward",t):r.parentOffset>0)?null:r}const Oge=(t,e,r)=>{let n=Mge(t,r);if(!n)return!1;let i=Gq(n);if(!i){let c=n.blockRange(),a=c&&Gj(c);return a==null?!1:(e&&e(t.tr.lift(c,a).scrollIntoView()),!0)}let o=i.nodeBefore;if(Vge(t,i,e,-1))return!0;if(n.parent.content.size==0&&(J1(o,"end")||js.isSelectable(o)))for(let c=n.depth;;c--){let a=ZD(t.doc,n.before(c),n.after(c),Ln.empty);if(a&&a.slice.size1)break}return o.isAtom&&i.depth==n.depth-1?(e&&e(t.tr.delete(i.pos-o.nodeSize,i.pos).scrollIntoView()),!0):!1},f6e=(t,e,r)=>{let n=Mge(t,r);if(!n)return!1;let i=Gq(n);return i?Rge(t,i,e):!1},p6e=(t,e,r)=>{let n=Lge(t,r);if(!n)return!1;let i=Kq(n);return i?Rge(t,i,e):!1};function Rge(t,e,r){let n=e.nodeBefore,i=n,o=e.pos-1;for(;!i.isTextblock;o--){if(i.type.spec.isolating)return!1;let _=i.lastChild;if(!_)return!1;i=_}let c=e.nodeAfter,a=c,m=e.pos+1;for(;!a.isTextblock;m++){if(a.type.spec.isolating)return!1;let _=a.firstChild;if(!_)return!1;a=_}let g=ZD(t.doc,o,m,Ln.empty);if(!g||g.from!=o||g instanceof Ul&&g.slice.size>=m-o)return!1;if(r){let _=t.tr.step(g);_.setSelection(li.create(_.doc,o)),r(_.scrollIntoView())}return!0}function J1(t,e,r=!1){for(let n=t;n;n=e=="start"?n.firstChild:n.lastChild){if(n.isTextblock)return!0;if(r&&n.childCount!=1)return!1}return!1}const Dge=(t,e,r)=>{let{$head:n,empty:i}=t.selection,o=n;if(!i)return!1;if(n.parent.isTextblock){if(r?!r.endOfTextblock("backward",t):n.parentOffset>0)return!1;o=Gq(n)}let c=o&&o.nodeBefore;return!c||!js.isSelectable(c)?!1:(e&&e(t.tr.setSelection(js.create(t.doc,o.pos-c.nodeSize)).scrollIntoView()),!0)};function Gq(t){if(!t.parent.type.spec.isolating)for(let e=t.depth-1;e>=0;e--){if(t.index(e)>0)return t.doc.resolve(t.before(e+1));if(t.node(e).type.spec.isolating)break}return null}function Lge(t,e){let{$cursor:r}=t.selection;return!r||(e?!e.endOfTextblock("forward",t):r.parentOffset{let n=Lge(t,r);if(!n)return!1;let i=Kq(n);if(!i)return!1;let o=i.nodeAfter;if(Vge(t,i,e,1))return!0;if(n.parent.content.size==0&&(J1(o,"start")||js.isSelectable(o))){let c=ZD(t.doc,n.before(),n.after(),Ln.empty);if(c&&c.slice.size{let{$head:n,empty:i}=t.selection,o=n;if(!i)return!1;if(n.parent.isTextblock){if(r?!r.endOfTextblock("forward",t):n.parentOffset=0;e--){let r=t.node(e);if(t.index(e)+1{let r=t.selection,n=r instanceof js,i;if(n){if(r.node.isTextblock||!Sx(t.doc,r.from))return!1;i=r.from}else if(i=KD(t.doc,r.from,-1),i==null)return!1;if(e){let o=t.tr.join(i);n&&o.setSelection(js.create(o.doc,i-t.doc.resolve(i).nodeBefore.nodeSize)),e(o.scrollIntoView())}return!0},g6e=(t,e)=>{let r=t.selection,n;if(r instanceof js){if(r.node.isTextblock||!Sx(t.doc,r.to))return!1;n=r.to}else if(n=KD(t.doc,r.to,1),n==null)return!1;return e&&e(t.tr.join(n).scrollIntoView()),!0},y6e=(t,e)=>{let{$from:r,$to:n}=t.selection,i=r.blockRange(n),o=i&&Gj(i);return o==null?!1:(e&&e(t.tr.lift(i,o).scrollIntoView()),!0)},Bge=(t,e)=>{let{$head:r,$anchor:n}=t.selection;return!r.parent.type.spec.code||!r.sameParent(n)?!1:(e&&e(t.tr.insertText(` `).scrollIntoView()),!0)};function Zq(t){for(let e=0;e{let{$head:r,$anchor:n}=t.selection;if(!r.parent.type.spec.code||!r.sameParent(n))return!1;let i=r.node(-1),o=r.indexAfter(-1),c=Zq(i.contentMatchAt(o));if(!c||!i.canReplaceWith(o,o,c))return!1;if(e){let a=r.after(),m=t.tr.replaceWith(a,a,c.createAndFill());m.setSelection(Pi.near(m.doc.resolve(a),1)),e(m.scrollIntoView())}return!0},$ge=(t,e)=>{let r=t.selection,{$from:n,$to:i}=r;if(r instanceof vd||n.parent.inlineContent||i.parent.inlineContent)return!1;let o=Zq(i.parent.contentMatchAt(i.indexAfter()));if(!o||!o.isTextblock)return!1;if(e){let c=(!n.parentOffset&&i.index(){let{$cursor:r}=t.selection;if(!r||r.parent.content.size)return!1;if(r.depth>1&&r.after()!=r.end(-1)){let o=r.before();if(Rm(t.doc,o))return e&&e(t.tr.split(o).scrollIntoView()),!0}let n=r.blockRange(),i=n&&Gj(n);return i==null?!1:(e&&e(t.tr.lift(n,i).scrollIntoView()),!0)};function v6e(t){return(e,r)=>{let{$from:n,$to:i}=e.selection;if(e.selection instanceof js&&e.selection.node.isBlock)return!n.parentOffset||!Rm(e.doc,n.pos)?!1:(r&&r(e.tr.split(n.pos).scrollIntoView()),!0);if(!n.depth)return!1;let o=[],c,a,m=!1,g=!1;for(let C=n.depth;;C--)if(n.node(C).isBlock){m=n.end(C)==n.pos+(n.depth-C),g=n.start(C)==n.pos-(n.depth-C),a=Zq(n.node(C-1).contentMatchAt(n.indexAfter(C-1))),o.unshift(m&&a?{type:a}:null),c=C;break}else{if(C==1)return!1;o.unshift(null)}let _=e.tr;(e.selection instanceof li||e.selection instanceof vd)&&_.deleteSelection();let j=_.mapping.map(n.pos),N=Rm(_.doc,j,o.length,o);if(N||(o[0]=a?{type:a}:null,N=Rm(_.doc,j,o.length,o)),!N)return!1;if(_.split(j,o.length,o),!m&&g&&n.node(c).type!=a){let C=_.mapping.map(n.before(c)),P=_.doc.resolve(C);a&&n.node(c-1).canReplaceWith(P.index(),P.index()+1,a)&&_.setNodeMarkup(_.mapping.map(n.before(c)),a)}return r&&r(_.scrollIntoView()),!0}}const _6e=v6e(),b6e=(t,e)=>{let{$from:r,to:n}=t.selection,i,o=r.sharedDepth(n);return o==0?!1:(i=r.before(o),e&&e(t.tr.setSelection(js.create(t.doc,i))),!0)};function w6e(t,e,r){let n=e.nodeBefore,i=e.nodeAfter,o=e.index();return!n||!i||!n.type.compatibleContent(i.type)?!1:!n.content.size&&e.parent.canReplace(o-1,o)?(r&&r(t.tr.delete(e.pos-n.nodeSize,e.pos).scrollIntoView()),!0):!e.parent.canReplace(o,o+1)||!(i.isTextblock||Sx(t.doc,e.pos))?!1:(r&&r(t.tr.join(e.pos).scrollIntoView()),!0)}function Vge(t,e,r,n){let i=e.nodeBefore,o=e.nodeAfter,c,a,m=i.type.spec.isolating||o.type.spec.isolating;if(!m&&w6e(t,e,r))return!0;let g=!m&&e.parent.canReplace(e.index(),e.index()+1);if(g&&(c=(a=i.contentMatchAt(i.childCount)).findWrapping(o.type))&&a.matchType(c[0]||o.type).validEnd){if(r){let C=e.pos+o.nodeSize,P=Qr.empty;for(let O=c.length-1;O>=0;O--)P=Qr.from(c[O].create(null,P));P=Qr.from(i.copy(P));let A=t.tr.step(new Kl(e.pos-1,C,e.pos,C,new Ln(P,1,0),c.length,!0)),I=A.doc.resolve(C+2*c.length);I.nodeAfter&&I.nodeAfter.type==i.type&&Sx(A.doc,I.pos)&&A.join(I.pos),r(A.scrollIntoView())}return!0}let _=o.type.spec.isolating||n>0&&m?null:Pi.findFrom(e,1),j=_&&_.$from.blockRange(_.$to),N=j&&Gj(j);if(N!=null&&N>=e.depth)return r&&r(t.tr.lift(j,N).scrollIntoView()),!0;if(g&&J1(o,"start",!0)&&J1(i,"end")){let C=i,P=[];for(;P.push(C),!C.isTextblock;)C=C.lastChild;let A=o,I=1;for(;!A.isTextblock;A=A.firstChild)I++;if(C.canReplace(C.childCount,C.childCount,A.content)){if(r){let O=Qr.empty;for(let z=P.length-1;z>=0;z--)O=Qr.from(P[z].copy(O));let R=t.tr.step(new Kl(e.pos-P.length,e.pos+o.nodeSize,e.pos+I,e.pos+o.nodeSize-I,new Ln(O,P.length,0),0,!0));r(R.scrollIntoView())}return!0}}return!1}function qge(t){return function(e,r){let n=e.selection,i=t<0?n.$from:n.$to,o=i.depth;for(;i.node(o).isInline;){if(!o)return!1;o--}return i.node(o).isTextblock?(r&&r(e.tr.setSelection(li.create(e.doc,t<0?i.start(o):i.end(o)))),!0):!1}}const j6e=qge(-1),S6e=qge(1);function N6e(t,e=null){return function(r,n){let{$from:i,$to:o}=r.selection,c=i.blockRange(o),a=c&&Rq(c,t,e);return a?(n&&n(r.tr.wrap(c,a).scrollIntoView()),!0):!1}}function mJ(t,e=null){return function(r,n){let i=!1;for(let o=0;o{if(i)return!1;if(!(!m.isTextblock||m.hasMarkup(t,e)))if(m.type==t)i=!0;else{let _=r.doc.resolve(g),j=_.index();i=_.parent.canReplaceWith(j,j+1,t)}})}if(!i)return!1;if(n){let o=r.tr;for(let c=0;c=2&&e.$from.node(e.depth-1).type.compatibleContent(r)&&e.startIndex==0){if(e.$from.index(e.depth-1)==0)return!1;let m=c.resolve(e.start-2);o=new QM(m,m,e.depth),e.endIndex=0;_--)o=Qr.from(r[_].type.create(r[_].attrs,o));t.step(new Kl(e.start-(n?2:0),e.end,e.start,e.end,new Ln(o,0,0),r.length,!0));let c=0;for(let _=0;_c.childCount>0&&c.firstChild.type==t);return o?r?n.node(o.depth-1).type==t?A6e(e,r,t,o):P6e(e,r,o):!0:!1}}function A6e(t,e,r,n){let i=t.tr,o=n.end,c=n.$to.end(n.depth);oA;P--)C-=i.child(P).nodeSize,n.delete(C-1,C+1);let o=n.doc.resolve(r.start),c=o.nodeAfter;if(n.mapping.map(r.end)!=r.start+o.nodeAfter.nodeSize)return!1;let a=r.startIndex==0,m=r.endIndex==i.childCount,g=o.node(-1),_=o.index(-1);if(!g.canReplace(_+(a?0:1),_+1,c.content.append(m?Qr.empty:Qr.from(i))))return!1;let j=o.pos,N=j+c.nodeSize;return n.step(new Kl(j-(a?1:0),N+(m?1:0),j+1,N-1,new Ln((a?Qr.empty:Qr.from(i.copy(Qr.empty))).append(m?Qr.empty:Qr.from(i.copy(Qr.empty))),a?0:1,m?0:1),a?0:1)),e(n.scrollIntoView()),!0}function I6e(t){return function(e,r){let{$from:n,$to:i}=e.selection,o=n.blockRange(i,g=>g.childCount>0&&g.firstChild.type==t);if(!o)return!1;let c=o.startIndex;if(c==0)return!1;let a=o.parent,m=a.child(c-1);if(m.type!=t)return!1;if(r){let g=m.lastChild&&m.lastChild.type==a.type,_=Qr.from(g?t.create():null),j=new Ln(Qr.from(t.create(null,Qr.from(a.type.create(null,_)))),g?3:1,0),N=o.start,C=o.end;r(e.tr.step(new Kl(N-(g?3:1),C,N,C,j,1,!0)).scrollIntoView())}return!0}}function eL(t){const{state:e,transaction:r}=t;let{selection:n}=r,{doc:i}=r,{storedMarks:o}=r;return{...e,apply:e.apply.bind(e),applyTransaction:e.applyTransaction.bind(e),plugins:e.plugins,schema:e.schema,reconfigure:e.reconfigure.bind(e),toJSON:e.toJSON.bind(e),get storedMarks(){return o},get selection(){return n},get doc(){return i},get tr(){return n=r.selection,i=r.doc,o=r.storedMarks,r}}}class tL{constructor(e){this.editor=e.editor,this.rawCommands=this.editor.extensionManager.commands,this.customState=e.state}get hasCustomState(){return!!this.customState}get state(){return this.customState||this.editor.state}get commands(){const{rawCommands:e,editor:r,state:n}=this,{view:i}=r,{tr:o}=n,c=this.buildProps(o);return Object.fromEntries(Object.entries(e).map(([a,m])=>[a,(..._)=>{const j=m(..._)(c);return!o.getMeta("preventDispatch")&&!this.hasCustomState&&i.dispatch(o),j}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(e,r=!0){const{rawCommands:n,editor:i,state:o}=this,{view:c}=i,a=[],m=!!e,g=e||o.tr,_=()=>(!m&&r&&!g.getMeta("preventDispatch")&&!this.hasCustomState&&c.dispatch(g),a.every(N=>N===!0)),j={...Object.fromEntries(Object.entries(n).map(([N,C])=>[N,(...A)=>{const I=this.buildProps(g,r),O=C(...A)(I);return a.push(O),j}])),run:_};return j}createCan(e){const{rawCommands:r,state:n}=this,i=!1,o=e||n.tr,c=this.buildProps(o,i);return{...Object.fromEntries(Object.entries(r).map(([m,g])=>[m,(..._)=>g(..._)({...c,dispatch:void 0})])),chain:()=>this.createChain(o,i)}}buildProps(e,r=!0){const{rawCommands:n,editor:i,state:o}=this,{view:c}=i,a={tr:e,editor:i,view:c,state:eL({state:o,transaction:e}),dispatch:r?()=>{}:void 0,chain:()=>this.createChain(e,r),can:()=>this.createCan(e),get commands(){return Object.fromEntries(Object.entries(n).map(([m,g])=>[m,(..._)=>g(..._)(a)]))}};return a}}let M6e=class{constructor(){this.callbacks={}}on(e,r){return this.callbacks[e]||(this.callbacks[e]=[]),this.callbacks[e].push(r),this}emit(e,...r){const n=this.callbacks[e];return n&&n.forEach(i=>i.apply(this,r)),this}off(e,r){const n=this.callbacks[e];return n&&(r?this.callbacks[e]=n.filter(i=>i!==r):delete this.callbacks[e]),this}once(e,r){const n=(...i)=>{this.off(e,n),r.apply(this,i)};return this.on(e,n)}removeAllListeners(){this.callbacks={}}};function Jn(t,e,r){return t.config[e]===void 0&&t.parent?Jn(t.parent,e,r):typeof t.config[e]=="function"?t.config[e].bind({...r,parent:t.parent?Jn(t.parent,e,r):null}):t.config[e]}function rL(t){const e=t.filter(i=>i.type==="extension"),r=t.filter(i=>i.type==="node"),n=t.filter(i=>i.type==="mark");return{baseExtensions:e,nodeExtensions:r,markExtensions:n}}function Hge(t){const e=[],{nodeExtensions:r,markExtensions:n}=rL(t),i=[...r,...n],o={default:null,rendered:!0,renderHTML:null,parseHTML:null,keepOnSplit:!0,isRequired:!1};return t.forEach(c=>{const a={name:c.name,options:c.options,storage:c.storage,extensions:i},m=Jn(c,"addGlobalAttributes",a);if(!m)return;m().forEach(_=>{_.types.forEach(j=>{Object.entries(_.attributes).forEach(([N,C])=>{e.push({type:j,name:N,attribute:{...o,...C}})})})})}),i.forEach(c=>{const a={name:c.name,options:c.options,storage:c.storage},m=Jn(c,"addAttributes",a);if(!m)return;const g=m();Object.entries(g).forEach(([_,j])=>{const N={...o,...j};typeof(N==null?void 0:N.default)=="function"&&(N.default=N.default()),N!=null&&N.isRequired&&(N==null?void 0:N.default)===void 0&&delete N.default,e.push({type:c.name,name:_,attribute:N})})}),e}function Xl(t,e){if(typeof t=="string"){if(!e.nodes[t])throw Error(`There is no node type named '${t}'. Maybe you forgot to add the extension?`);return e.nodes[t]}return t}function Ql(...t){return t.filter(e=>!!e).reduce((e,r)=>{const n={...e};return Object.entries(r).forEach(([i,o])=>{if(!n[i]){n[i]=o;return}if(i==="class"){const a=o?String(o).split(" "):[],m=n[i]?n[i].split(" "):[],g=a.filter(_=>!m.includes(_));n[i]=[...m,...g].join(" ")}else if(i==="style"){const a=o?o.split(";").map(_=>_.trim()).filter(Boolean):[],m=n[i]?n[i].split(";").map(_=>_.trim()).filter(Boolean):[],g=new Map;m.forEach(_=>{const[j,N]=_.split(":").map(C=>C.trim());g.set(j,N)}),a.forEach(_=>{const[j,N]=_.split(":").map(C=>C.trim());g.set(j,N)}),n[i]=Array.from(g.entries()).map(([_,j])=>`${_}: ${j}`).join("; ")}else n[i]=o}),n},{})}function rU(t,e){return e.filter(r=>r.type===t.type.name).filter(r=>r.attribute.rendered).map(r=>r.attribute.renderHTML?r.attribute.renderHTML(t.attrs)||{}:{[r.name]:t.attrs[r.name]}).reduce((r,n)=>Ql(r,n),{})}function Wge(t){return typeof t=="function"}function Oi(t,e=void 0,...r){return Wge(t)?e?t.bind(e)(...r):t(...r):t}function O6e(t={}){return Object.keys(t).length===0&&t.constructor===Object}function R6e(t){return typeof t!="string"?t:t.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(t):t==="true"?!0:t==="false"?!1:t}function gJ(t,e){return"style"in t?t:{...t,getAttrs:r=>{const n=t.getAttrs?t.getAttrs(r):t.attrs;if(n===!1)return!1;const i=e.reduce((o,c)=>{const a=c.attribute.parseHTML?c.attribute.parseHTML(r):R6e(r.getAttribute(c.name));return a==null?o:{...o,[c.name]:a}},{});return{...n,...i}}}}function yJ(t){return Object.fromEntries(Object.entries(t).filter(([e,r])=>e==="attrs"&&O6e(r)?!1:r!=null))}function D6e(t,e){var r;const n=Hge(t),{nodeExtensions:i,markExtensions:o}=rL(t),c=(r=i.find(g=>Jn(g,"topNode")))===null||r===void 0?void 0:r.name,a=Object.fromEntries(i.map(g=>{const _=n.filter(O=>O.type===g.name),j={name:g.name,options:g.options,storage:g.storage,editor:e},N=t.reduce((O,R)=>{const z=Jn(R,"extendNodeSchema",j);return{...O,...z?z(g):{}}},{}),C=yJ({...N,content:Oi(Jn(g,"content",j)),marks:Oi(Jn(g,"marks",j)),group:Oi(Jn(g,"group",j)),inline:Oi(Jn(g,"inline",j)),atom:Oi(Jn(g,"atom",j)),selectable:Oi(Jn(g,"selectable",j)),draggable:Oi(Jn(g,"draggable",j)),code:Oi(Jn(g,"code",j)),whitespace:Oi(Jn(g,"whitespace",j)),linebreakReplacement:Oi(Jn(g,"linebreakReplacement",j)),defining:Oi(Jn(g,"defining",j)),isolating:Oi(Jn(g,"isolating",j)),attrs:Object.fromEntries(_.map(O=>{var R;return[O.name,{default:(R=O==null?void 0:O.attribute)===null||R===void 0?void 0:R.default}]}))}),P=Oi(Jn(g,"parseHTML",j));P&&(C.parseDOM=P.map(O=>gJ(O,_)));const A=Jn(g,"renderHTML",j);A&&(C.toDOM=O=>A({node:O,HTMLAttributes:rU(O,_)}));const I=Jn(g,"renderText",j);return I&&(C.toText=I),[g.name,C]})),m=Object.fromEntries(o.map(g=>{const _=n.filter(I=>I.type===g.name),j={name:g.name,options:g.options,storage:g.storage,editor:e},N=t.reduce((I,O)=>{const R=Jn(O,"extendMarkSchema",j);return{...I,...R?R(g):{}}},{}),C=yJ({...N,inclusive:Oi(Jn(g,"inclusive",j)),excludes:Oi(Jn(g,"excludes",j)),group:Oi(Jn(g,"group",j)),spanning:Oi(Jn(g,"spanning",j)),code:Oi(Jn(g,"code",j)),attrs:Object.fromEntries(_.map(I=>{var O;return[I.name,{default:(O=I==null?void 0:I.attribute)===null||O===void 0?void 0:O.default}]}))}),P=Oi(Jn(g,"parseHTML",j));P&&(C.parseDOM=P.map(I=>gJ(I,_)));const A=Jn(g,"renderHTML",j);return A&&(C.toDOM=I=>A({mark:I,HTMLAttributes:rU(I,_)})),[g.name,C]}));return new Ime({topNode:c,nodes:a,marks:m})}function Iz(t,e){return e.nodes[t]||e.marks[t]||null}function xJ(t,e){return Array.isArray(e)?e.some(r=>(typeof r=="string"?r:r.name)===t.name):e}function Xq(t,e){const r=l0.fromSchema(e).serializeFragment(t),i=document.implementation.createHTMLDocument().createElement("div");return i.appendChild(r),i.innerHTML}const L6e=(t,e=500)=>{let r="";const n=t.parentOffset;return t.parent.nodesBetween(Math.max(0,n-e),n,(i,o,c,a)=>{var m,g;const _=((g=(m=i.type.spec).toText)===null||g===void 0?void 0:g.call(m,{node:i,pos:o,parent:c,index:a}))||i.textContent||"%leaf%";r+=i.isAtom&&!i.isText?_:_.slice(0,Math.max(0,n-o))}),r};function Qq(t){return Object.prototype.toString.call(t)==="[object RegExp]"}class nL{constructor(e){this.find=e.find,this.handler=e.handler}}const F6e=(t,e)=>{if(Qq(e))return e.exec(t);const r=e(t);if(!r)return null;const n=[r.text];return n.index=r.index,n.input=t,n.data=r.data,r.replaceWith&&(r.text.includes(r.replaceWith)||console.warn('[tiptap warn]: "inputRuleMatch.replaceWith" must be part of "inputRuleMatch.text".'),n.push(r.replaceWith)),n};function DP(t){var e;const{editor:r,from:n,to:i,text:o,rules:c,plugin:a}=t,{view:m}=r;if(m.composing)return!1;const g=m.state.doc.resolve(n);if(g.parent.type.spec.code||!((e=g.nodeBefore||g.nodeAfter)===null||e===void 0)&&e.marks.find(N=>N.type.spec.code))return!1;let _=!1;const j=L6e(g)+o;return c.forEach(N=>{if(_)return;const C=F6e(j,N.find);if(!C)return;const P=m.state.tr,A=eL({state:m.state,transaction:P}),I={from:n-(C[0].length-o.length),to:i},{commands:O,chain:R,can:z}=new tL({editor:r,state:A});N.handler({state:A,range:I,match:C,commands:O,chain:R,can:z})===null||!P.steps.length||(P.setMeta(a,{transform:P,from:n,to:i,text:o}),m.dispatch(P),_=!0)}),_}function z6e(t){const{editor:e,rules:r}=t,n=new wc({state:{init(){return null},apply(i,o,c){const a=i.getMeta(n);if(a)return a;const m=i.getMeta("applyInputRules");return!!m&&setTimeout(()=>{let{text:_}=m;typeof _=="string"?_=_:_=Xq(Qr.from(_),c.schema);const{from:j}=m,N=j+_.length;DP({editor:e,from:j,to:N,text:_,rules:r,plugin:n})}),i.selectionSet||i.docChanged?null:o}},props:{handleTextInput(i,o,c,a){return DP({editor:e,from:o,to:c,text:a,rules:r,plugin:n})},handleDOMEvents:{compositionend:i=>(setTimeout(()=>{const{$cursor:o}=i.state.selection;o&&DP({editor:e,from:o.pos,to:o.pos,text:"",rules:r,plugin:n})}),!1)},handleKeyDown(i,o){if(o.key!=="Enter")return!1;const{$cursor:c}=i.state.selection;return c?DP({editor:e,from:c.pos,to:c.pos,text:` `,rules:r,plugin:n}):!1}},isInputRules:!0});return n}function B6e(t){return Object.prototype.toString.call(t).slice(8,-1)}function LP(t){return B6e(t)!=="Object"?!1:t.constructor===Object&&Object.getPrototypeOf(t)===Object.prototype}function sL(t,e){const r={...t};return LP(t)&&LP(e)&&Object.keys(e).forEach(n=>{LP(e[n])&&LP(t[n])?r[n]=sL(t[n],e[n]):r[n]=e[n]}),r}class Ep{constructor(e={}){this.type="mark",this.name="mark",this.parent=null,this.child=null,this.config={name:this.name,defaultOptions:{}},this.config={...this.config,...e},this.name=this.config.name,e.defaultOptions&&Object.keys(e.defaultOptions).length>0&&console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${this.name}".`),this.options=this.config.defaultOptions,this.config.addOptions&&(this.options=Oi(Jn(this,"addOptions",{name:this.name}))),this.storage=Oi(Jn(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(e={}){return new Ep(e)}configure(e={}){const r=this.extend({...this.config,addOptions:()=>sL(this.options,e)});return r.name=this.name,r.parent=this.parent,r}extend(e={}){const r=new Ep(e);return r.parent=this,this.child=r,r.name=e.name?e.name:r.parent.name,e.defaultOptions&&Object.keys(e.defaultOptions).length>0&&console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${r.name}".`),r.options=Oi(Jn(r,"addOptions",{name:r.name})),r.storage=Oi(Jn(r,"addStorage",{name:r.name,options:r.options})),r}static handleExit({editor:e,mark:r}){const{tr:n}=e.state,i=e.state.selection.$from;if(i.pos===i.end()){const c=i.marks();if(!!!c.find(g=>(g==null?void 0:g.type.name)===r.name))return!1;const m=c.find(g=>(g==null?void 0:g.type.name)===r.name);return m&&n.removeStoredMark(m),n.insertText(" ",i.pos),e.view.dispatch(n),!0}return!1}}function $6e(t){return typeof t=="number"}class U6e{constructor(e){this.find=e.find,this.handler=e.handler}}const V6e=(t,e,r)=>{if(Qq(e))return[...t.matchAll(e)];const n=e(t,r);return n?n.map(i=>{const o=[i.text];return o.index=i.index,o.input=t,o.data=i.data,i.replaceWith&&(i.text.includes(i.replaceWith)||console.warn('[tiptap warn]: "pasteRuleMatch.replaceWith" must be part of "pasteRuleMatch.text".'),o.push(i.replaceWith)),o}):[]};function q6e(t){const{editor:e,state:r,from:n,to:i,rule:o,pasteEvent:c,dropEvent:a}=t,{commands:m,chain:g,can:_}=new tL({editor:e,state:r}),j=[];return r.doc.nodesBetween(n,i,(C,P)=>{if(!C.isTextblock||C.type.spec.code)return;const A=Math.max(n,P),I=Math.min(i,P+C.content.size),O=C.textBetween(A-P,I-P,void 0,"");V6e(O,o.find,c).forEach(z=>{if(z.index===void 0)return;const W=A+z.index+1,V=W+z[0].length,K={from:r.tr.mapping.map(W),to:r.tr.mapping.map(V)},Q=o.handler({state:r,range:K,match:z,commands:m,chain:g,can:_,pasteEvent:c,dropEvent:a});j.push(Q)})}),j.every(C=>C!==null)}let FP=null;const H6e=t=>{var e;const r=new ClipboardEvent("paste",{clipboardData:new DataTransfer});return(e=r.clipboardData)===null||e===void 0||e.setData("text/html",t),r};function W6e(t){const{editor:e,rules:r}=t;let n=null,i=!1,o=!1,c=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,a;try{a=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{a=null}const m=({state:_,from:j,to:N,rule:C,pasteEvt:P})=>{const A=_.tr,I=eL({state:_,transaction:A});if(!(!q6e({editor:e,state:I,from:Math.max(j-1,0),to:N.b-1,rule:C,pasteEvent:P,dropEvent:a})||!A.steps.length)){try{a=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{a=null}return c=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,A}};return r.map(_=>new wc({view(j){const N=P=>{var A;n=!((A=j.dom.parentElement)===null||A===void 0)&&A.contains(P.target)?j.dom.parentElement:null,n&&(FP=e)},C=()=>{FP&&(FP=null)};return window.addEventListener("dragstart",N),window.addEventListener("dragend",C),{destroy(){window.removeEventListener("dragstart",N),window.removeEventListener("dragend",C)}}},props:{handleDOMEvents:{drop:(j,N)=>{if(o=n===j.dom.parentElement,a=N,!o){const C=FP;C!=null&&C.isEditable&&setTimeout(()=>{const P=C.state.selection;P&&C.commands.deleteRange({from:P.from,to:P.to})},10)}return!1},paste:(j,N)=>{var C;const P=(C=N.clipboardData)===null||C===void 0?void 0:C.getData("text/html");return c=N,i=!!(P!=null&&P.includes("data-pm-slice")),!1}}},appendTransaction:(j,N,C)=>{const P=j[0],A=P.getMeta("uiEvent")==="paste"&&!i,I=P.getMeta("uiEvent")==="drop"&&!o,O=P.getMeta("applyPasteRules"),R=!!O;if(!A&&!I&&!R)return;if(R){let{text:V}=O;typeof V=="string"?V=V:V=Xq(Qr.from(V),C.schema);const{from:K}=O,Q=K+V.length,te=H6e(V);return m({rule:_,state:C,from:K,to:{b:Q},pasteEvt:te})}const z=N.doc.content.findDiffStart(C.doc.content),W=N.doc.content.findDiffEnd(C.doc.content);if(!(!$6e(z)||!W||z===W.b))return m({rule:_,state:C,from:z,to:W,pasteEvt:c})}}))}function G6e(t){const e=t.filter((r,n)=>t.indexOf(r)!==n);return Array.from(new Set(e))}class Bw{constructor(e,r){this.splittableMarks=[],this.editor=r,this.extensions=Bw.resolve(e),this.schema=D6e(this.extensions,r),this.setupExtensions()}static resolve(e){const r=Bw.sort(Bw.flatten(e)),n=G6e(r.map(i=>i.name));return n.length&&console.warn(`[tiptap warn]: Duplicate extension names found: [${n.map(i=>`'${i}'`).join(", ")}]. This can lead to issues.`),r}static flatten(e){return e.map(r=>{const n={name:r.name,options:r.options,storage:r.storage},i=Jn(r,"addExtensions",n);return i?[r,...this.flatten(i())]:r}).flat(10)}static sort(e){return e.sort((n,i)=>{const o=Jn(n,"priority")||100,c=Jn(i,"priority")||100;return o>c?-1:o{const n={name:r.name,options:r.options,storage:r.storage,editor:this.editor,type:Iz(r.name,this.schema)},i=Jn(r,"addCommands",n);return i?{...e,...i()}:e},{})}get plugins(){const{editor:e}=this,r=Bw.sort([...this.extensions].reverse()),n=[],i=[],o=r.map(c=>{const a={name:c.name,options:c.options,storage:c.storage,editor:e,type:Iz(c.name,this.schema)},m=[],g=Jn(c,"addKeyboardShortcuts",a);let _={};if(c.type==="mark"&&Jn(c,"exitable",a)&&(_.ArrowRight=()=>Ep.handleExit({editor:e,mark:c})),g){const A=Object.fromEntries(Object.entries(g()).map(([I,O])=>[I,()=>O({editor:e})]));_={..._,...A}}const j=h6e(_);m.push(j);const N=Jn(c,"addInputRules",a);xJ(c,e.options.enableInputRules)&&N&&n.push(...N());const C=Jn(c,"addPasteRules",a);xJ(c,e.options.enablePasteRules)&&C&&i.push(...C());const P=Jn(c,"addProseMirrorPlugins",a);if(P){const A=P();m.push(...A)}return m}).flat();return[z6e({editor:e,rules:n}),...W6e({editor:e,rules:i}),...o]}get attributes(){return Hge(this.extensions)}get nodeViews(){const{editor:e}=this,{nodeExtensions:r}=rL(this.extensions);return Object.fromEntries(r.filter(n=>!!Jn(n,"addNodeView")).map(n=>{const i=this.attributes.filter(m=>m.type===n.name),o={name:n.name,options:n.options,storage:n.storage,editor:e,type:Xl(n.name,this.schema)},c=Jn(n,"addNodeView",o);if(!c)return[];const a=(m,g,_,j,N)=>{const C=rU(m,i);return c()({node:m,view:g,getPos:_,decorations:j,innerDecorations:N,editor:e,extension:n,HTMLAttributes:C})};return[n.name,a]}))}setupExtensions(){this.extensions.forEach(e=>{var r;this.editor.extensionStorage[e.name]=e.storage;const n={name:e.name,options:e.options,storage:e.storage,editor:this.editor,type:Iz(e.name,this.schema)};e.type==="mark"&&(!((r=Oi(Jn(e,"keepOnSplit",n)))!==null&&r!==void 0)||r)&&this.splittableMarks.push(e.name);const i=Jn(e,"onBeforeCreate",n),o=Jn(e,"onCreate",n),c=Jn(e,"onUpdate",n),a=Jn(e,"onSelectionUpdate",n),m=Jn(e,"onTransaction",n),g=Jn(e,"onFocus",n),_=Jn(e,"onBlur",n),j=Jn(e,"onDestroy",n);i&&this.editor.on("beforeCreate",i),o&&this.editor.on("create",o),c&&this.editor.on("update",c),a&&this.editor.on("selectionUpdate",a),m&&this.editor.on("transaction",m),g&&this.editor.on("focus",g),_&&this.editor.on("blur",_),j&&this.editor.on("destroy",j)})}}class bc{constructor(e={}){this.type="extension",this.name="extension",this.parent=null,this.child=null,this.config={name:this.name,defaultOptions:{}},this.config={...this.config,...e},this.name=this.config.name,e.defaultOptions&&Object.keys(e.defaultOptions).length>0&&console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${this.name}".`),this.options=this.config.defaultOptions,this.config.addOptions&&(this.options=Oi(Jn(this,"addOptions",{name:this.name}))),this.storage=Oi(Jn(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(e={}){return new bc(e)}configure(e={}){const r=this.extend({...this.config,addOptions:()=>sL(this.options,e)});return r.name=this.name,r.parent=this.parent,r}extend(e={}){const r=new bc({...this.config,...e});return r.parent=this,this.child=r,r.name=e.name?e.name:r.parent.name,e.defaultOptions&&Object.keys(e.defaultOptions).length>0&&console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${r.name}".`),r.options=Oi(Jn(r,"addOptions",{name:r.name})),r.storage=Oi(Jn(r,"addStorage",{name:r.name,options:r.options})),r}}function Gge(t,e,r){const{from:n,to:i}=e,{blockSeparator:o=` `,textSerializers:c={}}=r||{};let a="";return t.nodesBetween(n,i,(m,g,_,j)=>{var N;m.isBlock&&g>n&&(a+=o);const C=c==null?void 0:c[m.type.name];if(C)return _&&(a+=C({node:m,pos:g,parent:_,index:j,range:e})),!1;m.isText&&(a+=(N=m==null?void 0:m.text)===null||N===void 0?void 0:N.slice(Math.max(n,g)-g,i-g))}),a}function Kge(t){return Object.fromEntries(Object.entries(t.nodes).filter(([,e])=>e.spec.toText).map(([e,r])=>[e,r.spec.toText]))}const K6e=bc.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new wc({key:new kd("clipboardTextSerializer"),props:{clipboardTextSerializer:()=>{const{editor:t}=this,{state:e,schema:r}=t,{doc:n,selection:i}=e,{ranges:o}=i,c=Math.min(...o.map(_=>_.$from.pos)),a=Math.max(...o.map(_=>_.$to.pos)),m=Kge(r);return Gge(n,{from:c,to:a},{...this.options.blockSeparator!==void 0?{blockSeparator:this.options.blockSeparator}:{},textSerializers:m})}}})]}}),Z6e=()=>({editor:t,view:e})=>(requestAnimationFrame(()=>{var r;t.isDestroyed||(e.dom.blur(),(r=window==null?void 0:window.getSelection())===null||r===void 0||r.removeAllRanges())}),!0),Y6e=(t=!1)=>({commands:e})=>e.setContent("",t),X6e=()=>({state:t,tr:e,dispatch:r})=>{const{selection:n}=e,{ranges:i}=n;return r&&i.forEach(({$from:o,$to:c})=>{t.doc.nodesBetween(o.pos,c.pos,(a,m)=>{if(a.type.isText)return;const{doc:g,mapping:_}=e,j=g.resolve(_.map(m)),N=g.resolve(_.map(m+a.nodeSize)),C=j.blockRange(N);if(!C)return;const P=Gj(C);if(a.type.isTextblock){const{defaultType:A}=j.parent.contentMatchAt(j.index());e.setNodeMarkup(C.start,A)}(P||P===0)&&e.lift(C,P)})}),!0},Q6e=t=>e=>t(e),J6e=()=>({state:t,dispatch:e})=>$ge(t,e),e8e=(t,e)=>({editor:r,tr:n})=>{const{state:i}=r,o=i.doc.slice(t.from,t.to);n.deleteRange(t.from,t.to);const c=n.mapping.map(e);return n.insert(c,o.content),n.setSelection(new li(n.doc.resolve(Math.max(c-1,0)))),!0},t8e=()=>({tr:t,dispatch:e})=>{const{selection:r}=t,n=r.$anchor.node();if(n.content.size>0)return!1;const i=t.selection.$anchor;for(let o=i.depth;o>0;o-=1)if(i.node(o).type===n.type){if(e){const a=i.before(o),m=i.after(o);t.delete(a,m).scrollIntoView()}return!0}return!1},r8e=t=>({tr:e,state:r,dispatch:n})=>{const i=Xl(t,r.schema),o=e.selection.$anchor;for(let c=o.depth;c>0;c-=1)if(o.node(c).type===i){if(n){const m=o.before(c),g=o.after(c);e.delete(m,g).scrollIntoView()}return!0}return!1},n8e=t=>({tr:e,dispatch:r})=>{const{from:n,to:i}=t;return r&&e.delete(n,i),!0},s8e=()=>({state:t,dispatch:e})=>Wq(t,e),i8e=()=>({commands:t})=>t.keyboardShortcut("Enter"),a8e=()=>({state:t,dispatch:e})=>x6e(t,e);function aO(t,e,r={strict:!0}){const n=Object.keys(e);return n.length?n.every(i=>r.strict?e[i]===t[i]:Qq(e[i])?e[i].test(t[i]):e[i]===t[i]):!0}function Zge(t,e,r={}){return t.find(n=>n.type===e&&aO(Object.fromEntries(Object.keys(r).map(i=>[i,n.attrs[i]])),r))}function vJ(t,e,r={}){return!!Zge(t,e,r)}function Jq(t,e,r){var n;if(!t||!e)return;let i=t.parent.childAfter(t.parentOffset);if((!i.node||!i.node.marks.some(_=>_.type===e))&&(i=t.parent.childBefore(t.parentOffset)),!i.node||!i.node.marks.some(_=>_.type===e)||(r=r||((n=i.node.marks[0])===null||n===void 0?void 0:n.attrs),!Zge([...i.node.marks],e,r)))return;let c=i.index,a=t.start()+i.offset,m=c+1,g=a+i.node.nodeSize;for(;c>0&&vJ([...t.parent.child(c-1).marks],e,r);)c-=1,a-=t.parent.child(c).nodeSize;for(;m({tr:r,state:n,dispatch:i})=>{const o=Cx(t,n.schema),{doc:c,selection:a}=r,{$from:m,from:g,to:_}=a;if(i){const j=Jq(m,o,e);if(j&&j.from<=g&&j.to>=_){const N=li.create(c,j.from,j.to);r.setSelection(N)}}return!0},l8e=t=>e=>{const r=typeof t=="function"?t(e):t;for(let n=0;n({editor:r,view:n,tr:i,dispatch:o})=>{e={scrollIntoView:!0,...e};const c=()=>{(eH()||c8e())&&n.dom.focus(),requestAnimationFrame(()=>{r.isDestroyed||(n.focus(),e!=null&&e.scrollIntoView&&r.commands.scrollIntoView())})};if(n.hasFocus()&&t===null||t===!1)return!0;if(o&&t===null&&!Yge(r.state.selection))return c(),!0;const a=Xge(i.doc,t)||r.state.selection,m=r.state.selection.eq(a);return o&&(m||i.setSelection(a),m&&i.storedMarks&&i.setStoredMarks(i.storedMarks),c()),!0},d8e=(t,e)=>r=>t.every((n,i)=>e(n,{...r,index:i})),h8e=(t,e)=>({tr:r,commands:n})=>n.insertContentAt({from:r.selection.from,to:r.selection.to},t,e),Qge=t=>{const e=t.childNodes;for(let r=e.length-1;r>=0;r-=1){const n=e[r];n.nodeType===3&&n.nodeValue&&/^(\n\s\s|\n)$/.test(n.nodeValue)?t.removeChild(n):n.nodeType===1&&Qge(n)}return t};function zP(t){const e=`${t}`,r=new window.DOMParser().parseFromString(e,"text/html").body;return Qge(r)}function yk(t,e,r){if(t instanceof Zy||t instanceof Qr)return t;r={slice:!0,parseOptions:{},...r};const n=typeof t=="object"&&t!==null,i=typeof t=="string";if(n)try{if(Array.isArray(t)&&t.length>0)return Qr.fromArray(t.map(a=>e.nodeFromJSON(a)));const c=e.nodeFromJSON(t);return r.errorOnInvalidContent&&c.check(),c}catch(o){if(r.errorOnInvalidContent)throw new Error("[tiptap error]: Invalid JSON content",{cause:o});return console.warn("[tiptap warn]: Invalid content.","Passed value:",t,"Error:",o),yk("",e,r)}if(i){if(r.errorOnInvalidContent){let c=!1,a="";const m=new Ime({topNode:e.spec.topNode,marks:e.spec.marks,nodes:e.spec.nodes.append({__tiptap__private__unknown__catch__all__node:{content:"inline*",group:"block",parseDOM:[{tag:"*",getAttrs:g=>(c=!0,a=typeof g=="string"?g:g.outerHTML,null)}]}})});if(r.slice?h2.fromSchema(m).parseSlice(zP(t),r.parseOptions):h2.fromSchema(m).parse(zP(t),r.parseOptions),r.errorOnInvalidContent&&c)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${a}`)})}const o=h2.fromSchema(e);return r.slice?o.parseSlice(zP(t),r.parseOptions).content:o.parse(zP(t),r.parseOptions)}return yk("",e,r)}function f8e(t,e,r){const n=t.steps.length-1;if(n{c===0&&(c=_)}),t.setSelection(Pi.near(t.doc.resolve(c),r))}const p8e=t=>!("type"in t),m8e=(t,e,r)=>({tr:n,dispatch:i,editor:o})=>{var c;if(i){r={parseOptions:o.options.parseOptions,updateSelection:!0,applyInputRules:!1,applyPasteRules:!1,...r};let a;const m=I=>{o.emit("contentError",{editor:o,error:I,disableCollaboration:()=>{o.storage.collaboration&&(o.storage.collaboration.isDisabled=!0)}})},g={preserveWhitespace:"full",...r.parseOptions};if(!r.errorOnInvalidContent&&!o.options.enableContentCheck&&o.options.emitContentError)try{yk(e,o.schema,{parseOptions:g,errorOnInvalidContent:!0})}catch(I){m(I)}try{a=yk(e,o.schema,{parseOptions:g,errorOnInvalidContent:(c=r.errorOnInvalidContent)!==null&&c!==void 0?c:o.options.enableContentCheck})}catch(I){return m(I),!1}let{from:_,to:j}=typeof t=="number"?{from:t,to:t}:{from:t.from,to:t.to},N=!0,C=!0;if((p8e(a)?a:[a]).forEach(I=>{I.check(),N=N?I.isText&&I.marks.length===0:!1,C=C?I.isBlock:!1}),_===j&&C){const{parent:I}=n.doc.resolve(_);I.isTextblock&&!I.type.spec.code&&!I.childCount&&(_-=1,j+=1)}let A;if(N){if(Array.isArray(e))A=e.map(I=>I.text||"").join("");else if(e instanceof Qr){let I="";e.forEach(O=>{O.text&&(I+=O.text)}),A=I}else typeof e=="object"&&e&&e.text?A=e.text:A=e;n.insertText(A,_,j)}else A=a,n.replaceWith(_,j,A);r.updateSelection&&f8e(n,n.steps.length-1,-1),r.applyInputRules&&n.setMeta("applyInputRules",{from:_,text:A}),r.applyPasteRules&&n.setMeta("applyPasteRules",{from:_,text:A})}return!0},g8e=()=>({state:t,dispatch:e})=>m6e(t,e),y8e=()=>({state:t,dispatch:e})=>g6e(t,e),x8e=()=>({state:t,dispatch:e})=>Oge(t,e),v8e=()=>({state:t,dispatch:e})=>Fge(t,e),_8e=()=>({state:t,dispatch:e,tr:r})=>{try{const n=KD(t.doc,t.selection.$from.pos,-1);return n==null?!1:(r.join(n,2),e&&e(r),!0)}catch{return!1}},b8e=()=>({state:t,dispatch:e,tr:r})=>{try{const n=KD(t.doc,t.selection.$from.pos,1);return n==null?!1:(r.join(n,2),e&&e(r),!0)}catch{return!1}},w8e=()=>({state:t,dispatch:e})=>f6e(t,e),j8e=()=>({state:t,dispatch:e})=>p6e(t,e);function Jge(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function S8e(t){const e=t.split(/-(?!$)/);let r=e[e.length-1];r==="Space"&&(r=" ");let n,i,o,c;for(let a=0;a({editor:e,view:r,tr:n,dispatch:i})=>{const o=S8e(t).split(/-(?!$)/),c=o.find(g=>!["Alt","Ctrl","Meta","Shift"].includes(g)),a=new KeyboardEvent("keydown",{key:c==="Space"?" ":c,altKey:o.includes("Alt"),ctrlKey:o.includes("Ctrl"),metaKey:o.includes("Meta"),shiftKey:o.includes("Shift"),bubbles:!0,cancelable:!0}),m=e.captureTransaction(()=>{r.someProp("handleKeyDown",g=>g(r,a))});return m==null||m.steps.forEach(g=>{const _=g.map(n.mapping);_&&i&&n.maybeStep(_)}),!0};function xk(t,e,r={}){const{from:n,to:i,empty:o}=t.selection,c=e?Xl(e,t.schema):null,a=[];t.doc.nodesBetween(n,i,(j,N)=>{if(j.isText)return;const C=Math.max(n,N),P=Math.min(i,N+j.nodeSize);a.push({node:j,from:C,to:P})});const m=i-n,g=a.filter(j=>c?c.name===j.node.type.name:!0).filter(j=>aO(j.node.attrs,r,{strict:!1}));return o?!!g.length:g.reduce((j,N)=>j+N.to-N.from,0)>=m}const C8e=(t,e={})=>({state:r,dispatch:n})=>{const i=Xl(t,r.schema);return xk(r,i,e)?y6e(r,n):!1},k8e=()=>({state:t,dispatch:e})=>Uge(t,e),T8e=t=>({state:e,dispatch:r})=>{const n=Xl(t,e.schema);return E6e(n)(e,r)},E8e=()=>({state:t,dispatch:e})=>Bge(t,e);function iL(t,e){return e.nodes[t]?"node":e.marks[t]?"mark":null}function _J(t,e){const r=typeof e=="string"?[e]:e;return Object.keys(t).reduce((n,i)=>(r.includes(i)||(n[i]=t[i]),n),{})}const A8e=(t,e)=>({tr:r,state:n,dispatch:i})=>{let o=null,c=null;const a=iL(typeof t=="string"?t:t.name,n.schema);return a?(a==="node"&&(o=Xl(t,n.schema)),a==="mark"&&(c=Cx(t,n.schema)),i&&r.selection.ranges.forEach(m=>{n.doc.nodesBetween(m.$from.pos,m.$to.pos,(g,_)=>{o&&o===g.type&&r.setNodeMarkup(_,void 0,_J(g.attrs,e)),c&&g.marks.length&&g.marks.forEach(j=>{c===j.type&&r.addMark(_,_+g.nodeSize,c.create(_J(j.attrs,e)))})})}),!0):!1},P8e=()=>({tr:t,dispatch:e})=>(e&&t.scrollIntoView(),!0),I8e=()=>({tr:t,dispatch:e})=>{if(e){const r=new vd(t.doc);t.setSelection(r)}return!0},M8e=()=>({state:t,dispatch:e})=>Dge(t,e),O8e=()=>({state:t,dispatch:e})=>zge(t,e),R8e=()=>({state:t,dispatch:e})=>b6e(t,e),D8e=()=>({state:t,dispatch:e})=>S6e(t,e),L8e=()=>({state:t,dispatch:e})=>j6e(t,e);function nU(t,e,r={},n={}){return yk(t,e,{slice:!1,parseOptions:r,errorOnInvalidContent:n.errorOnInvalidContent})}const F8e=(t,e=!1,r={},n={})=>({editor:i,tr:o,dispatch:c,commands:a})=>{var m,g;const{doc:_}=o;if(r.preserveWhitespace!=="full"){const j=nU(t,i.schema,r,{errorOnInvalidContent:(m=n.errorOnInvalidContent)!==null&&m!==void 0?m:i.options.enableContentCheck});return c&&o.replaceWith(0,_.content.size,j).setMeta("preventUpdate",!e),!0}return c&&o.setMeta("preventUpdate",!e),a.insertContentAt({from:0,to:_.content.size},t,{parseOptions:r,errorOnInvalidContent:(g=n.errorOnInvalidContent)!==null&&g!==void 0?g:i.options.enableContentCheck})};function eye(t,e){const r=Cx(e,t.schema),{from:n,to:i,empty:o}=t.selection,c=[];o?(t.storedMarks&&c.push(...t.storedMarks),c.push(...t.selection.$head.marks())):t.doc.nodesBetween(n,i,m=>{c.push(...m.marks)});const a=c.find(m=>m.type.name===r.name);return a?{...a.attrs}:{}}function z8e(t,e){const r=new Kme(t);return e.forEach(n=>{n.steps.forEach(i=>{r.step(i)})}),r}function B8e(t){for(let e=0;e{r(i)&&n.push({node:i,pos:o})}),n}function U8e(t,e){for(let r=t.depth;r>0;r-=1){const n=t.node(r);if(e(n))return{pos:r>0?t.before(r):0,start:t.start(r),depth:r,node:n}}}function tH(t){return e=>U8e(e.$from,t)}function V8e(t,e){const r={from:0,to:t.content.size};return Gge(t,r,e)}function q8e(t,e){const r=Xl(e,t.schema),{from:n,to:i}=t.selection,o=[];t.doc.nodesBetween(n,i,a=>{o.push(a)});const c=o.reverse().find(a=>a.type.name===r.name);return c?{...c.attrs}:{}}function tye(t,e){const r=iL(typeof e=="string"?e:e.name,t.schema);return r==="node"?q8e(t,e):r==="mark"?eye(t,e):{}}function H8e(t,e=JSON.stringify){const r={};return t.filter(n=>{const i=e(n);return Object.prototype.hasOwnProperty.call(r,i)?!1:r[i]=!0})}function W8e(t){const e=H8e(t);return e.length===1?e:e.filter((r,n)=>!e.filter((o,c)=>c!==n).some(o=>r.oldRange.from>=o.oldRange.from&&r.oldRange.to<=o.oldRange.to&&r.newRange.from>=o.newRange.from&&r.newRange.to<=o.newRange.to))}function G8e(t){const{mapping:e,steps:r}=t,n=[];return e.maps.forEach((i,o)=>{const c=[];if(i.ranges.length)i.forEach((a,m)=>{c.push({from:a,to:m})});else{const{from:a,to:m}=r[o];if(a===void 0||m===void 0)return;c.push({from:a,to:m})}c.forEach(({from:a,to:m})=>{const g=e.slice(o).map(a,-1),_=e.slice(o).map(m),j=e.invert().map(g,-1),N=e.invert().map(_);n.push({oldRange:{from:j,to:N},newRange:{from:g,to:_}})})}),W8e(n)}function rH(t,e,r){const n=[];return t===e?r.resolve(t).marks().forEach(i=>{const o=r.resolve(t),c=Jq(o,i.type);c&&n.push({mark:i,...c})}):r.nodesBetween(t,e,(i,o)=>{!i||(i==null?void 0:i.nodeSize)===void 0||n.push(...i.marks.map(c=>({from:o,to:o+i.nodeSize,mark:c})))}),n}function RI(t,e,r){return Object.fromEntries(Object.entries(r).filter(([n])=>{const i=t.find(o=>o.type===e&&o.name===n);return i?i.attribute.keepOnSplit:!1}))}function sU(t,e,r={}){const{empty:n,ranges:i}=t.selection,o=e?Cx(e,t.schema):null;if(n)return!!(t.storedMarks||t.selection.$from.marks()).filter(j=>o?o.name===j.type.name:!0).find(j=>aO(j.attrs,r,{strict:!1}));let c=0;const a=[];if(i.forEach(({$from:j,$to:N})=>{const C=j.pos,P=N.pos;t.doc.nodesBetween(C,P,(A,I)=>{if(!A.isText&&!A.marks.length)return;const O=Math.max(C,I),R=Math.min(P,I+A.nodeSize),z=R-O;c+=z,a.push(...A.marks.map(W=>({mark:W,from:O,to:R})))})}),c===0)return!1;const m=a.filter(j=>o?o.name===j.mark.type.name:!0).filter(j=>aO(j.mark.attrs,r,{strict:!1})).reduce((j,N)=>j+N.to-N.from,0),g=a.filter(j=>o?j.mark.type!==o&&j.mark.type.excludes(o):!0).reduce((j,N)=>j+N.to-N.from,0);return(m>0?m+g:m)>=c}function K8e(t,e,r={}){if(!e)return xk(t,null,r)||sU(t,null,r);const n=iL(e,t.schema);return n==="node"?xk(t,e,r):n==="mark"?sU(t,e,r):!1}function bJ(t,e){const{nodeExtensions:r}=rL(e),n=r.find(c=>c.name===t);if(!n)return!1;const i={name:n.name,options:n.options,storage:n.storage},o=Oi(Jn(n,"group",i));return typeof o!="string"?!1:o.split(" ").includes("list")}function nH(t,{checkChildren:e=!0,ignoreWhitespace:r=!1}={}){var n;if(r){if(t.type.name==="hardBreak")return!0;if(t.isText)return/^\s*$/m.test((n=t.text)!==null&&n!==void 0?n:"")}if(t.isText)return!t.text;if(t.isAtom||t.isLeaf)return!1;if(t.content.childCount===0)return!0;if(e){let i=!0;return t.content.forEach(o=>{i!==!1&&(nH(o,{ignoreWhitespace:r,checkChildren:e})||(i=!1))}),i}return!1}function Z8e(t){return t instanceof js}function Y8e(t,e,r){var n;const{selection:i}=e;let o=null;if(Yge(i)&&(o=i.$cursor),o){const a=(n=t.storedMarks)!==null&&n!==void 0?n:o.marks();return!!r.isInSet(a)||!a.some(m=>m.type.excludes(r))}const{ranges:c}=i;return c.some(({$from:a,$to:m})=>{let g=a.depth===0?t.doc.inlineContent&&t.doc.type.allowsMarkType(r):!1;return t.doc.nodesBetween(a.pos,m.pos,(_,j,N)=>{if(g)return!1;if(_.isInline){const C=!N||N.type.allowsMarkType(r),P=!!r.isInSet(_.marks)||!_.marks.some(A=>A.type.excludes(r));g=C&&P}return!g}),g})}const X8e=(t,e={})=>({tr:r,state:n,dispatch:i})=>{const{selection:o}=r,{empty:c,ranges:a}=o,m=Cx(t,n.schema);if(i)if(c){const g=eye(n,m);r.addStoredMark(m.create({...g,...e}))}else a.forEach(g=>{const _=g.$from.pos,j=g.$to.pos;n.doc.nodesBetween(_,j,(N,C)=>{const P=Math.max(C,_),A=Math.min(C+N.nodeSize,j);N.marks.find(O=>O.type===m)?N.marks.forEach(O=>{m===O.type&&r.addMark(P,A,m.create({...O.attrs,...e}))}):r.addMark(P,A,m.create(e))})});return Y8e(n,r,m)},Q8e=(t,e)=>({tr:r})=>(r.setMeta(t,e),!0),J8e=(t,e={})=>({state:r,dispatch:n,chain:i})=>{const o=Xl(t,r.schema);let c;return r.selection.$anchor.sameParent(r.selection.$head)&&(c=r.selection.$anchor.parent.attrs),o.isTextblock?i().command(({commands:a})=>mJ(o,{...c,...e})(r)?!0:a.clearNodes()).command(({state:a})=>mJ(o,{...c,...e})(a,n)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},eqe=t=>({tr:e,dispatch:r})=>{if(r){const{doc:n}=e,i=Qv(t,0,n.content.size),o=js.create(n,i);e.setSelection(o)}return!0},tqe=t=>({tr:e,dispatch:r})=>{if(r){const{doc:n}=e,{from:i,to:o}=typeof t=="number"?{from:t,to:t}:t,c=li.atStart(n).from,a=li.atEnd(n).to,m=Qv(i,c,a),g=Qv(o,c,a),_=li.create(n,m,g);e.setSelection(_)}return!0},rqe=t=>({state:e,dispatch:r})=>{const n=Xl(t,e.schema);return I6e(n)(e,r)};function wJ(t,e){const r=t.storedMarks||t.selection.$to.parentOffset&&t.selection.$from.marks();if(r){const n=r.filter(i=>e==null?void 0:e.includes(i.type.name));t.tr.ensureMarks(n)}}const nqe=({keepMarks:t=!0}={})=>({tr:e,state:r,dispatch:n,editor:i})=>{const{selection:o,doc:c}=e,{$from:a,$to:m}=o,g=i.extensionManager.attributes,_=RI(g,a.node().type.name,a.node().attrs);if(o instanceof js&&o.node.isBlock)return!a.parentOffset||!Rm(c,a.pos)?!1:(n&&(t&&wJ(r,i.extensionManager.splittableMarks),e.split(a.pos).scrollIntoView()),!0);if(!a.parent.isBlock)return!1;const j=m.parentOffset===m.parent.content.size,N=a.depth===0?void 0:B8e(a.node(-1).contentMatchAt(a.indexAfter(-1)));let C=j&&N?[{type:N,attrs:_}]:void 0,P=Rm(e.doc,e.mapping.map(a.pos),1,C);if(!C&&!P&&Rm(e.doc,e.mapping.map(a.pos),1,N?[{type:N}]:void 0)&&(P=!0,C=N?[{type:N,attrs:_}]:void 0),n){if(P&&(o instanceof li&&e.deleteSelection(),e.split(e.mapping.map(a.pos),1,C),N&&!j&&!a.parentOffset&&a.parent.type!==N)){const A=e.mapping.map(a.before()),I=e.doc.resolve(A);a.node(-1).canReplaceWith(I.index(),I.index()+1,N)&&e.setNodeMarkup(e.mapping.map(a.before()),N)}t&&wJ(r,i.extensionManager.splittableMarks),e.scrollIntoView()}return P},sqe=(t,e={})=>({tr:r,state:n,dispatch:i,editor:o})=>{var c;const a=Xl(t,n.schema),{$from:m,$to:g}=n.selection,_=n.selection.node;if(_&&_.isBlock||m.depth<2||!m.sameParent(g))return!1;const j=m.node(-1);if(j.type!==a)return!1;const N=o.extensionManager.attributes;if(m.parent.content.size===0&&m.node(-1).childCount===m.indexAfter(-1)){if(m.depth===2||m.node(-3).type!==a||m.index(-2)!==m.node(-2).childCount-1)return!1;if(i){let O=Qr.empty;const R=m.index(-1)?1:m.index(-2)?2:3;for(let te=m.depth-R;te>=m.depth-3;te-=1)O=Qr.from(m.node(te).copy(O));const z=m.indexAfter(-1){if(Q>-1)return!1;te.isTextblock&&te.content.size===0&&(Q=X+1)}),Q>-1&&r.setSelection(li.near(r.doc.resolve(Q))),r.scrollIntoView()}return!0}const C=g.pos===m.end()?j.contentMatchAt(0).defaultType:null,P={...RI(N,j.type.name,j.attrs),...e},A={...RI(N,m.node().type.name,m.node().attrs),...e};r.delete(m.pos,g.pos);const I=C?[{type:a,attrs:P},{type:C,attrs:A}]:[{type:a,attrs:P}];if(!Rm(r.doc,m.pos,2))return!1;if(i){const{selection:O,storedMarks:R}=n,{splittableMarks:z}=o.extensionManager,W=R||O.$to.parentOffset&&O.$from.marks();if(r.split(m.pos,2,I).scrollIntoView(),!W||!i)return!0;const V=W.filter(K=>z.includes(K.type.name));r.ensureMarks(V)}return!0},Mz=(t,e)=>{const r=tH(c=>c.type===e)(t.selection);if(!r)return!0;const n=t.doc.resolve(Math.max(0,r.pos-1)).before(r.depth);if(n===void 0)return!0;const i=t.doc.nodeAt(n);return r.node.type===(i==null?void 0:i.type)&&Sx(t.doc,r.pos)&&t.join(r.pos),!0},Oz=(t,e)=>{const r=tH(c=>c.type===e)(t.selection);if(!r)return!0;const n=t.doc.resolve(r.start).after(r.depth);if(n===void 0)return!0;const i=t.doc.nodeAt(n);return r.node.type===(i==null?void 0:i.type)&&Sx(t.doc,n)&&t.join(n),!0},iqe=(t,e,r,n={})=>({editor:i,tr:o,state:c,dispatch:a,chain:m,commands:g,can:_})=>{const{extensions:j,splittableMarks:N}=i.extensionManager,C=Xl(t,c.schema),P=Xl(e,c.schema),{selection:A,storedMarks:I}=c,{$from:O,$to:R}=A,z=O.blockRange(R),W=I||A.$to.parentOffset&&A.$from.marks();if(!z)return!1;const V=tH(K=>bJ(K.type.name,j))(A);if(z.depth>=1&&V&&z.depth-V.depth<=1){if(V.node.type===C)return g.liftListItem(P);if(bJ(V.node.type.name,j)&&C.validContent(V.node.content)&&a)return m().command(()=>(o.setNodeMarkup(V.pos,C),!0)).command(()=>Mz(o,C)).command(()=>Oz(o,C)).run()}return!r||!W||!a?m().command(()=>_().wrapInList(C,n)?!0:g.clearNodes()).wrapInList(C,n).command(()=>Mz(o,C)).command(()=>Oz(o,C)).run():m().command(()=>{const K=_().wrapInList(C,n),Q=W.filter(te=>N.includes(te.type.name));return o.ensureMarks(Q),K?!0:g.clearNodes()}).wrapInList(C,n).command(()=>Mz(o,C)).command(()=>Oz(o,C)).run()},aqe=(t,e={},r={})=>({state:n,commands:i})=>{const{extendEmptyMarkRange:o=!1}=r,c=Cx(t,n.schema);return sU(n,c,e)?i.unsetMark(c,{extendEmptyMarkRange:o}):i.setMark(c,e)},oqe=(t,e,r={})=>({state:n,commands:i})=>{const o=Xl(t,n.schema),c=Xl(e,n.schema),a=xk(n,o,r);let m;return n.selection.$anchor.sameParent(n.selection.$head)&&(m=n.selection.$anchor.parent.attrs),a?i.setNode(c,m):i.setNode(o,{...m,...r})},lqe=(t,e={})=>({state:r,commands:n})=>{const i=Xl(t,r.schema);return xk(r,i,e)?n.lift(i):n.wrapIn(i,e)},cqe=()=>({state:t,dispatch:e})=>{const r=t.plugins;for(let n=0;n=0;m-=1)c.step(a.steps[m].invert(a.docs[m]));if(o.text){const m=c.doc.resolve(o.from).marks();c.replaceWith(o.from,o.to,t.schema.text(o.text,m))}else c.delete(o.from,o.to)}return!0}}return!1},uqe=()=>({tr:t,dispatch:e})=>{const{selection:r}=t,{empty:n,ranges:i}=r;return n||e&&i.forEach(o=>{t.removeMark(o.$from.pos,o.$to.pos)}),!0},dqe=(t,e={})=>({tr:r,state:n,dispatch:i})=>{var o;const{extendEmptyMarkRange:c=!1}=e,{selection:a}=r,m=Cx(t,n.schema),{$from:g,empty:_,ranges:j}=a;if(!i)return!0;if(_&&c){let{from:N,to:C}=a;const P=(o=g.marks().find(I=>I.type===m))===null||o===void 0?void 0:o.attrs,A=Jq(g,m,P);A&&(N=A.from,C=A.to),r.removeMark(N,C,m)}else j.forEach(N=>{r.removeMark(N.$from.pos,N.$to.pos,m)});return r.removeStoredMark(m),!0},hqe=(t,e={})=>({tr:r,state:n,dispatch:i})=>{let o=null,c=null;const a=iL(typeof t=="string"?t:t.name,n.schema);return a?(a==="node"&&(o=Xl(t,n.schema)),a==="mark"&&(c=Cx(t,n.schema)),i&&r.selection.ranges.forEach(m=>{const g=m.$from.pos,_=m.$to.pos;let j,N,C,P;r.selection.empty?n.doc.nodesBetween(g,_,(A,I)=>{o&&o===A.type&&(C=Math.max(I,g),P=Math.min(I+A.nodeSize,_),j=I,N=A)}):n.doc.nodesBetween(g,_,(A,I)=>{I=g&&I<=_&&(o&&o===A.type&&r.setNodeMarkup(I,void 0,{...A.attrs,...e}),c&&A.marks.length&&A.marks.forEach(O=>{if(c===O.type){const R=Math.max(I,g),z=Math.min(I+A.nodeSize,_);r.addMark(R,z,c.create({...O.attrs,...e}))}}))}),N&&(j!==void 0&&r.setNodeMarkup(j,void 0,{...N.attrs,...e}),c&&N.marks.length&&N.marks.forEach(A=>{c===A.type&&r.addMark(C,P,c.create({...A.attrs,...e}))}))}),!0):!1},fqe=(t,e={})=>({state:r,dispatch:n})=>{const i=Xl(t,r.schema);return N6e(i,e)(r,n)},pqe=(t,e={})=>({state:r,dispatch:n})=>{const i=Xl(t,r.schema);return C6e(i,e)(r,n)};var mqe=Object.freeze({__proto__:null,blur:Z6e,clearContent:Y6e,clearNodes:X6e,command:Q6e,createParagraphNear:J6e,cut:e8e,deleteCurrentNode:t8e,deleteNode:r8e,deleteRange:n8e,deleteSelection:s8e,enter:i8e,exitCode:a8e,extendMarkRange:o8e,first:l8e,focus:u8e,forEach:d8e,insertContent:h8e,insertContentAt:m8e,joinBackward:x8e,joinDown:y8e,joinForward:v8e,joinItemBackward:_8e,joinItemForward:b8e,joinTextblockBackward:w8e,joinTextblockForward:j8e,joinUp:g8e,keyboardShortcut:N8e,lift:C8e,liftEmptyBlock:k8e,liftListItem:T8e,newlineInCode:E8e,resetAttributes:A8e,scrollIntoView:P8e,selectAll:I8e,selectNodeBackward:M8e,selectNodeForward:O8e,selectParentNode:R8e,selectTextblockEnd:D8e,selectTextblockStart:L8e,setContent:F8e,setMark:X8e,setMeta:Q8e,setNode:J8e,setNodeSelection:eqe,setTextSelection:tqe,sinkListItem:rqe,splitBlock:nqe,splitListItem:sqe,toggleList:iqe,toggleMark:aqe,toggleNode:oqe,toggleWrap:lqe,undoInputRule:cqe,unsetAllMarks:uqe,unsetMark:dqe,updateAttributes:hqe,wrapIn:fqe,wrapInList:pqe});const gqe=bc.create({name:"commands",addCommands(){return{...mqe}}}),yqe=bc.create({name:"drop",addProseMirrorPlugins(){return[new wc({key:new kd("tiptapDrop"),props:{handleDrop:(t,e,r,n)=>{this.editor.emit("drop",{editor:this.editor,event:e,slice:r,moved:n})}}})]}}),xqe=bc.create({name:"editable",addProseMirrorPlugins(){return[new wc({key:new kd("editable"),props:{editable:()=>this.editor.options.editable}})]}}),vqe=new kd("focusEvents"),_qe=bc.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:t}=this;return[new wc({key:vqe,props:{handleDOMEvents:{focus:(e,r)=>{t.isFocused=!0;const n=t.state.tr.setMeta("focus",{event:r}).setMeta("addToHistory",!1);return e.dispatch(n),!1},blur:(e,r)=>{t.isFocused=!1;const n=t.state.tr.setMeta("blur",{event:r}).setMeta("addToHistory",!1);return e.dispatch(n),!1}}}})]}}),bqe=bc.create({name:"keymap",addKeyboardShortcuts(){const t=()=>this.editor.commands.first(({commands:c})=>[()=>c.undoInputRule(),()=>c.command(({tr:a})=>{const{selection:m,doc:g}=a,{empty:_,$anchor:j}=m,{pos:N,parent:C}=j,P=j.parent.isTextblock&&N>0?a.doc.resolve(N-1):j,A=P.parent.type.spec.isolating,I=j.pos-j.parentOffset,O=A&&P.parent.childCount===1?I===j.pos:Pi.atStart(g).from===N;return!_||!C.type.isTextblock||C.textContent.length||!O||O&&j.parent.type.name==="paragraph"?!1:c.clearNodes()}),()=>c.deleteSelection(),()=>c.joinBackward(),()=>c.selectNodeBackward()]),e=()=>this.editor.commands.first(({commands:c})=>[()=>c.deleteSelection(),()=>c.deleteCurrentNode(),()=>c.joinForward(),()=>c.selectNodeForward()]),n={Enter:()=>this.editor.commands.first(({commands:c})=>[()=>c.newlineInCode(),()=>c.createParagraphNear(),()=>c.liftEmptyBlock(),()=>c.splitBlock()]),"Mod-Enter":()=>this.editor.commands.exitCode(),Backspace:t,"Mod-Backspace":t,"Shift-Backspace":t,Delete:e,"Mod-Delete":e,"Mod-a":()=>this.editor.commands.selectAll()},i={...n},o={...n,"Ctrl-h":t,"Alt-Backspace":t,"Ctrl-d":e,"Ctrl-Alt-Backspace":e,"Alt-Delete":e,"Alt-d":e,"Ctrl-a":()=>this.editor.commands.selectTextblockStart(),"Ctrl-e":()=>this.editor.commands.selectTextblockEnd()};return eH()||Jge()?o:i},addProseMirrorPlugins(){return[new wc({key:new kd("clearDocument"),appendTransaction:(t,e,r)=>{if(t.some(A=>A.getMeta("composition")))return;const n=t.some(A=>A.docChanged)&&!e.doc.eq(r.doc),i=t.some(A=>A.getMeta("preventClearDocument"));if(!n||i)return;const{empty:o,from:c,to:a}=e.selection,m=Pi.atStart(e.doc).from,g=Pi.atEnd(e.doc).to;if(o||!(c===m&&a===g)||!nH(r.doc))return;const N=r.tr,C=eL({state:r,transaction:N}),{commands:P}=new tL({editor:this.editor,state:C});if(P.clearNodes(),!!N.steps.length)return N}})]}}),wqe=bc.create({name:"paste",addProseMirrorPlugins(){return[new wc({key:new kd("tiptapPaste"),props:{handlePaste:(t,e,r)=>{this.editor.emit("paste",{editor:this.editor,event:e,slice:r})}}})]}}),jqe=bc.create({name:"tabindex",addProseMirrorPlugins(){return[new wc({key:new kd("tabindex"),props:{attributes:()=>this.editor.isEditable?{tabindex:"0"}:{}}})]}});class Uv{get name(){return this.node.type.name}constructor(e,r,n=!1,i=null){this.currentNode=null,this.actualDepth=null,this.isBlock=n,this.resolvedPos=e,this.editor=r,this.currentNode=i}get node(){return this.currentNode||this.resolvedPos.node()}get element(){return this.editor.view.domAtPos(this.pos).node}get depth(){var e;return(e=this.actualDepth)!==null&&e!==void 0?e:this.resolvedPos.depth}get pos(){return this.resolvedPos.pos}get content(){return this.node.content}set content(e){let r=this.from,n=this.to;if(this.isBlock){if(this.content.size===0){console.error(`You can’t set content on a block node. Tried to set content on ${this.name} at ${this.pos}`);return}r=this.from+1,n=this.to-1}this.editor.commands.insertContentAt({from:r,to:n},e)}get attributes(){return this.node.attrs}get textContent(){return this.node.textContent}get size(){return this.node.nodeSize}get from(){return this.isBlock?this.pos:this.resolvedPos.start(this.resolvedPos.depth)}get range(){return{from:this.from,to:this.to}}get to(){return this.isBlock?this.pos+this.size:this.resolvedPos.end(this.resolvedPos.depth)+(this.node.isText?0:1)}get parent(){if(this.depth===0)return null;const e=this.resolvedPos.start(this.resolvedPos.depth-1),r=this.resolvedPos.doc.resolve(e);return new Uv(r,this.editor)}get before(){let e=this.resolvedPos.doc.resolve(this.from-(this.isBlock?1:2));return e.depth!==this.depth&&(e=this.resolvedPos.doc.resolve(this.from-3)),new Uv(e,this.editor)}get after(){let e=this.resolvedPos.doc.resolve(this.to+(this.isBlock?2:1));return e.depth!==this.depth&&(e=this.resolvedPos.doc.resolve(this.to+3)),new Uv(e,this.editor)}get children(){const e=[];return this.node.content.forEach((r,n)=>{const i=r.isBlock&&!r.isTextblock,o=r.isAtom&&!r.isText,c=this.pos+n+(o?0:1);if(c<0||c>this.resolvedPos.doc.nodeSize-2)return;const a=this.resolvedPos.doc.resolve(c);if(!i&&a.depth<=this.depth)return;const m=new Uv(a,this.editor,i,i?r:null);i&&(m.actualDepth=this.depth+1),e.push(new Uv(a,this.editor,i,i?r:null))}),e}get firstChild(){return this.children[0]||null}get lastChild(){const e=this.children;return e[e.length-1]||null}closest(e,r={}){let n=null,i=this.parent;for(;i&&!n;){if(i.node.type.name===e)if(Object.keys(r).length>0){const o=i.node.attrs,c=Object.keys(r);for(let a=0;a{n&&i.length>0||(c.node.type.name===e&&o.every(m=>r[m]===c.node.attrs[m])&&i.push(c),!(n&&i.length>0)&&(i=i.concat(c.querySelectorAll(e,r,n))))}),i}setAttribute(e){const{tr:r}=this.editor.state;r.setNodeMarkup(this.from,void 0,{...this.node.attrs,...e}),this.editor.view.dispatch(r)}}const Sqe=`.ProseMirror { position: relative; } .ProseMirror { word-wrap: break-word; white-space: pre-wrap; white-space: break-spaces; -webkit-font-variant-ligatures: none; font-variant-ligatures: none; font-feature-settings: "liga" 0; /* the above doesn't seem to work in Edge */ } .ProseMirror [contenteditable="false"] { white-space: normal; } .ProseMirror [contenteditable="false"] [contenteditable="true"] { white-space: pre-wrap; } .ProseMirror pre { white-space: pre-wrap; } img.ProseMirror-separator { display: inline !important; border: none !important; margin: 0 !important; width: 0 !important; height: 0 !important; } .ProseMirror-gapcursor { display: none; pointer-events: none; position: absolute; margin: 0; } .ProseMirror-gapcursor:after { content: ""; display: block; position: absolute; top: -2px; width: 20px; border-top: 1px solid black; animation: ProseMirror-cursor-blink 1.1s steps(2, start) infinite; } @keyframes ProseMirror-cursor-blink { to { visibility: hidden; } } .ProseMirror-hideselection *::selection { background: transparent; } .ProseMirror-hideselection *::-moz-selection { background: transparent; } .ProseMirror-hideselection * { caret-color: transparent; } .ProseMirror-focused .ProseMirror-gapcursor { display: block; } .tippy-box[data-animation=fade][data-state=hidden] { opacity: 0 }`;function Nqe(t,e,r){const n=document.querySelector("style[data-tiptap-style]");if(n!==null)return n;const i=document.createElement("style");return e&&i.setAttribute("nonce",e),i.setAttribute("data-tiptap-style",""),i.innerHTML=t,document.getElementsByTagName("head")[0].appendChild(i),i}class Cqe extends M6e{constructor(e={}){super(),this.isFocused=!1,this.isInitialized=!1,this.extensionStorage={},this.options={element:document.createElement("div"),content:"",injectCSS:!0,injectNonce:void 0,extensions:[],autofocus:!1,editable:!0,editorProps:{},parseOptions:{},coreExtensionOptions:{},enableInputRules:!0,enablePasteRules:!0,enableCoreExtensions:!0,enableContentCheck:!1,emitContentError:!1,onBeforeCreate:()=>null,onCreate:()=>null,onUpdate:()=>null,onSelectionUpdate:()=>null,onTransaction:()=>null,onFocus:()=>null,onBlur:()=>null,onDestroy:()=>null,onContentError:({error:r})=>{throw r},onPaste:()=>null,onDrop:()=>null},this.isCapturingTransaction=!1,this.capturedTransaction=null,this.setOptions(e),this.createExtensionManager(),this.createCommandManager(),this.createSchema(),this.on("beforeCreate",this.options.onBeforeCreate),this.emit("beforeCreate",{editor:this}),this.on("contentError",this.options.onContentError),this.createView(),this.injectCSS(),this.on("create",this.options.onCreate),this.on("update",this.options.onUpdate),this.on("selectionUpdate",this.options.onSelectionUpdate),this.on("transaction",this.options.onTransaction),this.on("focus",this.options.onFocus),this.on("blur",this.options.onBlur),this.on("destroy",this.options.onDestroy),this.on("drop",({event:r,slice:n,moved:i})=>this.options.onDrop(r,n,i)),this.on("paste",({event:r,slice:n})=>this.options.onPaste(r,n)),window.setTimeout(()=>{this.isDestroyed||(this.commands.focus(this.options.autofocus),this.emit("create",{editor:this}),this.isInitialized=!0)},0)}get storage(){return this.extensionStorage}get commands(){return this.commandManager.commands}chain(){return this.commandManager.chain()}can(){return this.commandManager.can()}injectCSS(){this.options.injectCSS&&document&&(this.css=Nqe(Sqe,this.options.injectNonce))}setOptions(e={}){this.options={...this.options,...e},!(!this.view||!this.state||this.isDestroyed)&&(this.options.editorProps&&this.view.setProps(this.options.editorProps),this.view.updateState(this.state))}setEditable(e,r=!0){this.setOptions({editable:e}),r&&this.emit("update",{editor:this,transaction:this.state.tr})}get isEditable(){return this.options.editable&&this.view&&this.view.editable}get state(){return this.view.state}registerPlugin(e,r){const n=Wge(r)?r(e,[...this.state.plugins]):[...this.state.plugins,e],i=this.state.reconfigure({plugins:n});return this.view.updateState(i),i}unregisterPlugin(e){if(this.isDestroyed)return;const r=this.state.plugins;let n=r;if([].concat(e).forEach(o=>{const c=typeof o=="string"?`${o}$`:o.key;n=n.filter(a=>!a.key.startsWith(c))}),r.length===n.length)return;const i=this.state.reconfigure({plugins:n});return this.view.updateState(i),i}createExtensionManager(){var e,r;const i=[...this.options.enableCoreExtensions?[xqe,K6e.configure({blockSeparator:(r=(e=this.options.coreExtensionOptions)===null||e===void 0?void 0:e.clipboardTextSerializer)===null||r===void 0?void 0:r.blockSeparator}),gqe,_qe,bqe,jqe,yqe,wqe].filter(o=>typeof this.options.enableCoreExtensions=="object"?this.options.enableCoreExtensions[o.name]!==!1:!0):[],...this.options.extensions].filter(o=>["extension","node","mark"].includes(o==null?void 0:o.type));this.extensionManager=new Bw(i,this)}createCommandManager(){this.commandManager=new tL({editor:this})}createSchema(){this.schema=this.extensionManager.schema}createView(){var e;let r;try{r=nU(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:this.options.enableContentCheck})}catch(c){if(!(c instanceof Error)||!["[tiptap error]: Invalid JSON content","[tiptap error]: Invalid HTML content"].includes(c.message))throw c;this.emit("contentError",{editor:this,error:c,disableCollaboration:()=>{this.storage.collaboration&&(this.storage.collaboration.isDisabled=!0),this.options.extensions=this.options.extensions.filter(a=>a.name!=="collaboration"),this.createExtensionManager()}}),r=nU(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:!1})}const n=Xge(r,this.options.autofocus);this.view=new Pge(this.options.element,{...this.options.editorProps,attributes:{role:"textbox",...(e=this.options.editorProps)===null||e===void 0?void 0:e.attributes},dispatchTransaction:this.dispatchTransaction.bind(this),state:zw.create({doc:r,selection:n||void 0})});const i=this.state.reconfigure({plugins:this.extensionManager.plugins});this.view.updateState(i),this.createNodeViews(),this.prependClass();const o=this.view.dom;o.editor=this}createNodeViews(){this.view.isDestroyed||this.view.setProps({nodeViews:this.extensionManager.nodeViews})}prependClass(){this.view.dom.className=`tiptap ${this.view.dom.className}`}captureTransaction(e){this.isCapturingTransaction=!0,e(),this.isCapturingTransaction=!1;const r=this.capturedTransaction;return this.capturedTransaction=null,r}dispatchTransaction(e){if(this.view.isDestroyed)return;if(this.isCapturingTransaction){if(!this.capturedTransaction){this.capturedTransaction=e;return}e.steps.forEach(c=>{var a;return(a=this.capturedTransaction)===null||a===void 0?void 0:a.step(c)});return}const r=this.state.apply(e),n=!this.state.selection.eq(r.selection);this.emit("beforeTransaction",{editor:this,transaction:e,nextState:r}),this.view.updateState(r),this.emit("transaction",{editor:this,transaction:e}),n&&this.emit("selectionUpdate",{editor:this,transaction:e});const i=e.getMeta("focus"),o=e.getMeta("blur");i&&this.emit("focus",{editor:this,event:i.event,transaction:e}),o&&this.emit("blur",{editor:this,event:o.event,transaction:e}),!(!e.docChanged||e.getMeta("preventUpdate"))&&this.emit("update",{editor:this,transaction:e})}getAttributes(e){return tye(this.state,e)}isActive(e,r){const n=typeof e=="string"?e:null,i=typeof e=="string"?r:e;return K8e(this.state,n,i)}getJSON(){return this.state.doc.toJSON()}getHTML(){return Xq(this.state.doc.content,this.schema)}getText(e){const{blockSeparator:r=` `,textSerializers:n={}}=e||{};return V8e(this.state.doc,{blockSeparator:r,textSerializers:{...Kge(this.schema),...n}})}get isEmpty(){return nH(this.state.doc)}getCharacterCount(){return console.warn('[tiptap warn]: "editor.getCharacterCount()" is deprecated. Please use "editor.storage.characterCount.characters()" instead.'),this.state.doc.content.size-2}destroy(){if(this.emit("destroy"),this.view){const e=this.view.dom;e&&e.editor&&delete e.editor,this.view.destroy()}this.removeAllListeners()}get isDestroyed(){var e;return!(!((e=this.view)===null||e===void 0)&&e.docView)}$node(e,r){var n;return((n=this.$doc)===null||n===void 0?void 0:n.querySelector(e,r))||null}$nodes(e,r){var n;return((n=this.$doc)===null||n===void 0?void 0:n.querySelectorAll(e,r))||null}$pos(e){const r=this.state.doc.resolve(e);return new Uv(r,this)}get $doc(){return this.$pos(0)}}function ej(t){return new nL({find:t.find,handler:({state:e,range:r,match:n})=>{const i=Oi(t.getAttributes,void 0,n);if(i===!1||i===null)return null;const{tr:o}=e,c=n[n.length-1],a=n[0];if(c){const m=a.search(/\S/),g=r.from+a.indexOf(c),_=g+c.length;if(rH(r.from,r.to,e.doc).filter(C=>C.mark.type.excluded.find(A=>A===t.type&&A!==C.mark.type)).filter(C=>C.to>g).length)return null;_r.from&&o.delete(r.from+m,g);const N=r.from+m+c.length;o.addMark(r.from+m,N,t.type.create(i||{})),o.removeStoredMark(t.type)}}})}function kqe(t){return new nL({find:t.find,handler:({state:e,range:r,match:n})=>{const i=Oi(t.getAttributes,void 0,n)||{},{tr:o}=e,c=r.from;let a=r.to;const m=t.type.create(i);if(n[1]){const g=n[0].lastIndexOf(n[1]);let _=c+g;_>a?_=a:a=_+n[1].length;const j=n[0][n[0].length-1];o.insertText(j,c+n[0].length-1),o.replaceWith(_,a,m)}else if(n[0]){const g=t.type.isInline?c:c-1;o.insert(g,t.type.create(i)).delete(o.mapping.map(c),o.mapping.map(a))}o.scrollIntoView()}})}function iU(t){return new nL({find:t.find,handler:({state:e,range:r,match:n})=>{const i=e.doc.resolve(r.from),o=Oi(t.getAttributes,void 0,n)||{};if(!i.node(-1).canReplaceWith(i.index(-1),i.indexAfter(-1),t.type))return null;e.tr.delete(r.from,r.to).setBlockType(r.from,r.from,t.type,o)}})}function vk(t){return new nL({find:t.find,handler:({state:e,range:r,match:n,chain:i})=>{const o=Oi(t.getAttributes,void 0,n)||{},c=e.tr.delete(r.from,r.to),m=c.doc.resolve(r.from).blockRange(),g=m&&Rq(m,t.type,o);if(!g)return null;if(c.wrap(m,g),t.keepMarks&&t.editor){const{selection:j,storedMarks:N}=e,{splittableMarks:C}=t.editor.extensionManager,P=N||j.$to.parentOffset&&j.$from.marks();if(P){const A=P.filter(I=>C.includes(I.type.name));c.ensureMarks(A)}}if(t.keepAttributes){const j=t.type.name==="bulletList"||t.type.name==="orderedList"?"listItem":"taskList";i().updateAttributes(j,o).run()}const _=c.doc.resolve(r.from-1).nodeBefore;_&&_.type===t.type&&Sx(c.doc,r.from-1)&&(!t.joinPredicate||t.joinPredicate(n,_))&&c.join(r.from-1)}})}let Af=class aU{constructor(e={}){this.type="node",this.name="node",this.parent=null,this.child=null,this.config={name:this.name,defaultOptions:{}},this.config={...this.config,...e},this.name=this.config.name,e.defaultOptions&&Object.keys(e.defaultOptions).length>0&&console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${this.name}".`),this.options=this.config.defaultOptions,this.config.addOptions&&(this.options=Oi(Jn(this,"addOptions",{name:this.name}))),this.storage=Oi(Jn(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(e={}){return new aU(e)}configure(e={}){const r=this.extend({...this.config,addOptions:()=>sL(this.options,e)});return r.name=this.name,r.parent=this.parent,r}extend(e={}){const r=new aU(e);return r.parent=this,this.child=r,r.name=e.name?e.name:r.parent.name,e.defaultOptions&&Object.keys(e.defaultOptions).length>0&&console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${r.name}".`),r.options=Oi(Jn(r,"addOptions",{name:r.name})),r.storage=Oi(Jn(r,"addStorage",{name:r.name,options:r.options})),r}};function H_(t){return new U6e({find:t.find,handler:({state:e,range:r,match:n,pasteEvent:i})=>{const o=Oi(t.getAttributes,void 0,n,i);if(o===!1||o===null)return null;const{tr:c}=e,a=n[n.length-1],m=n[0];let g=r.to;if(a){const _=m.search(/\S/),j=r.from+m.indexOf(a),N=j+a.length;if(rH(r.from,r.to,e.doc).filter(P=>P.mark.type.excluded.find(I=>I===t.type&&I!==P.mark.type)).filter(P=>P.to>j).length)return null;Nr.from&&c.delete(r.from+_,j),g=r.from+_+a.length,c.addMark(r.from+_,g,t.type.create(o||{})),c.removeStoredMark(t.type)}}})}function Tqe(t,e){const{selection:r}=t,{$from:n}=r;if(r instanceof js){const o=n.index();return n.parent.canReplaceWith(o,o+1,e)}let i=n.depth;for(;i>=0;){const o=n.index(i);if(n.node(i).contentMatchAt(o).matchType(e))return!0;i-=1}return!1}function Eqe(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var rye={exports:{}},Rz={};/** * @license React * use-sync-external-store-shim.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 jJ;function Aqe(){if(jJ)return Rz;jJ=1;var t=Ve;function e(j,N){return j===N&&(j!==0||1/j===1/N)||j!==j&&N!==N}var r=typeof Object.is=="function"?Object.is:e,n=t.useState,i=t.useEffect,o=t.useLayoutEffect,c=t.useDebugValue;function a(j,N){var C=N(),P=n({inst:{value:C,getSnapshot:N}}),A=P[0].inst,I=P[1];return o(function(){A.value=C,A.getSnapshot=N,m(A)&&I({inst:A})},[j,C,N]),i(function(){return m(A)&&I({inst:A}),j(function(){m(A)&&I({inst:A})})},[j]),c(C),C}function m(j){var N=j.getSnapshot;j=j.value;try{var C=N();return!r(j,C)}catch{return!0}}function g(j,N){return N()}var _=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?g:a;return Rz.useSyncExternalStore=t.useSyncExternalStore!==void 0?t.useSyncExternalStore:_,Rz}rye.exports=Aqe();var sH=rye.exports;const Pqe=(...t)=>e=>{t.forEach(r=>{typeof r=="function"?r(e):r&&(r.current=e)})},Iqe=({contentComponent:t})=>{const e=sH.useSyncExternalStore(t.subscribe,t.getSnapshot,t.getServerSnapshot);return Ve.createElement(Ve.Fragment,null,Object.values(e))};function Mqe(){const t=new Set;let e={};return{subscribe(r){return t.add(r),()=>{t.delete(r)}},getSnapshot(){return e},getServerSnapshot(){return e},setRenderer(r,n){e={...e,[r]:B6.createPortal(n.reactElement,n.element,r)},t.forEach(i=>i())},removeRenderer(r){const n={...e};delete n[r],e=n,t.forEach(i=>i())}}}class Oqe extends Ve.Component{constructor(e){var r;super(e),this.editorContentRef=Ve.createRef(),this.initialized=!1,this.state={hasContentComponentInitialized:!!(!((r=e.editor)===null||r===void 0)&&r.contentComponent)}}componentDidMount(){this.init()}componentDidUpdate(){this.init()}init(){const e=this.props.editor;if(e&&!e.isDestroyed&&e.options.element){if(e.contentComponent)return;const r=this.editorContentRef.current;r.append(...e.options.element.childNodes),e.setOptions({element:r}),e.contentComponent=Mqe(),this.state.hasContentComponentInitialized||(this.unsubscribeToContentComponent=e.contentComponent.subscribe(()=>{this.setState(n=>n.hasContentComponentInitialized?n:{hasContentComponentInitialized:!0}),this.unsubscribeToContentComponent&&this.unsubscribeToContentComponent()})),e.createNodeViews(),this.initialized=!0}}componentWillUnmount(){const e=this.props.editor;if(!e||(this.initialized=!1,e.isDestroyed||e.view.setProps({nodeViews:{}}),this.unsubscribeToContentComponent&&this.unsubscribeToContentComponent(),e.contentComponent=null,!e.options.element.firstChild))return;const r=document.createElement("div");r.append(...e.options.element.childNodes),e.setOptions({element:r})}render(){const{editor:e,innerRef:r,...n}=this.props;return Ve.createElement(Ve.Fragment,null,Ve.createElement("div",{ref:Pqe(r,this.editorContentRef),...n}),(e==null?void 0:e.contentComponent)&&Ve.createElement(Iqe,{contentComponent:e.contentComponent}))}}const Rqe=D.forwardRef((t,e)=>{const r=Ve.useMemo(()=>Math.floor(Math.random()*4294967295).toString(),[t.editor]);return Ve.createElement(Oqe,{key:r,innerRef:e,...t})}),nye=Ve.memo(Rqe);var Dqe=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,i,o;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(i=n;i--!==0;)if(!t(e[i],r[i]))return!1;return!0}if(e instanceof Map&&r instanceof Map){if(e.size!==r.size)return!1;for(i of e.entries())if(!r.has(i[0]))return!1;for(i of e.entries())if(!t(i[1],r.get(i[0])))return!1;return!0}if(e instanceof Set&&r instanceof Set){if(e.size!==r.size)return!1;for(i of e.entries())if(!r.has(i[0]))return!1;return!0}if(ArrayBuffer.isView(e)&&ArrayBuffer.isView(r)){if(n=e.length,n!=r.length)return!1;for(i=n;i--!==0;)if(e[i]!==r[i])return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(o=Object.keys(e),n=o.length,n!==Object.keys(r).length)return!1;for(i=n;i--!==0;)if(!Object.prototype.hasOwnProperty.call(r,o[i]))return!1;for(i=n;i--!==0;){var c=o[i];if(!(c==="_owner"&&e.$$typeof)&&!t(e[c],r[c]))return!1}return!0}return e!==e&&r!==r},Lqe=Eqe(Dqe),sye={exports:{}},Dz={};/** * @license React * use-sync-external-store-shim/with-selector.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 SJ;function Fqe(){if(SJ)return Dz;SJ=1;var t=Ve,e=sH;function r(g,_){return g===_&&(g!==0||1/g===1/_)||g!==g&&_!==_}var n=typeof Object.is=="function"?Object.is:r,i=e.useSyncExternalStore,o=t.useRef,c=t.useEffect,a=t.useMemo,m=t.useDebugValue;return Dz.useSyncExternalStoreWithSelector=function(g,_,j,N,C){var P=o(null);if(P.current===null){var A={hasValue:!1,value:null};P.current=A}else A=P.current;P=a(function(){function O(K){if(!R){if(R=!0,z=K,K=N(K),C!==void 0&&A.hasValue){var Q=A.value;if(C(Q,K))return W=Q}return W=K}if(Q=W,n(z,K))return Q;var te=N(K);return C!==void 0&&C(Q,te)?Q:(z=K,W=te)}var R=!1,z,W,V=j===void 0?null:j;return[function(){return O(_())},V===null?void 0:function(){return O(V())}]},[_,j,N,C]);var I=i(g,P[0],P[1]);return c(function(){A.hasValue=!0,A.value=I},[I]),m(I),I},Dz}sye.exports=Fqe();var zqe=sye.exports;const Bqe=typeof window<"u"?D.useLayoutEffect:D.useEffect;class $qe{constructor(e){this.transactionNumber=0,this.lastTransactionNumber=0,this.subscribers=new Set,this.editor=e,this.lastSnapshot={editor:e,transactionNumber:0},this.getSnapshot=this.getSnapshot.bind(this),this.getServerSnapshot=this.getServerSnapshot.bind(this),this.watch=this.watch.bind(this),this.subscribe=this.subscribe.bind(this)}getSnapshot(){return this.transactionNumber===this.lastTransactionNumber?this.lastSnapshot:(this.lastTransactionNumber=this.transactionNumber,this.lastSnapshot={editor:this.editor,transactionNumber:this.transactionNumber},this.lastSnapshot)}getServerSnapshot(){return{editor:null,transactionNumber:0}}subscribe(e){return this.subscribers.add(e),()=>{this.subscribers.delete(e)}}watch(e){if(this.editor=e,this.editor){const r=()=>{this.transactionNumber+=1,this.subscribers.forEach(i=>i())},n=this.editor;return n.on("transaction",r),()=>{n.off("transaction",r)}}}}function Uqe(t){var e;const[r]=D.useState(()=>new $qe(t.editor)),n=zqe.useSyncExternalStoreWithSelector(r.subscribe,r.getSnapshot,r.getServerSnapshot,t.selector,(e=t.equalityFn)!==null&&e!==void 0?e:Lqe);return Bqe(()=>r.watch(t.editor),[t.editor,r]),D.useDebugValue(n),n}const Vqe=!1,oU=typeof window>"u",qqe=oU||!!(typeof window<"u"&&window.next);class iH{constructor(e){this.editor=null,this.subscriptions=new Set,this.isComponentMounted=!1,this.previousDeps=null,this.instanceId="",this.options=e,this.subscriptions=new Set,this.setEditor(this.getInitialEditor()),this.scheduleDestroy(),this.getEditor=this.getEditor.bind(this),this.getServerSnapshot=this.getServerSnapshot.bind(this),this.subscribe=this.subscribe.bind(this),this.refreshEditorInstance=this.refreshEditorInstance.bind(this),this.scheduleDestroy=this.scheduleDestroy.bind(this),this.onRender=this.onRender.bind(this),this.createEditor=this.createEditor.bind(this)}setEditor(e){this.editor=e,this.instanceId=Math.random().toString(36).slice(2,9),this.subscriptions.forEach(r=>r())}getInitialEditor(){return this.options.current.immediatelyRender===void 0?oU||qqe?null:this.createEditor():(this.options.current.immediatelyRender,this.options.current.immediatelyRender?this.createEditor():null)}createEditor(){const e={...this.options.current,onBeforeCreate:(...n)=>{var i,o;return(o=(i=this.options.current).onBeforeCreate)===null||o===void 0?void 0:o.call(i,...n)},onBlur:(...n)=>{var i,o;return(o=(i=this.options.current).onBlur)===null||o===void 0?void 0:o.call(i,...n)},onCreate:(...n)=>{var i,o;return(o=(i=this.options.current).onCreate)===null||o===void 0?void 0:o.call(i,...n)},onDestroy:(...n)=>{var i,o;return(o=(i=this.options.current).onDestroy)===null||o===void 0?void 0:o.call(i,...n)},onFocus:(...n)=>{var i,o;return(o=(i=this.options.current).onFocus)===null||o===void 0?void 0:o.call(i,...n)},onSelectionUpdate:(...n)=>{var i,o;return(o=(i=this.options.current).onSelectionUpdate)===null||o===void 0?void 0:o.call(i,...n)},onTransaction:(...n)=>{var i,o;return(o=(i=this.options.current).onTransaction)===null||o===void 0?void 0:o.call(i,...n)},onUpdate:(...n)=>{var i,o;return(o=(i=this.options.current).onUpdate)===null||o===void 0?void 0:o.call(i,...n)},onContentError:(...n)=>{var i,o;return(o=(i=this.options.current).onContentError)===null||o===void 0?void 0:o.call(i,...n)},onDrop:(...n)=>{var i,o;return(o=(i=this.options.current).onDrop)===null||o===void 0?void 0:o.call(i,...n)},onPaste:(...n)=>{var i,o;return(o=(i=this.options.current).onPaste)===null||o===void 0?void 0:o.call(i,...n)}};return new Cqe(e)}getEditor(){return this.editor}getServerSnapshot(){return null}subscribe(e){return this.subscriptions.add(e),()=>{this.subscriptions.delete(e)}}static compareOptions(e,r){return Object.keys(e).every(n=>["onCreate","onBeforeCreate","onDestroy","onUpdate","onTransaction","onFocus","onBlur","onSelectionUpdate","onContentError","onDrop","onPaste"].includes(n)?!0:n==="extensions"&&e.extensions&&r.extensions?e.extensions.length!==r.extensions.length?!1:e.extensions.every((i,o)=>{var c;return i===((c=r.extensions)===null||c===void 0?void 0:c[o])}):e[n]===r[n])}onRender(e){return()=>(this.isComponentMounted=!0,clearTimeout(this.scheduledDestructionTimeout),this.editor&&!this.editor.isDestroyed&&e.length===0?iH.compareOptions(this.options.current,this.editor.options)||this.editor.setOptions({...this.options.current,editable:this.editor.isEditable}):this.refreshEditorInstance(e),()=>{this.isComponentMounted=!1,this.scheduleDestroy()})}refreshEditorInstance(e){if(this.editor&&!this.editor.isDestroyed){if(this.previousDeps===null){this.previousDeps=e;return}if(this.previousDeps.length===e.length&&this.previousDeps.every((n,i)=>n===e[i]))return}this.editor&&!this.editor.isDestroyed&&this.editor.destroy(),this.setEditor(this.createEditor()),this.previousDeps=e}scheduleDestroy(){const e=this.instanceId,r=this.editor;this.scheduledDestructionTimeout=setTimeout(()=>{if(this.isComponentMounted&&this.instanceId===e){r&&r.setOptions(this.options.current);return}r&&!r.isDestroyed&&(r.destroy(),this.instanceId===e&&this.setEditor(null))},1)}}function iye(t={},e=[]){const r=D.useRef(t);r.current=t;const[n]=D.useState(()=>new iH(r)),i=sH.useSyncExternalStore(n.subscribe,n.getEditor,n.getServerSnapshot);return D.useDebugValue(i),D.useEffect(n.onRender(e)),Uqe({editor:i,selector:({transactionNumber:o})=>t.shouldRerenderOnTransaction===!1?null:t.immediatelyRender&&o===0?0:o+1}),i}const Hqe=D.createContext({editor:null});Hqe.Consumer;const Wqe=D.createContext({onDragStart:void 0}),Gqe=()=>D.useContext(Wqe);Ve.forwardRef((t,e)=>{const{onDragStart:r}=Gqe(),n=t.as||"div";return Ve.createElement(n,{...t,ref:e,"data-node-view-wrapper":"",onDragStart:r,style:{whiteSpace:"normal",...t.style}})});const Kqe=/^\s*>\s$/,Zqe=Af.create({name:"blockquote",addOptions(){return{HTMLAttributes:{}}},content:"block+",group:"block",defining:!0,parseHTML(){return[{tag:"blockquote"}]},renderHTML({HTMLAttributes:t}){return["blockquote",Ql(this.options.HTMLAttributes,t),0]},addCommands(){return{setBlockquote:()=>({commands:t})=>t.wrapIn(this.name),toggleBlockquote:()=>({commands:t})=>t.toggleWrap(this.name),unsetBlockquote:()=>({commands:t})=>t.lift(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-b":()=>this.editor.commands.toggleBlockquote()}},addInputRules(){return[vk({find:Kqe,type:this.type})]}}),Yqe=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,Xqe=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,Qqe=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,Jqe=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g,eHe=Ep.create({name:"bold",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"strong"},{tag:"b",getAttrs:t=>t.style.fontWeight!=="normal"&&null},{style:"font-weight=400",clearMark:t=>t.type.name===this.name},{style:"font-weight",getAttrs:t=>/^(bold(er)?|[5-9]\d{2,})$/.test(t)&&null}]},renderHTML({HTMLAttributes:t}){return["strong",Ql(this.options.HTMLAttributes,t),0]},addCommands(){return{setBold:()=>({commands:t})=>t.setMark(this.name),toggleBold:()=>({commands:t})=>t.toggleMark(this.name),unsetBold:()=>({commands:t})=>t.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-b":()=>this.editor.commands.toggleBold(),"Mod-B":()=>this.editor.commands.toggleBold()}},addInputRules(){return[ej({find:Yqe,type:this.type}),ej({find:Qqe,type:this.type})]},addPasteRules(){return[H_({find:Xqe,type:this.type}),H_({find:Jqe,type:this.type})]}}),tHe="listItem",NJ="textStyle",CJ=/^\s*([-+*])\s$/,rHe=Af.create({name:"bulletList",addOptions(){return{itemTypeName:"listItem",HTMLAttributes:{},keepMarks:!1,keepAttributes:!1}},group:"block list",content(){return`${this.options.itemTypeName}+`},parseHTML(){return[{tag:"ul"}]},renderHTML({HTMLAttributes:t}){return["ul",Ql(this.options.HTMLAttributes,t),0]},addCommands(){return{toggleBulletList:()=>({commands:t,chain:e})=>this.options.keepAttributes?e().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes(tHe,this.editor.getAttributes(NJ)).run():t.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-8":()=>this.editor.commands.toggleBulletList()}},addInputRules(){let t=vk({find:CJ,type:this.type});return(this.options.keepMarks||this.options.keepAttributes)&&(t=vk({find:CJ,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:()=>this.editor.getAttributes(NJ),editor:this.editor})),[t]}}),nHe=/(^|[^`])`([^`]+)`(?!`)/,sHe=/(^|[^`])`([^`]+)`(?!`)/g,iHe=Ep.create({name:"code",addOptions(){return{HTMLAttributes:{}}},excludes:"_",code:!0,exitable:!0,parseHTML(){return[{tag:"code"}]},renderHTML({HTMLAttributes:t}){return["code",Ql(this.options.HTMLAttributes,t),0]},addCommands(){return{setCode:()=>({commands:t})=>t.setMark(this.name),toggleCode:()=>({commands:t})=>t.toggleMark(this.name),unsetCode:()=>({commands:t})=>t.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-e":()=>this.editor.commands.toggleCode()}},addInputRules(){return[ej({find:nHe,type:this.type})]},addPasteRules(){return[H_({find:sHe,type:this.type})]}}),aHe=/^```([a-z]+)?[\s\n]$/,oHe=/^~~~([a-z]+)?[\s\n]$/,lHe=Af.create({name:"codeBlock",addOptions(){return{languageClassPrefix:"language-",exitOnTripleEnter:!0,exitOnArrowDown:!0,defaultLanguage:null,HTMLAttributes:{}}},content:"text*",marks:"",group:"block",code:!0,defining:!0,addAttributes(){return{language:{default:this.options.defaultLanguage,parseHTML:t=>{var e;const{languageClassPrefix:r}=this.options,o=[...((e=t.firstElementChild)===null||e===void 0?void 0:e.classList)||[]].filter(c=>c.startsWith(r)).map(c=>c.replace(r,""))[0];return o||null},rendered:!1}}},parseHTML(){return[{tag:"pre",preserveWhitespace:"full"}]},renderHTML({node:t,HTMLAttributes:e}){return["pre",Ql(this.options.HTMLAttributes,e),["code",{class:t.attrs.language?this.options.languageClassPrefix+t.attrs.language:null},0]]},addCommands(){return{setCodeBlock:t=>({commands:e})=>e.setNode(this.name,t),toggleCodeBlock:t=>({commands:e})=>e.toggleNode(this.name,"paragraph",t)}},addKeyboardShortcuts(){return{"Mod-Alt-c":()=>this.editor.commands.toggleCodeBlock(),Backspace:()=>{const{empty:t,$anchor:e}=this.editor.state.selection,r=e.pos===1;return!t||e.parent.type.name!==this.name?!1:r||!e.parent.textContent.length?this.editor.commands.clearNodes():!1},Enter:({editor:t})=>{if(!this.options.exitOnTripleEnter)return!1;const{state:e}=t,{selection:r}=e,{$from:n,empty:i}=r;if(!i||n.parent.type!==this.type)return!1;const o=n.parentOffset===n.parent.nodeSize-2,c=n.parent.textContent.endsWith(` `);return!o||!c?!1:t.chain().command(({tr:a})=>(a.delete(n.pos-2,n.pos),!0)).exitCode().run()},ArrowDown:({editor:t})=>{if(!this.options.exitOnArrowDown)return!1;const{state:e}=t,{selection:r,doc:n}=e,{$from:i,empty:o}=r;if(!o||i.parent.type!==this.type||!(i.parentOffset===i.parent.nodeSize-2))return!1;const a=i.after();return a===void 0?!1:n.nodeAt(a)?t.commands.command(({tr:g})=>(g.setSelection(Pi.near(n.resolve(a))),!0)):t.commands.exitCode()}}},addInputRules(){return[iU({find:aHe,type:this.type,getAttributes:t=>({language:t[1]})}),iU({find:oHe,type:this.type,getAttributes:t=>({language:t[1]})})]},addProseMirrorPlugins(){return[new wc({key:new kd("codeBlockVSCodeHandler"),props:{handlePaste:(t,e)=>{if(!e.clipboardData||this.editor.isActive(this.type.name))return!1;const r=e.clipboardData.getData("text/plain"),n=e.clipboardData.getData("vscode-editor-data"),i=n?JSON.parse(n):void 0,o=i==null?void 0:i.mode;if(!r||!o)return!1;const{tr:c,schema:a}=t.state,m=a.text(r.replace(/\r\n?/g,` `));return c.replaceSelectionWith(this.type.create({language:o},m)),c.selection.$from.parent.type!==this.type&&c.setSelection(li.near(c.doc.resolve(Math.max(0,c.selection.from-2)))),c.setMeta("paste",!0),t.dispatch(c),!0}}})]}}),cHe=Af.create({name:"doc",topNode:!0,content:"block+"});function uHe(t={}){return new wc({view(e){return new dHe(e,t)}})}class dHe{constructor(e,r){var n;this.editorView=e,this.cursorPos=null,this.element=null,this.timeout=-1,this.width=(n=r.width)!==null&&n!==void 0?n:1,this.color=r.color===!1?void 0:r.color||"black",this.class=r.class,this.handlers=["dragover","dragend","drop","dragleave"].map(i=>{let o=c=>{this[i](c)};return e.dom.addEventListener(i,o),{name:i,handler:o}})}destroy(){this.handlers.forEach(({name:e,handler:r})=>this.editorView.dom.removeEventListener(e,r))}update(e,r){this.cursorPos!=null&&r.doc!=e.state.doc&&(this.cursorPos>e.state.doc.content.size?this.setCursor(null):this.updateOverlay())}setCursor(e){e!=this.cursorPos&&(this.cursorPos=e,e==null?(this.element.parentNode.removeChild(this.element),this.element=null):this.updateOverlay())}updateOverlay(){let e=this.editorView.state.doc.resolve(this.cursorPos),r=!e.parent.inlineContent,n,i=this.editorView.dom,o=i.getBoundingClientRect(),c=o.width/i.offsetWidth,a=o.height/i.offsetHeight;if(r){let j=e.nodeBefore,N=e.nodeAfter;if(j||N){let C=this.editorView.nodeDOM(this.cursorPos-(j?j.nodeSize:0));if(C){let P=C.getBoundingClientRect(),A=j?P.bottom:P.top;j&&N&&(A=(A+this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top)/2);let I=this.width/2*a;n={left:P.left,right:P.right,top:A-I,bottom:A+I}}}}if(!n){let j=this.editorView.coordsAtPos(this.cursorPos),N=this.width/2*c;n={left:j.left-N,right:j.left+N,top:j.top,bottom:j.bottom}}let m=this.editorView.dom.offsetParent;this.element||(this.element=m.appendChild(document.createElement("div")),this.class&&(this.element.className=this.class),this.element.style.cssText="position: absolute; z-index: 50; pointer-events: none;",this.color&&(this.element.style.backgroundColor=this.color)),this.element.classList.toggle("prosemirror-dropcursor-block",r),this.element.classList.toggle("prosemirror-dropcursor-inline",!r);let g,_;if(!m||m==document.body&&getComputedStyle(m).position=="static")g=-pageXOffset,_=-pageYOffset;else{let j=m.getBoundingClientRect(),N=j.width/m.offsetWidth,C=j.height/m.offsetHeight;g=j.left-m.scrollLeft*N,_=j.top-m.scrollTop*C}this.element.style.left=(n.left-g)/c+"px",this.element.style.top=(n.top-_)/a+"px",this.element.style.width=(n.right-n.left)/c+"px",this.element.style.height=(n.bottom-n.top)/a+"px"}scheduleRemoval(e){clearTimeout(this.timeout),this.timeout=setTimeout(()=>this.setCursor(null),e)}dragover(e){if(!this.editorView.editable)return;let r=this.editorView.posAtCoords({left:e.clientX,top:e.clientY}),n=r&&r.inside>=0&&this.editorView.state.doc.nodeAt(r.inside),i=n&&n.type.spec.disableDropCursor,o=typeof i=="function"?i(this.editorView,r,e):i;if(r&&!o){let c=r.pos;if(this.editorView.dragging&&this.editorView.dragging.slice){let a=Vme(this.editorView.state.doc,c,this.editorView.dragging.slice);a!=null&&(c=a)}this.setCursor(c),this.scheduleRemoval(5e3)}}dragend(){this.scheduleRemoval(20)}drop(){this.scheduleRemoval(20)}dragleave(e){this.editorView.dom.contains(e.relatedTarget)||this.setCursor(null)}}const hHe=bc.create({name:"dropCursor",addOptions(){return{color:"currentColor",width:1,class:void 0}},addProseMirrorPlugins(){return[uHe(this.options)]}});class Mo extends Pi{constructor(e){super(e,e)}map(e,r){let n=e.resolve(r.map(this.head));return Mo.valid(n)?new Mo(n):Pi.near(n)}content(){return Ln.empty}eq(e){return e instanceof Mo&&e.head==this.head}toJSON(){return{type:"gapcursor",pos:this.head}}static fromJSON(e,r){if(typeof r.pos!="number")throw new RangeError("Invalid input for GapCursor.fromJSON");return new Mo(e.resolve(r.pos))}getBookmark(){return new aH(this.anchor)}static valid(e){let r=e.parent;if(r.isTextblock||!fHe(e)||!pHe(e))return!1;let n=r.type.spec.allowGapCursor;if(n!=null)return n;let i=r.contentMatchAt(e.index()).defaultType;return i&&i.isTextblock}static findGapCursorFrom(e,r,n=!1){e:for(;;){if(!n&&Mo.valid(e))return e;let i=e.pos,o=null;for(let c=e.depth;;c--){let a=e.node(c);if(r>0?e.indexAfter(c)0){o=a.child(r>0?e.indexAfter(c):e.index(c)-1);break}else if(c==0)return null;i+=r;let m=e.doc.resolve(i);if(Mo.valid(m))return m}for(;;){let c=r>0?o.firstChild:o.lastChild;if(!c){if(o.isAtom&&!o.isText&&!js.isSelectable(o)){e=e.doc.resolve(i+o.nodeSize*r),n=!1;continue e}break}o=c,i+=r;let a=e.doc.resolve(i);if(Mo.valid(a))return a}return null}}}Mo.prototype.visible=!1;Mo.findFrom=Mo.findGapCursorFrom;Pi.jsonID("gapcursor",Mo);class aH{constructor(e){this.pos=e}map(e){return new aH(e.map(this.pos))}resolve(e){let r=e.resolve(this.pos);return Mo.valid(r)?new Mo(r):Pi.near(r)}}function aye(t){return t.isAtom||t.spec.isolating||t.spec.createGapCursor}function fHe(t){for(let e=t.depth;e>=0;e--){let r=t.index(e),n=t.node(e);if(r==0){if(n.type.spec.isolating)return!0;continue}for(let i=n.child(r-1);;i=i.lastChild){if(i.childCount==0&&!i.inlineContent||aye(i.type))return!0;if(i.inlineContent)return!1}}return!0}function pHe(t){for(let e=t.depth;e>=0;e--){let r=t.indexAfter(e),n=t.node(e);if(r==n.childCount){if(n.type.spec.isolating)return!0;continue}for(let i=n.child(r);;i=i.firstChild){if(i.childCount==0&&!i.inlineContent||aye(i.type))return!0;if(i.inlineContent)return!1}}return!0}function mHe(){return new wc({props:{decorations:vHe,createSelectionBetween(t,e,r){return e.pos==r.pos&&Mo.valid(r)?new Mo(r):null},handleClick:yHe,handleKeyDown:gHe,handleDOMEvents:{beforeinput:xHe}}})}const gHe=Ige({ArrowLeft:BP("horiz",-1),ArrowRight:BP("horiz",1),ArrowUp:BP("vert",-1),ArrowDown:BP("vert",1)});function BP(t,e){const r=t=="vert"?e>0?"down":"up":e>0?"right":"left";return function(n,i,o){let c=n.selection,a=e>0?c.$to:c.$from,m=c.empty;if(c instanceof li){if(!o.endOfTextblock(r)||a.depth==0)return!1;m=!1,a=n.doc.resolve(e>0?a.after():a.before())}let g=Mo.findGapCursorFrom(a,e,m);return g?(i&&i(n.tr.setSelection(new Mo(g))),!0):!1}}function yHe(t,e,r){if(!t||!t.editable)return!1;let n=t.state.doc.resolve(e);if(!Mo.valid(n))return!1;let i=t.posAtCoords({left:r.clientX,top:r.clientY});return i&&i.inside>-1&&js.isSelectable(t.state.doc.nodeAt(i.inside))?!1:(t.dispatch(t.state.tr.setSelection(new Mo(n))),!0)}function xHe(t,e){if(e.inputType!="insertCompositionText"||!(t.state.selection instanceof Mo))return!1;let{$from:r}=t.state.selection,n=r.parent.contentMatchAt(r.index()).findWrapping(t.state.schema.nodes.text);if(!n)return!1;let i=Qr.empty;for(let c=n.length-1;c>=0;c--)i=Qr.from(n[c].createAndFill(null,i));let o=t.state.tr.replace(r.pos,r.pos,new Ln(i,0,0));return o.setSelection(li.near(o.doc.resolve(r.pos+1))),t.dispatch(o),!1}function vHe(t){if(!(t.selection instanceof Mo))return null;let e=document.createElement("div");return e.className="ProseMirror-gapcursor",Cl.create(t.doc,[ih.widget(t.selection.head,e,{key:"gapcursor"})])}const _He=bc.create({name:"gapCursor",addProseMirrorPlugins(){return[mHe()]},extendNodeSchema(t){var e;const r={name:t.name,options:t.options,storage:t.storage};return{allowGapCursor:(e=Oi(Jn(t,"allowGapCursor",r)))!==null&&e!==void 0?e:null}}}),bHe=Af.create({name:"hardBreak",addOptions(){return{keepMarks:!0,HTMLAttributes:{}}},inline:!0,group:"inline",selectable:!1,linebreakReplacement:!0,parseHTML(){return[{tag:"br"}]},renderHTML({HTMLAttributes:t}){return["br",Ql(this.options.HTMLAttributes,t)]},renderText(){return` `},addCommands(){return{setHardBreak:()=>({commands:t,chain:e,state:r,editor:n})=>t.first([()=>t.exitCode(),()=>t.command(()=>{const{selection:i,storedMarks:o}=r;if(i.$from.parent.type.spec.isolating)return!1;const{keepMarks:c}=this.options,{splittableMarks:a}=n.extensionManager,m=o||i.$to.parentOffset&&i.$from.marks();return e().insertContent({type:this.name}).command(({tr:g,dispatch:_})=>{if(_&&m&&c){const j=m.filter(N=>a.includes(N.type.name));g.ensureMarks(j)}return!0}).run()})])}},addKeyboardShortcuts(){return{"Mod-Enter":()=>this.editor.commands.setHardBreak(),"Shift-Enter":()=>this.editor.commands.setHardBreak()}}}),wHe=Af.create({name:"heading",addOptions(){return{levels:[1,2,3,4,5,6],HTMLAttributes:{}}},content:"inline*",group:"block",defining:!0,addAttributes(){return{level:{default:1,rendered:!1}}},parseHTML(){return this.options.levels.map(t=>({tag:`h${t}`,attrs:{level:t}}))},renderHTML({node:t,HTMLAttributes:e}){return[`h${this.options.levels.includes(t.attrs.level)?t.attrs.level:this.options.levels[0]}`,Ql(this.options.HTMLAttributes,e),0]},addCommands(){return{setHeading:t=>({commands:e})=>this.options.levels.includes(t.level)?e.setNode(this.name,t):!1,toggleHeading:t=>({commands:e})=>this.options.levels.includes(t.level)?e.toggleNode(this.name,"paragraph",t):!1}},addKeyboardShortcuts(){return this.options.levels.reduce((t,e)=>({...t,[`Mod-Alt-${e}`]:()=>this.editor.commands.toggleHeading({level:e})}),{})},addInputRules(){return this.options.levels.map(t=>iU({find:new RegExp(`^(#{${Math.min(...this.options.levels)},${t}})\\s$`),type:this.type,getAttributes:{level:t}}))}});var oO=200,Zl=function(){};Zl.prototype.append=function(e){return e.length?(e=Zl.from(e),!this.length&&e||e.length=r?Zl.empty:this.sliceInner(Math.max(0,e),Math.min(this.length,r))};Zl.prototype.get=function(e){if(!(e<0||e>=this.length))return this.getInner(e)};Zl.prototype.forEach=function(e,r,n){r===void 0&&(r=0),n===void 0&&(n=this.length),r<=n?this.forEachInner(e,r,n,0):this.forEachInvertedInner(e,r,n,0)};Zl.prototype.map=function(e,r,n){r===void 0&&(r=0),n===void 0&&(n=this.length);var i=[];return this.forEach(function(o,c){return i.push(e(o,c))},r,n),i};Zl.from=function(e){return e instanceof Zl?e:e&&e.length?new oye(e):Zl.empty};var oye=function(t){function e(n){t.call(this),this.values=n}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={length:{configurable:!0},depth:{configurable:!0}};return e.prototype.flatten=function(){return this.values},e.prototype.sliceInner=function(i,o){return i==0&&o==this.length?this:new e(this.values.slice(i,o))},e.prototype.getInner=function(i){return this.values[i]},e.prototype.forEachInner=function(i,o,c,a){for(var m=o;m=c;m--)if(i(this.values[m],a+m)===!1)return!1},e.prototype.leafAppend=function(i){if(this.length+i.length<=oO)return new e(this.values.concat(i.flatten()))},e.prototype.leafPrepend=function(i){if(this.length+i.length<=oO)return new e(i.flatten().concat(this.values))},r.length.get=function(){return this.values.length},r.depth.get=function(){return 0},Object.defineProperties(e.prototype,r),e}(Zl);Zl.empty=new oye([]);var jHe=function(t){function e(r,n){t.call(this),this.left=r,this.right=n,this.length=r.length+n.length,this.depth=Math.max(r.depth,n.depth)+1}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.flatten=function(){return this.left.flatten().concat(this.right.flatten())},e.prototype.getInner=function(n){return na&&this.right.forEachInner(n,Math.max(i-a,0),Math.min(this.length,o)-a,c+a)===!1)return!1},e.prototype.forEachInvertedInner=function(n,i,o,c){var a=this.left.length;if(i>a&&this.right.forEachInvertedInner(n,i-a,Math.max(o,a)-a,c+a)===!1||o=o?this.right.slice(n-o,i-o):this.left.slice(n,o).append(this.right.slice(0,i-o))},e.prototype.leafAppend=function(n){var i=this.right.leafAppend(n);if(i)return new e(this.left,i)},e.prototype.leafPrepend=function(n){var i=this.left.leafPrepend(n);if(i)return new e(i,this.right)},e.prototype.appendInner=function(n){return this.left.depth>=Math.max(this.right.depth,n.depth)+1?new e(this.left,new e(this.right,n)):new e(this,n)},e}(Zl);const SHe=500;class ff{constructor(e,r){this.items=e,this.eventCount=r}popEvent(e,r){if(this.eventCount==0)return null;let n=this.items.length;for(;;n--)if(this.items.get(n-1).selection){--n;break}let i,o;r&&(i=this.remapping(n,this.items.length),o=i.maps.length);let c=e.tr,a,m,g=[],_=[];return this.items.forEach((j,N)=>{if(!j.step){i||(i=this.remapping(n,N+1),o=i.maps.length),o--,_.push(j);return}if(i){_.push(new np(j.map));let C=j.step.map(i.slice(o)),P;C&&c.maybeStep(C).doc&&(P=c.mapping.maps[c.mapping.maps.length-1],g.push(new np(P,void 0,void 0,g.length+_.length))),o--,P&&i.appendMap(P,o)}else c.maybeStep(j.step);if(j.selection)return a=i?j.selection.map(i.slice(o)):j.selection,m=new ff(this.items.slice(0,n).append(_.reverse().concat(g)),this.eventCount-1),!1},this.items.length,0),{remaining:m,transform:c,selection:a}}addTransform(e,r,n,i){let o=[],c=this.eventCount,a=this.items,m=!i&&a.length?a.get(a.length-1):null;for(let _=0;_CHe&&(a=NHe(a,g),c-=g),new ff(a.append(o),c)}remapping(e,r){let n=new hk;return this.items.forEach((i,o)=>{let c=i.mirrorOffset!=null&&o-i.mirrorOffset>=e?n.maps.length-i.mirrorOffset:void 0;n.appendMap(i.map,c)},e,r),n}addMaps(e){return this.eventCount==0?this:new ff(this.items.append(e.map(r=>new np(r))),this.eventCount)}rebased(e,r){if(!this.eventCount)return this;let n=[],i=Math.max(0,this.items.length-r),o=e.mapping,c=e.steps.length,a=this.eventCount;this.items.forEach(N=>{N.selection&&a--},i);let m=r;this.items.forEach(N=>{let C=o.getMirror(--m);if(C==null)return;c=Math.min(c,C);let P=o.maps[C];if(N.step){let A=e.steps[C].invert(e.docs[C]),I=N.selection&&N.selection.map(o.slice(m+1,C));I&&a++,n.push(new np(P,A,I))}else n.push(new np(P))},i);let g=[];for(let N=r;NSHe&&(j=j.compress(this.items.length-n.length)),j}emptyItemCount(){let e=0;return this.items.forEach(r=>{r.step||e++}),e}compress(e=this.items.length){let r=this.remapping(0,e),n=r.maps.length,i=[],o=0;return this.items.forEach((c,a)=>{if(a>=e)i.push(c),c.selection&&o++;else if(c.step){let m=c.step.map(r.slice(n)),g=m&&m.getMap();if(n--,g&&r.appendMap(g,n),m){let _=c.selection&&c.selection.map(r.slice(n));_&&o++;let j=new np(g.invert(),m,_),N,C=i.length-1;(N=i.length&&i[C].merge(j))?i[C]=N:i.push(j)}}else c.map&&n--},this.items.length,0),new ff(Zl.from(i.reverse()),o)}}ff.empty=new ff(Zl.empty,0);function NHe(t,e){let r;return t.forEach((n,i)=>{if(n.selection&&e--==0)return r=i,!1}),t.slice(r)}class np{constructor(e,r,n,i){this.map=e,this.step=r,this.selection=n,this.mirrorOffset=i}merge(e){if(this.step&&e.step&&!e.selection){let r=e.step.merge(this.step);if(r)return new np(r.getMap().invert(),r,this.selection)}}}class ly{constructor(e,r,n,i,o){this.done=e,this.undone=r,this.prevRanges=n,this.prevTime=i,this.prevComposition=o}}const CHe=20;function kHe(t,e,r,n){let i=r.getMeta(b_),o;if(i)return i.historyState;r.getMeta(AHe)&&(t=new ly(t.done,t.undone,null,0,-1));let c=r.getMeta("appendedTransaction");if(r.steps.length==0)return t;if(c&&c.getMeta(b_))return c.getMeta(b_).redo?new ly(t.done.addTransform(r,void 0,n,DI(e)),t.undone,kJ(r.mapping.maps),t.prevTime,t.prevComposition):new ly(t.done,t.undone.addTransform(r,void 0,n,DI(e)),null,t.prevTime,t.prevComposition);if(r.getMeta("addToHistory")!==!1&&!(c&&c.getMeta("addToHistory")===!1)){let a=r.getMeta("composition"),m=t.prevTime==0||!c&&t.prevComposition!=a&&(t.prevTime<(r.time||0)-n.newGroupDelay||!THe(r,t.prevRanges)),g=c?Lz(t.prevRanges,r.mapping):kJ(r.mapping.maps);return new ly(t.done.addTransform(r,m?e.selection.getBookmark():void 0,n,DI(e)),ff.empty,g,r.time,a??t.prevComposition)}else return(o=r.getMeta("rebased"))?new ly(t.done.rebased(r,o),t.undone.rebased(r,o),Lz(t.prevRanges,r.mapping),t.prevTime,t.prevComposition):new ly(t.done.addMaps(r.mapping.maps),t.undone.addMaps(r.mapping.maps),Lz(t.prevRanges,r.mapping),t.prevTime,t.prevComposition)}function THe(t,e){if(!e)return!1;if(!t.docChanged)return!0;let r=!1;return t.mapping.maps[0].forEach((n,i)=>{for(let o=0;o=e[o]&&(r=!0)}),r}function kJ(t){let e=[];for(let r=t.length-1;r>=0&&e.length==0;r--)t[r].forEach((n,i,o,c)=>e.push(o,c));return e}function Lz(t,e){if(!t)return null;let r=[];for(let n=0;n{let i=b_.getState(r);if(!i||(t?i.undone:i.done).eventCount==0)return!1;if(n){let o=EHe(i,r,t);o&&n(e?o.scrollIntoView():o)}return!0}}const cye=lye(!1,!0),uye=lye(!0,!0),IHe=bc.create({name:"history",addOptions(){return{depth:100,newGroupDelay:500}},addCommands(){return{undo:()=>({state:t,dispatch:e})=>cye(t,e),redo:()=>({state:t,dispatch:e})=>uye(t,e)}},addProseMirrorPlugins(){return[PHe(this.options)]},addKeyboardShortcuts(){return{"Mod-z":()=>this.editor.commands.undo(),"Shift-Mod-z":()=>this.editor.commands.redo(),"Mod-y":()=>this.editor.commands.redo(),"Mod-я":()=>this.editor.commands.undo(),"Shift-Mod-я":()=>this.editor.commands.redo()}}}),MHe=Af.create({name:"horizontalRule",addOptions(){return{HTMLAttributes:{}}},group:"block",parseHTML(){return[{tag:"hr"}]},renderHTML({HTMLAttributes:t}){return["hr",Ql(this.options.HTMLAttributes,t)]},addCommands(){return{setHorizontalRule:()=>({chain:t,state:e})=>{if(!Tqe(e,e.schema.nodes[this.name]))return!1;const{selection:r}=e,{$from:n,$to:i}=r,o=t();return n.parentOffset===0?o.insertContentAt({from:Math.max(n.pos-1,0),to:i.pos},{type:this.name}):Z8e(r)?o.insertContentAt(i.pos,{type:this.name}):o.insertContent({type:this.name}),o.command(({tr:c,dispatch:a})=>{var m;if(a){const{$to:g}=c.selection,_=g.end();if(g.nodeAfter)g.nodeAfter.isTextblock?c.setSelection(li.create(c.doc,g.pos+1)):g.nodeAfter.isBlock?c.setSelection(js.create(c.doc,g.pos)):c.setSelection(li.create(c.doc,g.pos));else{const j=(m=g.parent.type.contentMatch.defaultType)===null||m===void 0?void 0:m.create();j&&(c.insert(_,j),c.setSelection(li.create(c.doc,_+1)))}c.scrollIntoView()}return!0}).run()}}},addInputRules(){return[kqe({find:/^(?:---|—-|___\s|\*\*\*\s)$/,type:this.type})]}}),OHe=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,RHe=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,DHe=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,LHe=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g,FHe=Ep.create({name:"italic",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"em"},{tag:"i",getAttrs:t=>t.style.fontStyle!=="normal"&&null},{style:"font-style=normal",clearMark:t=>t.type.name===this.name},{style:"font-style=italic"}]},renderHTML({HTMLAttributes:t}){return["em",Ql(this.options.HTMLAttributes,t),0]},addCommands(){return{setItalic:()=>({commands:t})=>t.setMark(this.name),toggleItalic:()=>({commands:t})=>t.toggleMark(this.name),unsetItalic:()=>({commands:t})=>t.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-i":()=>this.editor.commands.toggleItalic(),"Mod-I":()=>this.editor.commands.toggleItalic()}},addInputRules(){return[ej({find:OHe,type:this.type}),ej({find:DHe,type:this.type})]},addPasteRules(){return[H_({find:RHe,type:this.type}),H_({find:LHe,type:this.type})]}}),zHe=Af.create({name:"listItem",addOptions(){return{HTMLAttributes:{},bulletListTypeName:"bulletList",orderedListTypeName:"orderedList"}},content:"paragraph block*",defining:!0,parseHTML(){return[{tag:"li"}]},renderHTML({HTMLAttributes:t}){return["li",Ql(this.options.HTMLAttributes,t),0]},addKeyboardShortcuts(){return{Enter:()=>this.editor.commands.splitListItem(this.name),Tab:()=>this.editor.commands.sinkListItem(this.name),"Shift-Tab":()=>this.editor.commands.liftListItem(this.name)}}}),BHe="listItem",EJ="textStyle",AJ=/^(\d+)\.\s$/,$He=Af.create({name:"orderedList",addOptions(){return{itemTypeName:"listItem",HTMLAttributes:{},keepMarks:!1,keepAttributes:!1}},group:"block list",content(){return`${this.options.itemTypeName}+`},addAttributes(){return{start:{default:1,parseHTML:t=>t.hasAttribute("start")?parseInt(t.getAttribute("start")||"",10):1},type:{default:null,parseHTML:t=>t.getAttribute("type")}}},parseHTML(){return[{tag:"ol"}]},renderHTML({HTMLAttributes:t}){const{start:e,...r}=t;return e===1?["ol",Ql(this.options.HTMLAttributes,r),0]:["ol",Ql(this.options.HTMLAttributes,t),0]},addCommands(){return{toggleOrderedList:()=>({commands:t,chain:e})=>this.options.keepAttributes?e().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes(BHe,this.editor.getAttributes(EJ)).run():t.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-7":()=>this.editor.commands.toggleOrderedList()}},addInputRules(){let t=vk({find:AJ,type:this.type,getAttributes:e=>({start:+e[1]}),joinPredicate:(e,r)=>r.childCount+r.attrs.start===+e[1]});return(this.options.keepMarks||this.options.keepAttributes)&&(t=vk({find:AJ,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:e=>({start:+e[1],...this.editor.getAttributes(EJ)}),joinPredicate:(e,r)=>r.childCount+r.attrs.start===+e[1],editor:this.editor})),[t]}}),UHe=Af.create({name:"paragraph",priority:1e3,addOptions(){return{HTMLAttributes:{}}},group:"block",content:"inline*",parseHTML(){return[{tag:"p"}]},renderHTML({HTMLAttributes:t}){return["p",Ql(this.options.HTMLAttributes,t),0]},addCommands(){return{setParagraph:()=>({commands:t})=>t.setNode(this.name)}},addKeyboardShortcuts(){return{"Mod-Alt-0":()=>this.editor.commands.setParagraph()}}}),VHe=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/,qHe=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g,HHe=Ep.create({name:"strike",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"s"},{tag:"del"},{tag:"strike"},{style:"text-decoration",consuming:!1,getAttrs:t=>t.includes("line-through")?{}:!1}]},renderHTML({HTMLAttributes:t}){return["s",Ql(this.options.HTMLAttributes,t),0]},addCommands(){return{setStrike:()=>({commands:t})=>t.setMark(this.name),toggleStrike:()=>({commands:t})=>t.toggleMark(this.name),unsetStrike:()=>({commands:t})=>t.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-s":()=>this.editor.commands.toggleStrike()}},addInputRules(){return[ej({find:VHe,type:this.type})]},addPasteRules(){return[H_({find:qHe,type:this.type})]}}),WHe=Af.create({name:"text",group:"inline"}),dye=bc.create({name:"starterKit",addExtensions(){const t=[];return this.options.bold!==!1&&t.push(eHe.configure(this.options.bold)),this.options.blockquote!==!1&&t.push(Zqe.configure(this.options.blockquote)),this.options.bulletList!==!1&&t.push(rHe.configure(this.options.bulletList)),this.options.code!==!1&&t.push(iHe.configure(this.options.code)),this.options.codeBlock!==!1&&t.push(lHe.configure(this.options.codeBlock)),this.options.document!==!1&&t.push(cHe.configure(this.options.document)),this.options.dropcursor!==!1&&t.push(hHe.configure(this.options.dropcursor)),this.options.gapcursor!==!1&&t.push(_He.configure(this.options.gapcursor)),this.options.hardBreak!==!1&&t.push(bHe.configure(this.options.hardBreak)),this.options.heading!==!1&&t.push(wHe.configure(this.options.heading)),this.options.history!==!1&&t.push(IHe.configure(this.options.history)),this.options.horizontalRule!==!1&&t.push(MHe.configure(this.options.horizontalRule)),this.options.italic!==!1&&t.push(FHe.configure(this.options.italic)),this.options.listItem!==!1&&t.push(zHe.configure(this.options.listItem)),this.options.orderedList!==!1&&t.push($He.configure(this.options.orderedList)),this.options.paragraph!==!1&&t.push(UHe.configure(this.options.paragraph)),this.options.strike!==!1&&t.push(HHe.configure(this.options.strike)),this.options.text!==!1&&t.push(WHe.configure(this.options.text)),t}}),GHe="aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3nlop4pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2o0dyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rckmsd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0stone5umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5mögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2olterskluwer11odside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2",KHe="ελ1υ2бг1ел3дети4ею2католик6ом3мкд2он1сква6онлайн5рг3рус2ф2сайт3рб3укр3қаз3հայ3ישראל5קום3ابوظبي5رامكو5لاردن4بحرين5جزائر5سعودية6عليان5مغرب5مارات5یران5بارت2زار4يتك3ھارت5تونس4سودان3رية5شبكة4عراق2ب2مان4فلسطين6قطر3كاثوليك6وم3مصر2ليسيا5وريتانيا7قع4همراه5پاکستان7ڀارت4कॉम3नेट3भारत0म्3ोत5संगठन5বাংলা5ভারত2ৰত4ਭਾਰਤ4ભારત4ଭାରତ4இந்தியா6லங்கை6சிங்கப்பூர்11భారత్5ಭಾರತ4ഭാരതം5ලංකා4คอม3ไทย3ລາວ3გე2みんな3アマゾン4クラウド4グーグル4コム2ストア3セール3ファッション6ポイント4世界2中信1国1國1文网3亚马逊3企业2佛山2信息2健康2八卦2公司1益2台湾1灣2商城1店1标2嘉里0大酒店5在线2大拿2天主教3娱乐2家電2广东2微博2慈善2我爱你3手机2招聘2政务1府2新加坡2闻2时尚2書籍2机构2淡马锡3游戏2澳門2点看2移动2组织机构4网址1店1站1络2联通2谷歌2购物2通販2集团2電訊盈科4飞利浦3食品2餐厅2香格里拉3港2닷넷1컴2삼성2한국2",lU="numeric",cU="ascii",uU="alpha",g2="asciinumeric",HC="alphanumeric",dU="domain",hye="emoji",ZHe="scheme",YHe="slashscheme",zz="whitespace";function XHe(t,e){return t in e||(e[t]=[]),e[t]}function Jv(t,e,r){e[lU]&&(e[g2]=!0,e[HC]=!0),e[cU]&&(e[g2]=!0,e[uU]=!0),e[g2]&&(e[HC]=!0),e[uU]&&(e[HC]=!0),e[HC]&&(e[dU]=!0),e[hye]&&(e[dU]=!0);for(const n in e){const i=XHe(n,r);i.indexOf(t)<0&&i.push(t)}}function QHe(t,e){const r={};for(const n in e)e[n].indexOf(t)>=0&&(r[n]=!0);return r}function Mu(t=null){this.j={},this.jr=[],this.jd=null,this.t=t}Mu.groups={};Mu.prototype={accepts(){return!!this.t},go(t){const e=this,r=e.j[t];if(r)return r;for(let n=0;nt.ta(e,r,n,i),Eo=(t,e,r,n,i)=>t.tr(e,r,n,i),PJ=(t,e,r,n,i)=>t.ts(e,r,n,i),nn=(t,e,r,n,i)=>t.tt(e,r,n,i),vm="WORD",hU="UWORD",fye="ASCIINUMERICAL",pye="ALPHANUMERICAL",_k="LOCALHOST",fU="TLD",pU="UTLD",LI="SCHEME",Cw="SLASH_SCHEME",oH="NUM",mU="WS",lH="NL",y2="OPENBRACE",x2="CLOSEBRACE",lO="OPENBRACKET",cO="CLOSEBRACKET",uO="OPENPAREN",dO="CLOSEPAREN",hO="OPENANGLEBRACKET",fO="CLOSEANGLEBRACKET",pO="FULLWIDTHLEFTPAREN",mO="FULLWIDTHRIGHTPAREN",gO="LEFTCORNERBRACKET",yO="RIGHTCORNERBRACKET",xO="LEFTWHITECORNERBRACKET",vO="RIGHTWHITECORNERBRACKET",_O="FULLWIDTHLESSTHAN",bO="FULLWIDTHGREATERTHAN",wO="AMPERSAND",jO="APOSTROPHE",SO="ASTERISK",cy="AT",NO="BACKSLASH",CO="BACKTICK",kO="CARET",gy="COLON",cH="COMMA",TO="DOLLAR",sp="DOT",EO="EQUALS",uH="EXCLAMATION",Kd="HYPHEN",v2="PERCENT",AO="PIPE",PO="PLUS",IO="POUND",_2="QUERY",dH="QUOTE",mye="FULLWIDTHMIDDLEDOT",hH="SEMI",ip="SLASH",b2="TILDE",MO="UNDERSCORE",gye="EMOJI",OO="SYM";var yye=Object.freeze({__proto__:null,ALPHANUMERICAL:pye,AMPERSAND:wO,APOSTROPHE:jO,ASCIINUMERICAL:fye,ASTERISK:SO,AT:cy,BACKSLASH:NO,BACKTICK:CO,CARET:kO,CLOSEANGLEBRACKET:fO,CLOSEBRACE:x2,CLOSEBRACKET:cO,CLOSEPAREN:dO,COLON:gy,COMMA:cH,DOLLAR:TO,DOT:sp,EMOJI:gye,EQUALS:EO,EXCLAMATION:uH,FULLWIDTHGREATERTHAN:bO,FULLWIDTHLEFTPAREN:pO,FULLWIDTHLESSTHAN:_O,FULLWIDTHMIDDLEDOT:mye,FULLWIDTHRIGHTPAREN:mO,HYPHEN:Kd,LEFTCORNERBRACKET:gO,LEFTWHITECORNERBRACKET:xO,LOCALHOST:_k,NL:lH,NUM:oH,OPENANGLEBRACKET:hO,OPENBRACE:y2,OPENBRACKET:lO,OPENPAREN:uO,PERCENT:v2,PIPE:AO,PLUS:PO,POUND:IO,QUERY:_2,QUOTE:dH,RIGHTCORNERBRACKET:yO,RIGHTWHITECORNERBRACKET:vO,SCHEME:LI,SEMI:hH,SLASH:ip,SLASH_SCHEME:Cw,SYM:OO,TILDE:b2,TLD:fU,UNDERSCORE:MO,UTLD:pU,UWORD:hU,WORD:vm,WS:mU});const pm=/[a-z]/,_C=new RegExp("\\p{L}","u"),Bz=new RegExp("\\p{Emoji}","u"),mm=/\d/,$z=/\s/,IJ="\r",Uz=` `,JHe="️",eWe="‍",Vz="";let $P=null,UP=null;function tWe(t=[]){const e={};Mu.groups=e;const r=new Mu;$P==null&&($P=MJ(GHe)),UP==null&&(UP=MJ(KHe)),nn(r,"'",jO),nn(r,"{",y2),nn(r,"}",x2),nn(r,"[",lO),nn(r,"]",cO),nn(r,"(",uO),nn(r,")",dO),nn(r,"<",hO),nn(r,">",fO),nn(r,"(",pO),nn(r,")",mO),nn(r,"「",gO),nn(r,"」",yO),nn(r,"『",xO),nn(r,"』",vO),nn(r,"<",_O),nn(r,">",bO),nn(r,"&",wO),nn(r,"*",SO),nn(r,"@",cy),nn(r,"`",CO),nn(r,"^",kO),nn(r,":",gy),nn(r,",",cH),nn(r,"$",TO),nn(r,".",sp),nn(r,"=",EO),nn(r,"!",uH),nn(r,"-",Kd),nn(r,"%",v2),nn(r,"|",AO),nn(r,"+",PO),nn(r,"#",IO),nn(r,"?",_2),nn(r,'"',dH),nn(r,"/",ip),nn(r,";",hH),nn(r,"~",b2),nn(r,"_",MO),nn(r,"\\",NO),nn(r,"・",mye);const n=Eo(r,mm,oH,{[lU]:!0});Eo(n,mm,n);const i=Eo(n,pm,fye,{[g2]:!0}),o=Eo(n,_C,pye,{[HC]:!0}),c=Eo(r,pm,vm,{[cU]:!0});Eo(c,mm,i),Eo(c,pm,c),Eo(i,mm,i),Eo(i,pm,i);const a=Eo(r,_C,hU,{[uU]:!0});Eo(a,pm),Eo(a,mm,o),Eo(a,_C,a),Eo(o,mm,o),Eo(o,pm),Eo(o,_C,o);const m=nn(r,Uz,lH,{[zz]:!0}),g=nn(r,IJ,mU,{[zz]:!0}),_=Eo(r,$z,mU,{[zz]:!0});nn(r,Vz,_),nn(g,Uz,m),nn(g,Vz,_),Eo(g,$z,_),nn(_,IJ),nn(_,Uz),Eo(_,$z,_),nn(_,Vz,_);const j=Eo(r,Bz,gye,{[hye]:!0});nn(j,"#"),Eo(j,Bz,j),nn(j,JHe,j);const N=nn(j,eWe);nn(N,"#"),Eo(N,Bz,j);const C=[[pm,c],[mm,i]],P=[[pm,null],[_C,a],[mm,o]];for(let A=0;A<$P.length;A++)Xg(r,$P[A],fU,vm,C);for(let A=0;AA[0]>I[0]?1:-1);for(let A=0;A=0?R[dU]=!0:pm.test(I)?mm.test(I)?R[g2]=!0:R[cU]=!0:R[lU]=!0,PJ(r,I,I,R)}return PJ(r,"localhost",_k,{ascii:!0}),r.jd=new Mu(OO),{start:r,tokens:Object.assign({groups:e},yye)}}function xye(t,e){const r=rWe(e.replace(/[A-Z]/g,a=>a.toLowerCase())),n=r.length,i=[];let o=0,c=0;for(;c=0&&(j+=r[c].length,N++),g+=r[c].length,o+=r[c].length,c++;o-=j,c-=N,g-=j,i.push({t:_.t,v:e.slice(o-g,o),s:o-g,e:o})}return i}function rWe(t){const e=[],r=t.length;let n=0;for(;n56319||n+1===r||(o=t.charCodeAt(n+1))<56320||o>57343?t[n]:t.slice(n,n+2);e.push(c),n+=c.length}return e}function Xg(t,e,r,n,i){let o;const c=e.length;for(let a=0;a=0;)o++;if(o>0){e.push(r.join(""));for(let c=parseInt(t.substring(n,n+o),10);c>0;c--)r.pop();n+=o}else r.push(t[n]),n++}return e}const bk={defaultProtocol:"http",events:null,format:OJ,formatHref:OJ,nl2br:!1,tagName:"a",target:null,rel:null,validate:!0,truncate:1/0,className:null,attributes:null,ignoreTags:[],render:null};function fH(t,e=null){let r=Object.assign({},bk);t&&(r=Object.assign(r,t instanceof fH?t.o:t));const n=r.ignoreTags,i=[];for(let o=0;or?n.substring(0,r)+"…":n},toFormattedHref(t){return t.get("formatHref",this.toHref(t.get("defaultProtocol")),this)},startIndex(){return this.tk[0].s},endIndex(){return this.tk[this.tk.length-1].e},toObject(t=bk.defaultProtocol){return{type:this.t,value:this.toString(),isLink:this.isLink,href:this.toHref(t),start:this.startIndex(),end:this.endIndex()}},toFormattedObject(t){return{type:this.t,value:this.toFormattedString(t),isLink:this.isLink,href:this.toFormattedHref(t),start:this.startIndex(),end:this.endIndex()}},validate(t){return t.get("validate",this.toString(),this)},render(t){const e=this,r=this.toHref(t.get("defaultProtocol")),n=t.get("formatHref",r,this),i=t.get("tagName",r,e),o=this.toFormattedString(t),c={},a=t.get("className",r,e),m=t.get("target",r,e),g=t.get("rel",r,e),_=t.getObj("attributes",r,e),j=t.getObj("events",r,e);return c.href=n,a&&(c.class=a),m&&(c.target=m),g&&(c.rel=g),_&&Object.assign(c,_),{tagName:i,attributes:c,content:o,eventListeners:j}}};function aL(t,e){class r extends vye{constructor(i,o){super(i,o),this.t=t}}for(const n in e)r.prototype[n]=e[n];return r.t=t,r}const RJ=aL("email",{isLink:!0,toHref(){return"mailto:"+this.toString()}}),DJ=aL("text"),nWe=aL("nl"),VP=aL("url",{isLink:!0,toHref(t=bk.defaultProtocol){return this.hasProtocol()?this.v:`${t}://${this.v}`},hasProtocol(){const t=this.tk;return t.length>=2&&t[0].t!==_k&&t[1].t===gy}}),qd=t=>new Mu(t);function sWe({groups:t}){const e=t.domain.concat([wO,SO,cy,NO,CO,kO,TO,EO,Kd,oH,v2,AO,PO,IO,ip,OO,b2,MO]),r=[jO,gy,cH,sp,uH,v2,_2,dH,hH,hO,fO,y2,x2,cO,lO,uO,dO,pO,mO,gO,yO,xO,vO,_O,bO],n=[wO,jO,SO,NO,CO,kO,TO,EO,Kd,y2,x2,v2,AO,PO,IO,_2,ip,OO,b2,MO],i=qd(),o=nn(i,b2);Ai(o,n,o),Ai(o,t.domain,o);const c=qd(),a=qd(),m=qd();Ai(i,t.domain,c),Ai(i,t.scheme,a),Ai(i,t.slashscheme,m),Ai(c,n,o),Ai(c,t.domain,c);const g=nn(c,cy);nn(o,cy,g),nn(a,cy,g),nn(m,cy,g);const _=nn(o,sp);Ai(_,n,o),Ai(_,t.domain,o);const j=qd();Ai(g,t.domain,j),Ai(j,t.domain,j);const N=nn(j,sp);Ai(N,t.domain,j);const C=qd(RJ);Ai(N,t.tld,C),Ai(N,t.utld,C),nn(g,_k,C);const P=nn(j,Kd);nn(P,Kd,P),Ai(P,t.domain,j),Ai(C,t.domain,j),nn(C,sp,N),nn(C,Kd,P);const A=nn(C,gy);Ai(A,t.numeric,RJ);const I=nn(c,Kd),O=nn(c,sp);nn(I,Kd,I),Ai(I,t.domain,c),Ai(O,n,o),Ai(O,t.domain,c);const R=qd(VP);Ai(O,t.tld,R),Ai(O,t.utld,R),Ai(R,t.domain,c),Ai(R,n,o),nn(R,sp,O),nn(R,Kd,I),nn(R,cy,g);const z=nn(R,gy),W=qd(VP);Ai(z,t.numeric,W);const V=qd(VP),K=qd();Ai(V,e,V),Ai(V,r,K),Ai(K,e,V),Ai(K,r,K),nn(R,ip,V),nn(W,ip,V);const Q=nn(a,gy),te=nn(m,gy),X=nn(te,ip),ie=nn(X,ip);Ai(a,t.domain,c),nn(a,sp,O),nn(a,Kd,I),Ai(m,t.domain,c),nn(m,sp,O),nn(m,Kd,I),Ai(Q,t.domain,V),nn(Q,ip,V),nn(Q,_2,V),Ai(ie,t.domain,V),Ai(ie,e,V),nn(ie,ip,V);const he=[[y2,x2],[lO,cO],[uO,dO],[hO,fO],[pO,mO],[gO,yO],[xO,vO],[_O,bO]];for(let xe=0;xe=0&&N++,i++,_++;if(N<0)i-=_,i0&&(o.push(qz(DJ,e,c)),c=[]),i-=N,_-=N;const C=j.t,P=r.slice(i-_,i);o.push(qz(C,e,P))}}return c.length>0&&o.push(qz(DJ,e,c)),o}function qz(t,e,r){const n=r[0].s,i=r[r.length-1].e,o=e.slice(n,i);return new t(o,r)}const aWe=typeof console<"u"&&console&&console.warn||(()=>{}),oWe="until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time.",ro={scanner:null,parser:null,tokenQueue:[],pluginQueue:[],customSchemes:[],initialized:!1};function lWe(){return Mu.groups={},ro.scanner=null,ro.parser=null,ro.tokenQueue=[],ro.pluginQueue=[],ro.customSchemes=[],ro.initialized=!1,ro}function LJ(t,e=!1){if(ro.initialized&&aWe(`linkifyjs: already initialized - will not register custom scheme "${t}" ${oWe}`),!/^[0-9a-z]+(-[0-9a-z]+)*$/.test(t))throw new Error(`linkifyjs: incorrect scheme format. 1. Must only contain digits, lowercase ASCII letters or "-" 2. Cannot start or end with "-" 3. "-" cannot repeat`);ro.customSchemes.push([t,e])}function cWe(){ro.scanner=tWe(ro.customSchemes);for(let t=0;t{const i=e.some(g=>g.docChanged)&&!r.doc.eq(n.doc),o=e.some(g=>g.getMeta("preventAutolink"));if(!i||o)return;const{tr:c}=n,a=z8e(r.doc,[...e]);if(G8e(a).forEach(({newRange:g})=>{const _=$8e(n.doc,g,C=>C.isTextblock);let j,N;if(_.length>1)j=_[0],N=n.doc.textBetween(j.pos,j.pos+j.node.nodeSize,void 0," ");else if(_.length){const C=n.doc.textBetween(g.from,g.to," "," ");if(!dWe.test(C))return;j=_[0],N=n.doc.textBetween(j.pos,g.to,void 0," ")}if(j&&N){const C=N.split(uWe).filter(Boolean);if(C.length<=0)return!1;const P=C[C.length-1],A=j.pos+N.lastIndexOf(P);if(!P)return!1;const I=pH(P).map(O=>O.toObject(t.defaultProtocol));if(!fWe(I))return!1;I.filter(O=>O.isLink).map(O=>({...O,from:A+O.start+1,to:A+O.end+1})).filter(O=>n.schema.marks.code?!n.doc.rangeHasMark(O.from,O.to,n.schema.marks.code):!0).filter(O=>t.validate(O.value)).filter(O=>t.shouldAutoLink(O.value)).forEach(O=>{rH(O.from,O.to,n.doc).some(R=>R.mark.type===t.type)||c.addMark(O.from,O.to,t.type.create({href:O.href}))})}}),!!c.steps.length)return c}})}function mWe(t){return new wc({key:new kd("handleClickLink"),props:{handleClick:(e,r,n)=>{var i,o;if(n.button!==0||!e.editable)return!1;let c=n.target;const a=[];for(;c.nodeName!=="DIV";)a.push(c),c=c.parentNode;if(!a.find(N=>N.nodeName==="A"))return!1;const m=tye(e.state,t.type.name),g=n.target,_=(i=g==null?void 0:g.href)!==null&&i!==void 0?i:m.href,j=(o=g==null?void 0:g.target)!==null&&o!==void 0?o:m.target;return g&&_?(window.open(_,j),!0):!1}}})}function gWe(t){return new wc({key:new kd("handlePasteLink"),props:{handlePaste:(e,r,n)=>{const{state:i}=e,{selection:o}=i,{empty:c}=o;if(c)return!1;let a="";n.content.forEach(g=>{a+=g.textContent});const m=_ye(a,{defaultProtocol:t.defaultProtocol}).find(g=>g.isLink&&g.value===a);return!a||!m?!1:t.editor.commands.setMark(t.type,{href:m.href})}}})}function Tv(t,e){const r=["http","https","ftp","ftps","mailto","tel","callto","sms","cid","xmpp"];return e&&e.forEach(n=>{const i=typeof n=="string"?n:n.scheme;i&&r.push(i)}),!t||t.replace(hWe,"").match(new RegExp(`^(?:(?:${r.join("|")}):|[^a-z]|[a-z0-9+.-]+(?:[^a-z+.-:]|$))`,"i"))}const bye=Ep.create({name:"link",priority:1e3,keepOnSplit:!1,exitable:!0,onCreate(){this.options.validate&&!this.options.shouldAutoLink&&(this.options.shouldAutoLink=this.options.validate,console.warn("The `validate` option is deprecated. Rename to the `shouldAutoLink` option instead.")),this.options.protocols.forEach(t=>{if(typeof t=="string"){LJ(t);return}LJ(t.scheme,t.optionalSlashes)})},onDestroy(){lWe()},inclusive(){return this.options.autolink},addOptions(){return{openOnClick:!0,linkOnPaste:!0,autolink:!0,protocols:[],defaultProtocol:"http",HTMLAttributes:{target:"_blank",rel:"noopener noreferrer nofollow",class:null},isAllowedUri:(t,e)=>!!Tv(t,e.protocols),validate:t=>!!t,shouldAutoLink:t=>!!t}},addAttributes(){return{href:{default:null,parseHTML(t){return t.getAttribute("href")}},target:{default:this.options.HTMLAttributes.target},rel:{default:this.options.HTMLAttributes.rel},class:{default:this.options.HTMLAttributes.class}}},parseHTML(){return[{tag:"a[href]",getAttrs:t=>{const e=t.getAttribute("href");return!e||!this.options.isAllowedUri(e,{defaultValidate:r=>!!Tv(r,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?!1:null}}]},renderHTML({HTMLAttributes:t}){return this.options.isAllowedUri(t.href,{defaultValidate:e=>!!Tv(e,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?["a",Ql(this.options.HTMLAttributes,t),0]:["a",Ql(this.options.HTMLAttributes,{...t,href:""}),0]},addCommands(){return{setLink:t=>({chain:e})=>{const{href:r}=t;return this.options.isAllowedUri(r,{defaultValidate:n=>!!Tv(n,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?e().setMark(this.name,t).setMeta("preventAutolink",!0).run():!1},toggleLink:t=>({chain:e})=>{const{href:r}=t;return this.options.isAllowedUri(r,{defaultValidate:n=>!!Tv(n,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?e().toggleMark(this.name,t,{extendEmptyMarkRange:!0}).setMeta("preventAutolink",!0).run():!1},unsetLink:()=>({chain:t})=>t().unsetMark(this.name,{extendEmptyMarkRange:!0}).setMeta("preventAutolink",!0).run()}},addPasteRules(){return[H_({find:t=>{const e=[];if(t){const{protocols:r,defaultProtocol:n}=this.options,i=_ye(t).filter(o=>o.isLink&&this.options.isAllowedUri(o.value,{defaultValidate:c=>!!Tv(c,r),protocols:r,defaultProtocol:n}));i.length&&i.forEach(o=>e.push({text:o.value,data:{href:o.href},index:o.start}))}return e},type:this.type,getAttributes:t=>{var e;return{href:(e=t.data)===null||e===void 0?void 0:e.href}}})]},addProseMirrorPlugins(){const t=[],{protocols:e,defaultProtocol:r}=this.options;return this.options.autolink&&t.push(pWe({type:this.type,defaultProtocol:this.options.defaultProtocol,validate:n=>this.options.isAllowedUri(n,{defaultValidate:i=>!!Tv(i,e),protocols:e,defaultProtocol:r}),shouldAutoLink:this.options.shouldAutoLink})),this.options.openOnClick===!0&&t.push(mWe({type:this.type})),this.options.linkOnPaste&&t.push(gWe({editor:this.editor,defaultProtocol:this.options.defaultProtocol,type:this.type})),t}}),wye=bc.create({name:"textAlign",addOptions(){return{types:[],alignments:["left","center","right","justify"],defaultAlignment:null}},addGlobalAttributes(){return[{types:this.options.types,attributes:{textAlign:{default:this.options.defaultAlignment,parseHTML:t=>{const e=t.style.textAlign;return this.options.alignments.includes(e)?e:this.options.defaultAlignment},renderHTML:t=>t.textAlign?{style:`text-align: ${t.textAlign}`}:{}}}}]},addCommands(){return{setTextAlign:t=>({commands:e})=>this.options.alignments.includes(t)?this.options.types.map(r=>e.updateAttributes(r,{textAlign:t})).every(r=>r):!1,unsetTextAlign:()=>({commands:t})=>this.options.types.map(e=>t.resetAttributes(e,"textAlign")).every(e=>e),toggleTextAlign:t=>({editor:e,commands:r})=>this.options.alignments.includes(t)?e.isActive({textAlign:t})?r.unsetTextAlign():r.setTextAlign(t):!1}},addKeyboardShortcuts(){return{"Mod-Shift-l":()=>this.editor.commands.setTextAlign("left"),"Mod-Shift-e":()=>this.editor.commands.setTextAlign("center"),"Mod-Shift-r":()=>this.editor.commands.setTextAlign("right"),"Mod-Shift-j":()=>this.editor.commands.setTextAlign("justify")}}}),yWe=t=>{if(!t.children.length)return;const e=t.querySelectorAll("span");e&&e.forEach(r=>{var n,i;const o=r.getAttribute("style"),c=(i=(n=r.parentElement)===null||n===void 0?void 0:n.closest("span"))===null||i===void 0?void 0:i.getAttribute("style");r.setAttribute("style",`${c};${o}`)})},jye=Ep.create({name:"textStyle",priority:101,addOptions(){return{HTMLAttributes:{},mergeNestedSpanStyles:!1}},parseHTML(){return[{tag:"span",getAttrs:t=>t.hasAttribute("style")?(this.options.mergeNestedSpanStyles&&yWe(t),{}):!1}]},renderHTML({HTMLAttributes:t}){return["span",Ql(this.options.HTMLAttributes,t),0]},addCommands(){return{removeEmptyTextStyle:()=>({tr:t})=>{const{selection:e}=t;return t.doc.nodesBetween(e.from,e.to,(r,n)=>{if(r.isTextblock)return!0;r.marks.filter(i=>i.type===this.type).some(i=>Object.values(i.attrs).some(o=>!!o))||t.removeMark(n,n+r.nodeSize,this.type)}),!0}}}});function ag({content:t,onChange:e,placeholder:r="Enter content...",minHeight:n="150px"}){const[i,o]=D.useState(!1),[c,a]=D.useState(""),[m,g]=D.useState(!0),_=iye({extensions:[dye,bye.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),wye.configure({types:["heading","paragraph"]}),jye],content:t,onUpdate:({editor:P})=>{e(P.getHTML())},editorProps:{attributes:{class:"outline-none","data-placeholder":r}}});D.useEffect(()=>{_&&t!==_.getHTML()&&_.commands.setContent(t)},[t,_]);const j=()=>{if(!_)return;const P=_.getAttributes("link").href||"",A=_.getAttributes("link").target;a(P),g(A==="_blank"),o(!0)},N=()=>{_&&(c===""?_.chain().focus().extendMarkRange("link").unsetLink().run():_.chain().focus().extendMarkRange("link").setLink({href:c,target:m?"_blank":null,rel:m?"noopener noreferrer nofollow":null}).run(),o(!1),a(""))},C=()=>{_&&_.chain().focus().extendMarkRange("link").unsetLink().run()};return _?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-0.5 p-2 border-b bg-muted/30",children:[s.jsx(de,{type:"button",variant:"ghost",size:"sm",onClick:()=>_.chain().focus().toggleHeading({level:1}).run(),className:_.isActive("heading",{level:1})?"bg-muted":"",title:"Heading 1",children:s.jsx(A2e,{className:"h-4 w-4"})}),s.jsx(de,{type:"button",variant:"ghost",size:"sm",onClick:()=>_.chain().focus().toggleHeading({level:2}).run(),className:_.isActive("heading",{level:2})?"bg-muted":"",title:"Heading 2",children:s.jsx(P2e,{className:"h-4 w-4"})}),s.jsx("div",{className:"w-px h-6 bg-border mx-1"}),s.jsx(de,{type:"button",variant:"ghost",size:"sm",onClick:()=>_.chain().focus().toggleBold().run(),className:_.isActive("bold")?"bg-muted":"",title:"Bold",children:s.jsx(aoe,{className:"h-4 w-4"})}),s.jsx(de,{type:"button",variant:"ghost",size:"sm",onClick:()=>_.chain().focus().toggleItalic().run(),className:_.isActive("italic")?"bg-muted":"",title:"Italic",children:s.jsx(poe,{className:"h-4 w-4"})}),s.jsx("div",{className:"w-px h-6 bg-border mx-1"}),s.jsx(de,{type:"button",variant:"ghost",size:"sm",onClick:()=>_.chain().focus().toggleBulletList().run(),className:_.isActive("bulletList")?"bg-muted":"",title:"Bullet List",children:s.jsx(Aj,{className:"h-4 w-4"})}),s.jsx(de,{type:"button",variant:"ghost",size:"sm",onClick:()=>_.chain().focus().toggleOrderedList().run(),className:_.isActive("orderedList")?"bg-muted":"",title:"Numbered List",children:s.jsx(yoe,{className:"h-4 w-4"})}),s.jsx("div",{className:"w-px h-6 bg-border mx-1"}),s.jsx(de,{type:"button",variant:"ghost",size:"sm",onClick:()=>_.chain().focus().setTextAlign("left").run(),className:_.isActive({textAlign:"left"})?"bg-muted":"",title:"Align Left",children:s.jsx(toe,{className:"h-4 w-4"})}),s.jsx(de,{type:"button",variant:"ghost",size:"sm",onClick:()=>_.chain().focus().setTextAlign("center").run(),className:_.isActive({textAlign:"center"})?"bg-muted":"",title:"Align Center",children:s.jsx(eoe,{className:"h-4 w-4"})}),s.jsx(de,{type:"button",variant:"ghost",size:"sm",onClick:()=>_.chain().focus().setTextAlign("right").run(),className:_.isActive({textAlign:"right"})?"bg-muted":"",title:"Align Right",children:s.jsx(roe,{className:"h-4 w-4"})}),s.jsx("div",{className:"w-px h-6 bg-border mx-1"}),s.jsx(de,{type:"button",variant:"ghost",size:"sm",onClick:j,className:_.isActive("link")?"bg-muted":"",title:"Add Link",children:s.jsx(Go,{className:"h-4 w-4"})}),_.isActive("link")&&s.jsx(de,{type:"button",variant:"ghost",size:"sm",onClick:C,title:"Remove Link",children:s.jsx(Go,{className:"h-4 w-4"})}),s.jsx("div",{className:"w-px h-6 bg-border mx-1"}),s.jsx(de,{type:"button",variant:"ghost",size:"sm",onClick:()=>_.chain().focus().undo().run(),disabled:!_.can().undo(),title:"Undo",children:s.jsx(Noe,{className:"h-4 w-4"})}),s.jsx(de,{type:"button",variant:"ghost",size:"sm",onClick:()=>_.chain().focus().redo().run(),disabled:!_.can().redo(),title:"Redo",children:s.jsx(boe,{className:"h-4 w-4"})})]}),s.jsx(nye,{editor:_,className:"prose prose-sm max-w-none p-3 focus:outline-none [&_.ProseMirror]:outline-none",style:{minHeight:n}})]}),s.jsx(mn,{open:i,onOpenChange:o,children:s.jsxs(pn,{className:"sm:max-w-md",children:[s.jsx(xn,{children:s.jsx(gn,{children:"Insert Link"})}),s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"link-url",children:"URL"}),s.jsx(Et,{id:"link-url",value:c,onChange:P=>a(P.target.value),placeholder:"https://example.com"})]}),s.jsxs("div",{className:"flex items-center space-x-2",children:[s.jsx(ri,{id:"link-new-tab",checked:m,onCheckedChange:g}),s.jsx(mt,{htmlFor:"link-new-tab",children:"Open in new tab"})]})]}),s.jsxs(zi,{children:[s.jsx(de,{type:"button",variant:"outline",onClick:()=>o(!1),children:"Cancel"}),s.jsx(de,{type:"button",onClick:N,children:c?"Apply Link":"Remove Link"})]})]})})]}):null}var Gs=function(){return Gs=Object.assign||function(e){for(var r,n=1,i=arguments.length;n1&&(m||!g),j=e>1&&(g||!m),N=function(){n&&o(n)},C=function(){i&&o(i)};return s.jsx(YWe,{displayMonth:t.displayMonth,hideNext:_,hidePrevious:j,nextMonth:i,previousMonth:n,onPreviousClick:N,onNextClick:C})}function XWe(t){var e,r=Za(),n=r.classNames,i=r.disableNavigation,o=r.styles,c=r.captionLayout,a=r.components,m=(e=a==null?void 0:a.CaptionLabel)!==null&&e!==void 0?e:Cye,g;return i?g=s.jsx(m,{id:t.id,displayMonth:t.displayMonth}):c==="dropdown"?g=s.jsx(FJ,{displayMonth:t.displayMonth,id:t.id}):c==="dropdown-buttons"?g=s.jsxs(s.Fragment,{children:[s.jsx(FJ,{displayMonth:t.displayMonth,displayIndex:t.displayIndex,id:t.id}),s.jsx(zJ,{displayMonth:t.displayMonth,displayIndex:t.displayIndex,id:t.id})]}):g=s.jsxs(s.Fragment,{children:[s.jsx(m,{id:t.id,displayMonth:t.displayMonth,displayIndex:t.displayIndex}),s.jsx(zJ,{displayMonth:t.displayMonth,id:t.id})]}),s.jsx("div",{className:n.caption,style:o.caption,children:g})}function QWe(t){var e=Za(),r=e.footer,n=e.styles,i=e.classNames.tfoot;return r?s.jsx("tfoot",{className:i,style:n.tfoot,children:s.jsx("tr",{children:s.jsx("td",{colSpan:8,children:r})})}):s.jsx(s.Fragment,{})}function JWe(t,e,r){for(var n=r?z_(new Date):Np(new Date,{locale:t,weekStartsOn:e}),i=[],o=0;o<7;o++){var c=hc(n,o);i.push(c)}return i}function eGe(){var t=Za(),e=t.classNames,r=t.styles,n=t.showWeekNumber,i=t.locale,o=t.weekStartsOn,c=t.ISOWeek,a=t.formatters.formatWeekdayName,m=t.labels.labelWeekday,g=JWe(i,o,c);return s.jsxs("tr",{style:r.head_row,className:e.head_row,children:[n&&s.jsx("td",{style:r.head_cell,className:e.head_cell}),g.map(function(_,j){return s.jsx("th",{scope:"col",className:e.head_cell,style:r.head_cell,"aria-label":m(_,{locale:i}),children:a(_,{locale:i})},j)})]})}function tGe(){var t,e=Za(),r=e.classNames,n=e.styles,i=e.components,o=(t=i==null?void 0:i.HeadRow)!==null&&t!==void 0?t:eGe;return s.jsx("thead",{style:n.head,className:r.head,children:s.jsx(o,{})})}function rGe(t){var e=Za(),r=e.locale,n=e.formatters.formatDay;return s.jsx(s.Fragment,{children:n(t.date,{locale:r})})}var gH=D.createContext(void 0);function nGe(t){if(!zT(t.initialProps)){var e={selected:void 0,modifiers:{disabled:[]}};return s.jsx(gH.Provider,{value:e,children:t.children})}return s.jsx(sGe,{initialProps:t.initialProps,children:t.children})}function sGe(t){var e=t.initialProps,r=t.children,n=e.selected,i=e.min,o=e.max,c=function(g,_,j){var N,C;(N=e.onDayClick)===null||N===void 0||N.call(e,g,_,j);var P=!!(_.selected&&i&&(n==null?void 0:n.length)===i);if(!P){var A=!!(!_.selected&&o&&(n==null?void 0:n.length)===o);if(!A){var I=n?Sye([],n):[];if(_.selected){var O=I.findIndex(function(R){return Wo(g,R)});I.splice(O,1)}else I.push(g);(C=e.onSelect)===null||C===void 0||C.call(e,I,g,_,j)}}},a={disabled:[]};n&&a.disabled.push(function(g){var _=o&&n.length>o-1,j=n.some(function(N){return Wo(N,g)});return!!(_&&!j)});var m={selected:n,onDayClick:c,modifiers:a};return s.jsx(gH.Provider,{value:m,children:r})}function yH(){var t=D.useContext(gH);if(!t)throw new Error("useSelectMultiple must be used within a SelectMultipleProvider");return t}function iGe(t,e){var r=e||{},n=r.from,i=r.to;return n&&i?Wo(i,t)&&Wo(n,t)?void 0:Wo(i,t)?{from:i,to:void 0}:Wo(n,t)?void 0:UM(n,t)?{from:t,to:i}:{from:n,to:t}:i?UM(t,i)?{from:i,to:t}:{from:t,to:i}:n?lq(t,n)?{from:t,to:n}:{from:n,to:t}:{from:t,to:void 0}}var xH=D.createContext(void 0);function aGe(t){if(!BT(t.initialProps)){var e={selected:void 0,modifiers:{range_start:[],range_end:[],range_middle:[],disabled:[]}};return s.jsx(xH.Provider,{value:e,children:t.children})}return s.jsx(oGe,{initialProps:t.initialProps,children:t.children})}function oGe(t){var e=t.initialProps,r=t.children,n=e.selected,i=n||{},o=i.from,c=i.to,a=e.min,m=e.max,g=function(C,P,A){var I,O;(I=e.onDayClick)===null||I===void 0||I.call(e,C,P,A);var R=iGe(C,n);(O=e.onSelect)===null||O===void 0||O.call(e,R,C,P,A)},_={range_start:[],range_end:[],range_middle:[],disabled:[]};if(o?(_.range_start=[o],c?(_.range_end=[c],Wo(o,c)||(_.range_middle=[{after:o,before:c}])):_.range_end=[o]):c&&(_.range_start=[c],_.range_end=[c]),a&&(o&&!c&&_.disabled.push({after:hz(o,a-1),before:hc(o,a-1)}),o&&c&&_.disabled.push({after:o,before:hc(o,a-1)}),!o&&c&&_.disabled.push({after:hz(c,a-1),before:hc(c,a-1)})),m){if(o&&!c&&(_.disabled.push({before:hc(o,-m+1)}),_.disabled.push({after:hc(o,m-1)})),o&&c){var j=yf(c,o)+1,N=m-j;_.disabled.push({before:hz(o,N)}),_.disabled.push({after:hc(c,N)})}!o&&c&&(_.disabled.push({before:hc(c,-m+1)}),_.disabled.push({after:hc(c,m-1)}))}return s.jsx(xH.Provider,{value:{selected:n,onDayClick:g,modifiers:_},children:r})}function vH(){var t=D.useContext(xH);if(!t)throw new Error("useSelectRange must be used within a SelectRangeProvider");return t}function FI(t){return Array.isArray(t)?Sye([],t):t!==void 0?[t]:[]}function lGe(t){var e={};return Object.entries(t).forEach(function(r){var n=r[0],i=r[1];e[n]=FI(i)}),e}var kf;(function(t){t.Outside="outside",t.Disabled="disabled",t.Selected="selected",t.Hidden="hidden",t.Today="today",t.RangeStart="range_start",t.RangeEnd="range_end",t.RangeMiddle="range_middle"})(kf||(kf={}));var cGe=kf.Selected,gm=kf.Disabled,uGe=kf.Hidden,dGe=kf.Today,Hz=kf.RangeEnd,Wz=kf.RangeMiddle,Gz=kf.RangeStart,hGe=kf.Outside;function fGe(t,e,r){var n,i=(n={},n[cGe]=FI(t.selected),n[gm]=FI(t.disabled),n[uGe]=FI(t.hidden),n[dGe]=[t.today],n[Hz]=[],n[Wz]=[],n[Gz]=[],n[hGe]=[],n);return t.fromDate&&i[gm].push({before:t.fromDate}),t.toDate&&i[gm].push({after:t.toDate}),zT(t)?i[gm]=i[gm].concat(e.modifiers[gm]):BT(t)&&(i[gm]=i[gm].concat(r.modifiers[gm]),i[Gz]=r.modifiers[Gz],i[Wz]=r.modifiers[Wz],i[Hz]=r.modifiers[Hz]),i}var Eye=D.createContext(void 0);function pGe(t){var e=Za(),r=yH(),n=vH(),i=fGe(e,r,n),o=lGe(e.modifiers),c=Gs(Gs({},i),o);return s.jsx(Eye.Provider,{value:c,children:t.children})}function Aye(){var t=D.useContext(Eye);if(!t)throw new Error("useModifiers must be used within a ModifiersProvider");return t}function mGe(t){return!!(t&&typeof t=="object"&&"before"in t&&"after"in t)}function gGe(t){return!!(t&&typeof t=="object"&&"from"in t)}function yGe(t){return!!(t&&typeof t=="object"&&"after"in t)}function xGe(t){return!!(t&&typeof t=="object"&&"before"in t)}function vGe(t){return!!(t&&typeof t=="object"&&"dayOfWeek"in t)}function _Ge(t,e){var r,n=e.from,i=e.to;if(n&&i){var o=yf(i,n)<0;o&&(r=[i,n],n=r[0],i=r[1]);var c=yf(t,n)>=0&&yf(i,t)>=0;return c}return i?Wo(i,t):n?Wo(n,t):!1}function bGe(t){return iq(t)}function wGe(t){return Array.isArray(t)&&t.every(iq)}function jGe(t,e){return e.some(function(r){if(typeof r=="boolean")return r;if(bGe(r))return Wo(t,r);if(wGe(r))return r.includes(t);if(gGe(r))return _Ge(t,r);if(vGe(r))return r.dayOfWeek.includes(t.getDay());if(mGe(r)){var n=yf(r.before,t),i=yf(r.after,t),o=n>0,c=i<0,a=UM(r.before,r.after);return a?c&&o:o||c}return yGe(r)?yf(t,r.after)>0:xGe(r)?yf(r.before,t)>0:typeof r=="function"?r(t):!1})}function _H(t,e,r){var n=Object.keys(e).reduce(function(o,c){var a=e[c];return jGe(t,a)&&o.push(c),o},[]),i={};return n.forEach(function(o){return i[o]=!0}),r&&!cq(t,r)&&(i.outside=!0),i}function SGe(t,e){for(var r=zu(t[0]),n=MD(t[t.length-1]),i,o,c=r;c<=n;){var a=_H(c,e),m=!a.disabled&&!a.hidden;if(!m){c=hc(c,1);continue}if(a.selected)return c;a.today&&!o&&(o=c),i||(i=c),c=hc(c,1)}return o||i}var NGe=365;function Pye(t,e){var r=e.moveBy,n=e.direction,i=e.context,o=e.modifiers,c=e.retry,a=c===void 0?{count:0,lastFocused:t}:c,m=i.weekStartsOn,g=i.fromDate,_=i.toDate,j=i.locale,N={day:hc,week:I$,month:gh,year:k3e,startOfWeek:function(I){return i.ISOWeek?z_(I):Np(I,{locale:j,weekStartsOn:m})},endOfWeek:function(I){return i.ISOWeek?efe(I):aq(I,{locale:j,weekStartsOn:m})}},C=N[r](t,n==="after"?1:-1);n==="before"&&g?C=T3e([g,C]):n==="after"&&_&&(C=E3e([_,C]));var P=!0;if(o){var A=_H(C,o);P=!A.disabled&&!A.hidden}return P?C:a.count>NGe?a.lastFocused:Pye(C,{moveBy:r,direction:n,context:i,modifiers:o,retry:Gs(Gs({},a),{count:a.count+1})})}var Iye=D.createContext(void 0);function CGe(t){var e=$T(),r=Aye(),n=D.useState(),i=n[0],o=n[1],c=D.useState(),a=c[0],m=c[1],g=SGe(e.displayMonths,r),_=i??(a&&e.isDateDisplayed(a))?a:g,j=function(){m(i),o(void 0)},N=function(I){o(I)},C=Za(),P=function(I,O){if(i){var R=Pye(i,{moveBy:I,direction:O,context:C,modifiers:r});Wo(i,R)||(e.goToDate(R,i),N(R))}},A={focusedDay:i,focusTarget:_,blur:j,focus:N,focusDayAfter:function(){return P("day","after")},focusDayBefore:function(){return P("day","before")},focusWeekAfter:function(){return P("week","after")},focusWeekBefore:function(){return P("week","before")},focusMonthBefore:function(){return P("month","before")},focusMonthAfter:function(){return P("month","after")},focusYearBefore:function(){return P("year","before")},focusYearAfter:function(){return P("year","after")},focusStartOfWeek:function(){return P("startOfWeek","before")},focusEndOfWeek:function(){return P("endOfWeek","after")}};return s.jsx(Iye.Provider,{value:A,children:t.children})}function bH(){var t=D.useContext(Iye);if(!t)throw new Error("useFocusContext must be used within a FocusProvider");return t}function kGe(t,e){var r=Aye(),n=_H(t,r,e);return n}var wH=D.createContext(void 0);function TGe(t){if(!oL(t.initialProps)){var e={selected:void 0};return s.jsx(wH.Provider,{value:e,children:t.children})}return s.jsx(EGe,{initialProps:t.initialProps,children:t.children})}function EGe(t){var e=t.initialProps,r=t.children,n=function(o,c,a){var m,g,_;if((m=e.onDayClick)===null||m===void 0||m.call(e,o,c,a),c.selected&&!e.required){(g=e.onSelect)===null||g===void 0||g.call(e,void 0,o,c,a);return}(_=e.onSelect)===null||_===void 0||_.call(e,o,o,c,a)},i={selected:e.selected,onDayClick:n};return s.jsx(wH.Provider,{value:i,children:r})}function Mye(){var t=D.useContext(wH);if(!t)throw new Error("useSelectSingle must be used within a SelectSingleProvider");return t}function AGe(t,e){var r=Za(),n=Mye(),i=yH(),o=vH(),c=bH(),a=c.focusDayAfter,m=c.focusDayBefore,g=c.focusWeekAfter,_=c.focusWeekBefore,j=c.blur,N=c.focus,C=c.focusMonthBefore,P=c.focusMonthAfter,A=c.focusYearBefore,I=c.focusYearAfter,O=c.focusStartOfWeek,R=c.focusEndOfWeek,z=function(Ce){var Se,je,et,bt;oL(r)?(Se=n.onDayClick)===null||Se===void 0||Se.call(n,t,e,Ce):zT(r)?(je=i.onDayClick)===null||je===void 0||je.call(i,t,e,Ce):BT(r)?(et=o.onDayClick)===null||et===void 0||et.call(o,t,e,Ce):(bt=r.onDayClick)===null||bt===void 0||bt.call(r,t,e,Ce)},W=function(Ce){var Se;N(t),(Se=r.onDayFocus)===null||Se===void 0||Se.call(r,t,e,Ce)},V=function(Ce){var Se;j(),(Se=r.onDayBlur)===null||Se===void 0||Se.call(r,t,e,Ce)},K=function(Ce){var Se;(Se=r.onDayMouseEnter)===null||Se===void 0||Se.call(r,t,e,Ce)},Q=function(Ce){var Se;(Se=r.onDayMouseLeave)===null||Se===void 0||Se.call(r,t,e,Ce)},te=function(Ce){var Se;(Se=r.onDayPointerEnter)===null||Se===void 0||Se.call(r,t,e,Ce)},X=function(Ce){var Se;(Se=r.onDayPointerLeave)===null||Se===void 0||Se.call(r,t,e,Ce)},ie=function(Ce){var Se;(Se=r.onDayTouchCancel)===null||Se===void 0||Se.call(r,t,e,Ce)},he=function(Ce){var Se;(Se=r.onDayTouchEnd)===null||Se===void 0||Se.call(r,t,e,Ce)},xe=function(Ce){var Se;(Se=r.onDayTouchMove)===null||Se===void 0||Se.call(r,t,e,Ce)},pe=function(Ce){var Se;(Se=r.onDayTouchStart)===null||Se===void 0||Se.call(r,t,e,Ce)},ve=function(Ce){var Se;(Se=r.onDayKeyUp)===null||Se===void 0||Se.call(r,t,e,Ce)},ge=function(Ce){var Se;switch(Ce.key){case"ArrowLeft":Ce.preventDefault(),Ce.stopPropagation(),r.dir==="rtl"?a():m();break;case"ArrowRight":Ce.preventDefault(),Ce.stopPropagation(),r.dir==="rtl"?m():a();break;case"ArrowDown":Ce.preventDefault(),Ce.stopPropagation(),g();break;case"ArrowUp":Ce.preventDefault(),Ce.stopPropagation(),_();break;case"PageUp":Ce.preventDefault(),Ce.stopPropagation(),Ce.shiftKey?A():C();break;case"PageDown":Ce.preventDefault(),Ce.stopPropagation(),Ce.shiftKey?I():P();break;case"Home":Ce.preventDefault(),Ce.stopPropagation(),O();break;case"End":Ce.preventDefault(),Ce.stopPropagation(),R();break}(Se=r.onDayKeyDown)===null||Se===void 0||Se.call(r,t,e,Ce)},ke={onClick:z,onFocus:W,onBlur:V,onKeyDown:ge,onKeyUp:ve,onMouseEnter:K,onMouseLeave:Q,onPointerEnter:te,onPointerLeave:X,onTouchCancel:ie,onTouchEnd:he,onTouchMove:xe,onTouchStart:pe};return ke}function PGe(){var t=Za(),e=Mye(),r=yH(),n=vH(),i=oL(t)?e.selected:zT(t)?r.selected:BT(t)?n.selected:void 0;return i}function IGe(t){return Object.values(kf).includes(t)}function MGe(t,e){var r=[t.classNames.day];return Object.keys(e).forEach(function(n){var i=t.modifiersClassNames[n];if(i)r.push(i);else if(IGe(n)){var o=t.classNames["day_".concat(n)];o&&r.push(o)}}),r}function OGe(t,e){var r=Gs({},t.styles.day);return Object.keys(e).forEach(function(n){var i;r=Gs(Gs({},r),(i=t.modifiersStyles)===null||i===void 0?void 0:i[n])}),r}function RGe(t,e,r){var n,i,o,c=Za(),a=bH(),m=kGe(t,e),g=AGe(t,m),_=PGe(),j=!!(c.onDayClick||c.mode!=="default");D.useEffect(function(){var K;m.outside||a.focusedDay&&j&&Wo(a.focusedDay,t)&&((K=r.current)===null||K===void 0||K.focus())},[a.focusedDay,t,r,j,m.outside]);var N=MGe(c,m).join(" "),C=OGe(c,m),P=!!(m.outside&&!c.showOutsideDays||m.hidden),A=(o=(i=c.components)===null||i===void 0?void 0:i.DayContent)!==null&&o!==void 0?o:rGe,I=s.jsx(A,{date:t,displayMonth:e,activeModifiers:m}),O={style:C,className:N,children:I,role:"gridcell"},R=a.focusTarget&&Wo(a.focusTarget,t)&&!m.outside,z=a.focusedDay&&Wo(a.focusedDay,t),W=Gs(Gs(Gs({},O),(n={disabled:m.disabled,role:"gridcell"},n["aria-selected"]=m.selected,n.tabIndex=z||R?0:-1,n)),g),V={isButton:j,isHidden:P,activeModifiers:m,selectedDays:_,buttonProps:W,divProps:O};return V}function DGe(t){var e=D.useRef(null),r=RGe(t.date,t.displayMonth,e);return r.isHidden?s.jsx("div",{role:"gridcell"}):r.isButton?s.jsx(RO,Gs({name:"day",ref:e},r.buttonProps)):s.jsx("div",Gs({},r.divProps))}function LGe(t){var e=t.number,r=t.dates,n=Za(),i=n.onWeekNumberClick,o=n.styles,c=n.classNames,a=n.locale,m=n.labels.labelWeekNumber,g=n.formatters.formatWeekNumber,_=g(Number(e),{locale:a});if(!i)return s.jsx("span",{className:c.weeknumber,style:o.weeknumber,children:_});var j=m(Number(e),{locale:a}),N=function(C){i(e,r,C)};return s.jsx(RO,{name:"week-number","aria-label":j,className:c.weeknumber,style:o.weeknumber,onClick:N,children:_})}function FGe(t){var e,r,n=Za(),i=n.styles,o=n.classNames,c=n.showWeekNumber,a=n.components,m=(e=a==null?void 0:a.Day)!==null&&e!==void 0?e:DGe,g=(r=a==null?void 0:a.WeekNumber)!==null&&r!==void 0?r:LGe,_;return c&&(_=s.jsx("td",{className:o.cell,style:i.cell,children:s.jsx(g,{number:t.weekNumber,dates:t.dates})})),s.jsxs("tr",{className:o.row,style:i.row,children:[_,t.dates.map(function(j){return s.jsx("td",{className:o.cell,style:i.cell,role:"presentation",children:s.jsx(m,{displayMonth:t.displayMonth,date:j})},DFe(j))})]})}function BJ(t,e,r){for(var n=r!=null&&r.ISOWeek?efe(e):aq(e,r),i=r!=null&&r.ISOWeek?z_(t):Np(t,r),o=yf(n,i),c=[],a=0;a<=o;a++)c.push(hc(i,a));var m=c.reduce(function(g,_){var j=r!=null&&r.ISOWeek?tfe(_):nfe(_,r),N=g.find(function(C){return C.weekNumber===j});return N?(N.dates.push(_),g):(g.push({weekNumber:j,dates:[_]}),g)},[]);return m}function zGe(t,e){var r=BJ(zu(t),MD(t),e);if(e!=null&&e.useFixedWeeks){var n=FFe(t,e);if(n<6){var i=r[r.length-1],o=i.dates[i.dates.length-1],c=I$(o,6-n),a=BJ(I$(o,1),c,e);r.push.apply(r,a)}}return r}function BGe(t){var e,r,n,i=Za(),o=i.locale,c=i.classNames,a=i.styles,m=i.hideHead,g=i.fixedWeeks,_=i.components,j=i.weekStartsOn,N=i.firstWeekContainsDate,C=i.ISOWeek,P=zGe(t.displayMonth,{useFixedWeeks:!!g,ISOWeek:C,locale:o,weekStartsOn:j,firstWeekContainsDate:N}),A=(e=_==null?void 0:_.Head)!==null&&e!==void 0?e:tGe,I=(r=_==null?void 0:_.Row)!==null&&r!==void 0?r:FGe,O=(n=_==null?void 0:_.Footer)!==null&&n!==void 0?n:QWe;return s.jsxs("table",{id:t.id,className:c.table,style:a.table,role:"grid","aria-labelledby":t["aria-labelledby"],children:[!m&&s.jsx(A,{}),s.jsx("tbody",{className:c.tbody,style:a.tbody,children:P.map(function(R){return s.jsx(I,{displayMonth:t.displayMonth,dates:R.dates,weekNumber:R.weekNumber},R.weekNumber)})}),s.jsx(O,{displayMonth:t.displayMonth})]})}function $Ge(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}var UGe=$Ge()?D.useLayoutEffect:D.useEffect,Kz=!1,VGe=0;function $J(){return"react-day-picker-".concat(++VGe)}function qGe(t){var e,r=t??(Kz?$J():null),n=D.useState(r),i=n[0],o=n[1];return UGe(function(){i===null&&o($J())},[]),D.useEffect(function(){Kz===!1&&(Kz=!0)},[]),(e=t??i)!==null&&e!==void 0?e:void 0}function HGe(t){var e,r,n=Za(),i=n.dir,o=n.classNames,c=n.styles,a=n.components,m=$T().displayMonths,g=qGe(n.id?"".concat(n.id,"-").concat(t.displayIndex):void 0),_=n.id?"".concat(n.id,"-grid-").concat(t.displayIndex):void 0,j=[o.month],N=c.month,C=t.displayIndex===0,P=t.displayIndex===m.length-1,A=!C&&!P;i==="rtl"&&(e=[C,P],P=e[0],C=e[1]),C&&(j.push(o.caption_start),N=Gs(Gs({},N),c.caption_start)),P&&(j.push(o.caption_end),N=Gs(Gs({},N),c.caption_end)),A&&(j.push(o.caption_between),N=Gs(Gs({},N),c.caption_between));var I=(r=a==null?void 0:a.Caption)!==null&&r!==void 0?r:XWe;return s.jsxs("div",{className:j.join(" "),style:N,children:[s.jsx(I,{id:g,displayMonth:t.displayMonth,displayIndex:t.displayIndex}),s.jsx(BGe,{id:_,"aria-labelledby":g,displayMonth:t.displayMonth})]},t.displayIndex)}function WGe(t){var e=Za(),r=e.classNames,n=e.styles;return s.jsx("div",{className:r.months,style:n.months,children:t.children})}function GGe(t){var e,r,n=t.initialProps,i=Za(),o=bH(),c=$T(),a=D.useState(!1),m=a[0],g=a[1];D.useEffect(function(){i.initialFocus&&o.focusTarget&&(m||(o.focus(o.focusTarget),g(!0)))},[i.initialFocus,m,o.focus,o.focusTarget,o]);var _=[i.classNames.root,i.className];i.numberOfMonths>1&&_.push(i.classNames.multiple_months),i.showWeekNumber&&_.push(i.classNames.with_weeknumber);var j=Gs(Gs({},i.styles.root),i.style),N=Object.keys(n).filter(function(P){return P.startsWith("data-")}).reduce(function(P,A){var I;return Gs(Gs({},P),(I={},I[A]=n[A],I))},{}),C=(r=(e=n.components)===null||e===void 0?void 0:e.Months)!==null&&r!==void 0?r:WGe;return s.jsx("div",Gs({className:_.join(" "),style:j,dir:i.dir,id:i.id,nonce:n.nonce,title:n.title,lang:n.lang},N,{children:s.jsx(C,{children:c.displayMonths.map(function(P,A){return s.jsx(HGe,{displayIndex:A,displayMonth:P},A)})})}))}function KGe(t){var e=t.children,r=xWe(t,["children"]);return s.jsx(LWe,{initialProps:r,children:s.jsx(GWe,{children:s.jsx(TGe,{initialProps:r,children:s.jsx(nGe,{initialProps:r,children:s.jsx(aGe,{initialProps:r,children:s.jsx(pGe,{children:s.jsx(CGe,{children:e})})})})})})})}function ZGe(t){return s.jsx(KGe,Gs({},t,{children:s.jsx(GGe,{initialProps:t})}))}function Oye({className:t,classNames:e,showOutsideDays:r=!0,...n}){return s.jsx(ZGe,{showOutsideDays:r,className:ar("p-3",t),classNames:{months:"flex flex-col sm:flex-row space-y-4 sm:space-x-4 sm:space-y-0",month:"space-y-4",caption:"flex justify-center pt-1 relative items-center",caption_label:"text-sm font-medium",nav:"space-x-1 flex items-center",nav_button:ar(sk({variant:"outline"}),"h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100"),nav_button_previous:"absolute left-1",nav_button_next:"absolute right-1",table:"w-full border-collapse space-y-1",head_row:"flex",head_cell:"text-muted-foreground rounded-md w-9 font-normal text-[0.8rem]",row:"flex w-full mt-2",cell:"h-9 w-9 text-center text-sm p-0 relative [&:has([aria-selected].day-range-end)]:rounded-r-md [&:has([aria-selected].day-outside)]:bg-accent/50 [&:has([aria-selected])]:bg-accent first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md focus-within:relative focus-within:z-20",day:ar(sk({variant:"ghost"}),"h-9 w-9 p-0 font-normal aria-selected:opacity-100"),day_range_end:"day-range-end",day_selected:"bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground",day_today:"bg-accent text-accent-foreground",day_outside:"day-outside text-muted-foreground opacity-50 aria-selected:bg-accent/50 aria-selected:text-muted-foreground aria-selected:opacity-30",day_disabled:"text-muted-foreground opacity-50",day_range_middle:"aria-selected:bg-accent aria-selected:text-accent-foreground",day_hidden:"invisible",...e},components:{IconLeft:({...i})=>s.jsx(I1,{className:"h-4 w-4"}),IconRight:({...i})=>s.jsx(wd,{className:"h-4 w-4"})},...n})}Oye.displayName="Calendar";const UT=async t=>{try{const{data:e,error:r}=await ae.functions.invoke("send-push-notification",{body:t});return r?(console.error("Error sending notification:",r),{success:!1,error:r}):(console.log("Notification sent:",e),{success:!0,data:e})}catch(e){return console.error("Error sending notification:",e),{success:!1,error:e}}},YGe=async(t,e)=>UT({title:"New Template Available",body:`Check out the new template: ${t}`,url:`/template/${e}`}),XGe=async(t,e)=>UT({title:"New Academy Video",body:`New video added: ${t}`,url:`/academy/${e}`}),QGe=async(t,e)=>UT({title:"New Event",body:`New event: ${t}`,url:`/event/${e}`}),JGe=async(t,e)=>UT({title:"New Resource Kit",body:`New resource kit available: ${t}`,url:`/toolbox/${e}`}),e9e=async(t,e)=>UT({title:"New Social Swag",body:`New social swag available: ${t}`,url:`/social-swag/${e}`}),qP={title:"",description:"",image_url:"",video_url:"",event_date:void 0,event_time:"12:00",zoom_link:"",zoom_meeting_id:"",capacity:"",is_published:!1};function t9e(){const t=Bs(),e=Wn(),[r,n]=D.useState(!1),[i,o]=D.useState(null),[c,a]=D.useState(qP),[m,g]=D.useState(null),[_,j]=D.useState(null),[N,C]=D.useState(!1),P=D.useRef(null),[A,I]=D.useState(!1),[O,R]=D.useState(null),{data:z,isLoading:W}=Sr({queryKey:["admin-events"],queryFn:async()=>{const{data:je,error:et}=await ae.from("events").select("*").order("event_date",{ascending:!0});if(et)throw et;return je}}),{data:V}=Sr({queryKey:["event-registrations-count"],queryFn:async()=>{const{data:je,error:et}=await ae.from("event_registrations").select("event_id");if(et)throw et;const bt={};return je.forEach(_e=>{bt[_e.event_id]=(bt[_e.event_id]||0)+1}),bt}}),{data:K,isLoading:Q}=Sr({queryKey:["event-registrations-details",O==null?void 0:O.id],queryFn:async()=>{if(!O)return[];const{data:je,error:et}=await ae.from("event_registrations").select("id, user_id, registered_at, zoom_join_url, zoom_name, zoom_email").eq("event_id",O.id).order("registered_at",{ascending:!1});if(et)throw et;if(!je||je.length===0)return[];const bt=je.map(pt=>pt.user_id).filter(Boolean);let _e=[];if(bt.length>0){const{data:pt,error:nt}=await ae.from("profiles").select("id, name, email").in("id",bt);if(nt)throw nt;_e=pt||[]}const Ye=new Map((_e==null?void 0:_e.map(pt=>[pt.id,pt]))||[]);return je.map(pt=>({...pt,profiles:pt.user_id&&Ye.get(pt.user_id)||null}))},enabled:!!O}),te=je=>{R(je),I(!0)},X=zr({mutationFn:async je=>{const{data:{session:et}}=await ae.auth.getSession();if(!et)throw new Error("Not authenticated");const bt=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/zoom-sync-registrations",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${et.access_token}`},body:JSON.stringify({event_id:je})}),_e=await bt.json();if(!bt.ok)throw new Error(_e.error||"Failed to sync");return _e},onSuccess:je=>{e.invalidateQueries({queryKey:["event-registrations-details",O==null?void 0:O.id]}),e.invalidateQueries({queryKey:["event-registrations-count"]}),Dt.success(je.message)},onError:je=>{Dt.error("Failed to sync: "+je.message)}}),ie=async je=>{const et=je.name.split(".").pop(),_e=`${`${crypto.randomUUID()}.${et}`}`,{error:Ye}=await ae.storage.from("event-images").upload(_e,je);if(Ye)throw Ye;const{data:{publicUrl:pt}}=ae.storage.from("event-images").getPublicUrl(_e);return pt},he=je=>{var bt;const et=(bt=je.target.files)==null?void 0:bt[0];if(et){if(et.size>5*1024*1024){Dt.error("Image must be less than 5MB");return}g(et),j(URL.createObjectURL(et))}},xe=()=>{g(null),j(null),a({...c,image_url:""}),P.current&&(P.current.value="")},pe=zr({mutationFn:async je=>{C(!0);let et=je.image_url;m&&(et=await ie(m)||"");const bt=new Date(je.event_date),[_e,Ye]=je.event_time.split(":");bt.setHours(parseInt(_e),parseInt(Ye));const{data:pt,error:nt}=await ae.from("events").insert({title:je.title,description:je.description||null,image_url:et||null,video_url:je.video_url||null,event_date:bt.toISOString(),zoom_link:je.zoom_link,zoom_meeting_id:je.zoom_meeting_id||null,capacity:je.capacity?parseInt(je.capacity):null,is_published:je.is_published}).select().single();if(nt)throw nt;pt&&QGe(je.title,pt.id)},onSuccess:()=>{e.invalidateQueries({queryKey:["admin-events"]}),Dt.success("Event created successfully"),n(!1),a(qP),g(null),j(null),C(!1)},onError:je=>{Dt.error("Failed to create event: "+je.message),C(!1)}}),ve=zr({mutationFn:async({id:je,data:et})=>{C(!0);let bt=et.image_url;m&&(bt=await ie(m)||"");const _e=new Date(et.event_date),[Ye,pt]=et.event_time.split(":");_e.setHours(parseInt(Ye),parseInt(pt));const{error:nt}=await ae.from("events").update({title:et.title,description:et.description||null,image_url:bt||null,video_url:et.video_url||null,event_date:_e.toISOString(),zoom_link:et.zoom_link,zoom_meeting_id:et.zoom_meeting_id||null,capacity:et.capacity?parseInt(et.capacity):null,is_published:et.is_published}).eq("id",je);if(nt)throw nt},onSuccess:()=>{e.invalidateQueries({queryKey:["admin-events"]}),Dt.success("Event updated successfully"),n(!1),o(null),a(qP),g(null),j(null),C(!1)},onError:je=>{Dt.error("Failed to update event: "+je.message),C(!1)}}),ge=zr({mutationFn:async je=>{const{error:et}=await ae.from("events").delete().eq("id",je);if(et)throw et},onSuccess:()=>{e.invalidateQueries({queryKey:["admin-events"]}),Dt.success("Event deleted successfully")},onError:je=>{Dt.error("Failed to delete event: "+je.message)}}),ke=je=>{var bt;const et=new Date(je.event_date);o(je),a({title:je.title,description:je.description||"",image_url:je.image_url||"",video_url:je.video_url||"",event_date:et,event_time:Vn(et,"HH:mm"),zoom_link:je.zoom_link,zoom_meeting_id:je.zoom_meeting_id||"",capacity:((bt=je.capacity)==null?void 0:bt.toString())||"",is_published:je.is_published}),j(je.image_url||null),g(null),n(!0)},Ce=je=>{if(je.preventDefault(),!c.event_date){Dt.error("Please select a date");return}i?ve.mutate({id:i.id,data:c}):pe.mutate(c)},Se=()=>{n(!1),o(null),a(qP),g(null),j(null)};return s.jsx("div",{className:"min-h-screen bg-background p-6",children:s.jsxs("div",{className:"max-w-6xl mx-auto",children:[s.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[s.jsx(de,{variant:"ghost",size:"icon",onClick:()=>t("/dashboard"),children:s.jsx(Ka,{className:"h-5 w-5"})}),s.jsxs("div",{children:[s.jsx("h1",{className:"text-2xl font-bold",children:"Event Management"}),s.jsx("p",{className:"text-muted-foreground",children:"Create and manage upcoming events"})]})]}),s.jsxs(at,{className:"mb-6",children:[s.jsxs(xr,{className:"flex flex-row items-center justify-between",children:[s.jsx(wr,{children:"All Events"}),s.jsxs(mn,{open:r,onOpenChange:je=>!je&&Se(),children:[s.jsx(Do,{asChild:!0,children:s.jsxs(de,{onClick:()=>n(!0),children:[s.jsx(Qn,{className:"h-4 w-4 mr-2"}),"Add Event"]})}),s.jsxs(pn,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[s.jsx(xn,{children:s.jsx(gn,{children:i?"Edit Event":"Create New Event"})}),s.jsxs("form",{onSubmit:Ce,className:"space-y-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"title",children:"Title *"}),s.jsx(Et,{id:"title",value:c.title,onChange:je=>a({...c,title:je.target.value}),placeholder:"Event title",required:!0})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Description"}),s.jsx(ag,{content:c.description,onChange:je=>a({...c,description:je}),placeholder:"Event description",minHeight:"120px"})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Event Image"}),s.jsx("input",{type:"file",ref:P,accept:"image/*",onChange:he,className:"hidden"}),_?s.jsxs("div",{className:"relative",children:[s.jsx("img",{src:_,alt:"Event preview",className:"w-full h-32 object-cover rounded-lg border"}),s.jsx(de,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:xe,children:s.jsx(Ni,{className:"h-4 w-4"})})]}):s.jsxs(de,{type:"button",variant:"outline",className:"w-full h-32 border-dashed flex flex-col gap-2",onClick:()=>{var je;return(je=P.current)==null?void 0:je.click()},children:[s.jsx(Vu,{className:"h-6 w-6"}),s.jsx("span",{className:"text-sm",children:"Click to upload image"})]})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Date *"}),s.jsxs(HD,{children:[s.jsx(WD,{asChild:!0,children:s.jsxs(de,{variant:"outline",className:ar("w-full justify-start text-left font-normal",!c.event_date&&"text-muted-foreground"),children:[s.jsx(ko,{className:"mr-2 h-4 w-4"}),c.event_date?Vn(c.event_date,"PPP"):"Pick a date"]})}),s.jsx(RT,{className:"w-auto p-0",align:"start",children:s.jsx(Oye,{mode:"single",selected:c.event_date,onSelect:je=>a({...c,event_date:je}),initialFocus:!0,className:"p-3 pointer-events-auto"})})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"time",children:"Time *"}),s.jsx(Et,{id:"time",type:"time",value:c.event_time,onChange:je=>a({...c,event_time:je.target.value}),required:!0})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"zoom_link",children:"Zoom Link *"}),s.jsx(Et,{id:"zoom_link",value:c.zoom_link,onChange:je=>a({...c,zoom_link:je.target.value}),placeholder:"https://zoom.us/j/...",required:!0})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"zoom_meeting_id",children:"Zoom Meeting ID (for API registration)"}),s.jsx(Et,{id:"zoom_meeting_id",value:c.zoom_meeting_id,onChange:je=>a({...c,zoom_meeting_id:je.target.value}),placeholder:"e.g., 1234567890 (find in Zoom dashboard)"}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Optional: Enter the numeric meeting ID for automatic Zoom registration"})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"video_url",children:"Promo Video URL (optional)"}),s.jsx(Et,{id:"video_url",value:c.video_url,onChange:je=>a({...c,video_url:je.target.value}),placeholder:"YouTube, Vimeo, or Bunny.net embed URL"}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Add a preview/promo video for this event"})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"capacity",children:"Capacity (optional)"}),s.jsx(Et,{id:"capacity",type:"number",value:c.capacity,onChange:je=>a({...c,capacity:je.target.value}),placeholder:"Leave empty for unlimited",min:"1"})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx(mt,{htmlFor:"is_published",children:"Published"}),s.jsx(ri,{id:"is_published",checked:c.is_published,onCheckedChange:je=>a({...c,is_published:je})})]}),s.jsxs("div",{className:"flex gap-2 pt-4",children:[s.jsx(de,{type:"button",variant:"outline",onClick:Se,className:"flex-1",children:"Cancel"}),s.jsx(de,{type:"submit",className:"flex-1",disabled:pe.isPending||ve.isPending||N,children:N?"Uploading...":i?"Update Event":"Create Event"})]})]})]})]})]}),s.jsx(ct,{children:W?s.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading events..."}):(z==null?void 0:z.length)===0?s.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No events yet. Create your first event!"}):s.jsxs(ni,{children:[s.jsx(si,{children:s.jsxs(Dr,{children:[s.jsx(Nt,{children:"Title"}),s.jsx(Nt,{children:"Date & Time"}),s.jsx(Nt,{children:"Registrations"}),s.jsx(Nt,{children:"Status"}),s.jsx(Nt,{className:"text-right",children:"Actions"})]})}),s.jsx(ii,{children:z==null?void 0:z.map(je=>s.jsxs(Dr,{children:[s.jsx(xt,{className:"font-medium",children:je.title}),s.jsx(xt,{children:Vn(new Date(je.event_date),"PPP p")}),s.jsx(xt,{children:s.jsxs(de,{variant:"ghost",size:"sm",className:"gap-1",onClick:()=>te(je),children:[s.jsx(_i,{className:"h-4 w-4"}),(V==null?void 0:V[je.id])||0,je.capacity&&` / ${je.capacity}`]})}),s.jsx(xt,{children:s.jsx("span",{className:ar("px-2 py-1 rounded-full text-xs font-medium",je.is_published?"bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200":"bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200"),children:je.is_published?"Published":"Draft"})}),s.jsx(xt,{className:"text-right",children:s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(de,{variant:"ghost",size:"icon",onClick:()=>window.open(je.zoom_link,"_blank"),title:"Open Zoom Link",children:s.jsx(oa,{className:"h-4 w-4"})}),s.jsx(de,{variant:"ghost",size:"icon",onClick:()=>ke(je),children:s.jsx(io,{className:"h-4 w-4"})}),s.jsx(de,{variant:"ghost",size:"icon",onClick:()=>{confirm("Are you sure you want to delete this event?")&&ge.mutate(je.id)},children:s.jsx(oi,{className:"h-4 w-4 text-destructive"})})]})})]},je.id))})]})})]}),s.jsx(mn,{open:A,onOpenChange:I,children:s.jsxs(pn,{className:"max-w-2xl max-h-[80vh] overflow-y-auto",children:[s.jsx(xn,{children:s.jsxs(gn,{className:"flex items-center gap-2",children:[s.jsx(_i,{className:"h-5 w-5"}),"Registrations: ",O==null?void 0:O.title]})}),s.jsxs("div",{className:"flex items-center justify-between mb-4",children:[s.jsxs("p",{className:"text-sm text-muted-foreground",children:[(K==null?void 0:K.length)||0," registered attendee",(K==null?void 0:K.length)!==1?"s":""," (local)"]}),(O==null?void 0:O.zoom_meeting_id)&&s.jsxs(de,{variant:"outline",size:"sm",onClick:()=>X.mutate(O.id),disabled:X.isPending,children:[s.jsx(R1,{className:ar("h-4 w-4 mr-2",X.isPending&&"animate-spin")}),X.isPending?"Syncing...":"Sync from Zoom"]})]}),Q?s.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading registrations..."}):(K==null?void 0:K.length)===0?s.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[s.jsx("p",{children:"No registrations yet for this event."}),(O==null?void 0:O.zoom_meeting_id)&&s.jsx("p",{className:"text-xs mt-2",children:'Click "Sync from Zoom" to import registrations from Zoom.'})]}):s.jsx("div",{className:"space-y-4",children:s.jsxs(ni,{children:[s.jsx(si,{children:s.jsxs(Dr,{children:[s.jsx(Nt,{children:"Name"}),s.jsx(Nt,{children:"Email"}),s.jsx(Nt,{children:"Registered"}),s.jsx(Nt,{children:"Zoom Status"})]})}),s.jsx(ii,{children:K==null?void 0:K.map(je=>{var Ye,pt;const et=((Ye=je.profiles)==null?void 0:Ye.name)||je.zoom_name||"Unknown",bt=((pt=je.profiles)==null?void 0:pt.email)||je.zoom_email||null,_e=!je.user_id;return s.jsxs(Dr,{children:[s.jsx(xt,{className:"font-medium",children:s.jsxs("div",{className:"flex items-center gap-2",children:[et,_e&&s.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-muted text-muted-foreground",children:"External"})]})}),s.jsx(xt,{children:bt?s.jsxs("a",{href:`mailto:${bt}`,className:"flex items-center gap-1 text-primary hover:underline",children:[s.jsx(Fo,{className:"h-3 w-3"}),bt]}):s.jsx("span",{className:"text-muted-foreground",children:"No email"})}),s.jsx(xt,{className:"text-muted-foreground text-sm",children:Vn(new Date(je.registered_at),"MMM d, yyyy h:mm a")}),s.jsx(xt,{children:je.zoom_join_url?s.jsx("span",{className:"inline-flex items-center gap-1 text-xs px-2 py-1 rounded-full bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200",children:"Registered"}):s.jsx("span",{className:"inline-flex items-center gap-1 text-xs px-2 py-1 rounded-full bg-muted text-muted-foreground",children:"Pending"})})]},je.id)})})]})})]})})]})})}const r9e=()=>{const{user:t}=rn(),{toast:e}=Ri(),r=Wn(),[n,i]=D.useState(!1),[o,c]=D.useState(null),[a,m]=D.useState({name:"",description:"",category_id:"",type_id:"",publish_date:new Date().toISOString().split("T")[0],links:[{title:"",canva_share_link:"",sort_order:0}],guides:[],video_url:""}),[g,_]=D.useState(null),[j,N]=D.useState(0),[C,P]=D.useState(!1),[A,I]=D.useState(null),[O,R]=D.useState(""),[z,W]=D.useState(""),[V,K]=D.useState(""),[Q,te]=D.useState(!1),[X,ie]=D.useState(!1),{data:he=[]}=Sr({queryKey:["template-categories"],queryFn:async()=>{const{data:Be,error:Pe}=await ae.from("template_categories").select("*").order("name");if(Pe)throw Pe;return Be}}),{data:xe=[]}=Sr({queryKey:["template-types"],queryFn:async()=>{const{data:Be,error:Pe}=await ae.from("template_types").select("*").order("name");if(Pe)throw Pe;return Be}}),{data:pe=[],isLoading:ve}=Sr({queryKey:["canva-templates-admin"],queryFn:async()=>{const{data:Be,error:Pe}=await ae.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).order("publish_date",{ascending:!1});if(Pe)throw Pe;const{data:ut,error:jt}=await ae.from("template_links").select("*").order("sort_order");if(jt)throw jt;const{data:$t,error:Ht}=await ae.from("template_guides").select("*").order("sort_order");if(Ht)throw Ht;return Be.map(Kt=>({...Kt,links:(ut==null?void 0:ut.filter(Ar=>Ar.template_id===Kt.id))||[],guides:($t==null?void 0:$t.filter(Ar=>Ar.template_id===Kt.id))||[]}))}}),ge=zr({mutationFn:async Be=>{const{data:Pe,error:ut}=await ae.from("template_categories").insert({name:Be}).select().single();if(ut)throw ut;return Pe},onSuccess:Be=>{r.invalidateQueries({queryKey:["template-categories"]}),m({...a,category_id:Be.id}),W(""),te(!1),e({title:"Category added"})},onError:Be=>{e({title:"Error adding category",description:Be.message,variant:"destructive"})}}),ke=zr({mutationFn:async Be=>{const{data:Pe,error:ut}=await ae.from("template_types").insert({name:Be}).select().single();if(ut)throw ut;return Pe},onSuccess:Be=>{r.invalidateQueries({queryKey:["template-types"]}),m({...a,type_id:Be.id}),K(""),ie(!1),e({title:"Type added"})},onError:Be=>{e({title:"Error adding type",description:Be.message,variant:"destructive"})}}),Ce=zr({mutationFn:async Be=>{var Ht;let Pe=Be.existingImageUrl;if(Be.image){const Lt=Be.image.name.split(".").pop(),Kt=`${Date.now()}-${Math.random().toString(36).substring(7)}.${Lt}`,{error:Ar}=await ae.storage.from("template-previews").upload(Kt,Be.image);if(Ar)throw Ar;const{data:rt}=ae.storage.from("template-previews").getPublicUrl(Kt);Pe=rt.publicUrl}const ut={name:Be.template.name,description:Be.template.description||null,category_id:Be.template.category_id||null,type_id:Be.template.type_id||null,preview_image_url:Pe,video_url:Be.videoUrl||null,publish_date:Be.template.publish_date?new Date(Be.template.publish_date).toISOString():new Date().toISOString(),created_by:t==null?void 0:t.id};let jt=Be.templateId;if(jt){const{error:Lt}=await ae.from("canva_templates").update(ut).eq("id",jt);if(Lt)throw Lt;const{error:Kt}=await ae.from("template_links").delete().eq("template_id",jt);if(Kt)throw Kt;const Ar=((Ht=Be.existingGuides)==null?void 0:Ht.map(_t=>_t.id).filter(Boolean))||[],rt=Be.template.guides.map(_t=>_t.id).filter(Boolean),We=Ar.filter(_t=>!rt.includes(_t));We.length>0&&await ae.from("template_guides").delete().in("id",We)}else{const{data:Lt,error:Kt}=await ae.from("canva_templates").insert(ut).select().single();if(Kt)throw Kt;jt=Lt.id,YGe(Be.template.name,Lt.id)}const $t=Be.template.links.filter(Lt=>Lt.title.trim()&&Lt.canva_share_link.trim());if($t.length>0){const Lt=$t.map((Ar,rt)=>({template_id:jt,title:Ar.title.trim(),canva_share_link:Ar.canva_share_link.trim(),sort_order:rt})),{error:Kt}=await ae.from("template_links").insert(Lt);if(Kt)throw Kt}for(let Lt=0;Lt{r.invalidateQueries({queryKey:["canva-templates-admin"]}),r.invalidateQueries({queryKey:["canva-templates"]}),je(),i(!1),e({title:o?"Template updated":"Template created"})},onError:Be=>{e({title:"Error saving template",description:Be.message,variant:"destructive"})}}),Se=zr({mutationFn:async Be=>{const{error:Pe}=await ae.from("canva_templates").delete().eq("id",Be);if(Pe)throw Pe},onSuccess:()=>{r.invalidateQueries({queryKey:["canva-templates-admin"]}),r.invalidateQueries({queryKey:["canva-templates"]}),e({title:"Template deleted"})},onError:Be=>{e({title:"Error deleting template",description:Be.message,variant:"destructive"})}}),je=()=>{m({name:"",description:"",category_id:"",type_id:"",publish_date:new Date().toISOString().split("T")[0],links:[{title:"",canva_share_link:"",sort_order:0}],guides:[],video_url:""}),I(null),R(""),c(null),te(!1),ie(!1),W(""),K(""),_(null),N(0),P(!1)},et=Be=>{var Pe;c(Be),m({name:Be.name,description:Be.description||"",category_id:Be.category_id||"",type_id:Be.type_id||"",publish_date:Be.publish_date?new Date(Be.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],links:Be.links&&Be.links.length>0?Be.links.map(ut=>({id:ut.id,title:ut.title,canva_share_link:ut.canva_share_link,sort_order:ut.sort_order})):[{title:"",canva_share_link:"",sort_order:0}],guides:((Pe=Be.guides)==null?void 0:Pe.map(ut=>({id:ut.id,name:ut.name,file_url:ut.file_url,file_type:ut.file_type,file_size:ut.file_size,sort_order:ut.sort_order})))||[],video_url:Be.video_url||""}),R(Be.preview_image_url||""),_(null),i(!0)},bt=Be=>{var ut;const Pe=(ut=Be.target.files)==null?void 0:ut[0];Pe&&(I(Pe),R(URL.createObjectURL(Pe)))},_e=()=>{m({...a,links:[...a.links,{title:"",canva_share_link:"",sort_order:a.links.length}]})},Ye=Be=>{if(a.links.length<=1)return;const Pe=a.links.filter((ut,jt)=>jt!==Be);m({...a,links:Pe})},pt=(Be,Pe,ut)=>{const jt=[...a.links];jt[Be]={...jt[Be],[Pe]:ut},m({...a,links:jt})},nt=Be=>{const Pe=Be.target.files;if(!Pe)return;const ut=Array.from(Pe).map((jt,$t)=>({name:jt.name.replace(/\.[^/.]+$/,""),file_url:"",file_type:jt.type,file_size:jt.size,sort_order:a.guides.length+$t,file:jt}));m({...a,guides:[...a.guides,...ut]}),Be.target.value=""},Qt=Be=>{const Pe=a.guides.filter((ut,jt)=>jt!==Be);m({...a,guides:Pe})},gt=(Be,Pe)=>{const ut=[...a.guides];ut[Be]={...ut[Be],name:Pe},m({...a,guides:ut})},Me=async()=>{if(!g)return null;P(!0),N(0);try{const{data:Be,error:Pe}=await ae.functions.invoke("bunny-upload",{body:{action:"create",title:a.name||g.name}});if(Pe)throw new Error(Pe.message);const{videoId:ut,libraryId:jt}=Be,{data:$t,error:Ht}=await ae.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:ut}});if(Ht)throw new Error(Ht.message);const Lt=new XMLHttpRequest;return await new Promise((Ar,rt)=>{Lt.upload.addEventListener("progress",We=>{if(We.lengthComputable){const _t=Math.round(We.loaded/We.total*100);N(_t)}}),Lt.addEventListener("load",()=>{Lt.status>=200&&Lt.status<300?Ar():rt(new Error(`Upload failed with status ${Lt.status}`))}),Lt.addEventListener("error",()=>rt(new Error("Upload failed"))),Lt.open("PUT",$t.uploadUrl),Lt.setRequestHeader("AccessKey",$t.apiKey),Lt.send(g)}),`https://player.mediadelivery.net/embed/${jt}/${ut}`}catch(Be){return console.error("Bunny upload error:",Be),e({title:"Video upload failed",description:Be instanceof Error?Be.message:"Unknown error",variant:"destructive"}),null}finally{P(!1)}},Oe=Be=>{var ut;const Pe=(ut=Be.target.files)==null?void 0:ut[0];Pe&&_(Pe),Be.target.value=""},Ie=async Be=>{if(Be.preventDefault(),!a.name.trim()){e({title:"Please enter a template name",variant:"destructive"});return}if(a.links.filter(jt=>jt.title.trim()&&jt.canva_share_link.trim()).length===0){e({title:"Please add at least one Canva link",variant:"destructive"});return}let ut=a.video_url;if(g){const jt=await Me();if(!jt)return;ut=jt}Ce.mutate({template:a,image:A,existingImageUrl:(o==null?void 0:o.preview_image_url)||null,templateId:o==null?void 0:o.id,existingGuides:o==null?void 0:o.guides,videoUrl:ut})};return s.jsx(Jr,{title:"Manage Templates",children:s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[s.jsxs(at,{children:[s.jsx(xr,{className:"pb-2",children:s.jsx(wr,{className:"text-sm font-medium text-muted-foreground",children:"Total Templates"})}),s.jsx(ct,{children:s.jsx("div",{className:"text-2xl font-bold",children:pe.length})})]}),s.jsxs(at,{children:[s.jsx(xr,{className:"pb-2",children:s.jsx(wr,{className:"text-sm font-medium text-muted-foreground",children:"Categories"})}),s.jsx(ct,{children:s.jsx("div",{className:"text-2xl font-bold",children:he.length})})]}),s.jsxs(at,{children:[s.jsx(xr,{className:"pb-2",children:s.jsx(wr,{className:"text-sm font-medium text-muted-foreground",children:"Template Types"})}),s.jsx(ct,{children:s.jsx("div",{className:"text-2xl font-bold",children:xe.length})})]})]}),s.jsxs(mn,{open:n,onOpenChange:Be=>{i(Be),Be||je()},children:[s.jsx(Do,{asChild:!0,children:s.jsxs(de,{className:"gap-2",children:[s.jsx(Qn,{className:"h-4 w-4"}),"Add Template"]})}),s.jsxs(pn,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[s.jsx(xn,{children:s.jsx(gn,{children:o?"Edit Template":"Add New Template"})}),s.jsxs("form",{onSubmit:Ie,className:"space-y-6 pt-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"name",children:"Name *"}),s.jsx(Et,{id:"name",value:a.name,onChange:Be=>m({...a,name:Be.target.value}),placeholder:"Template name",required:!0})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Description"}),s.jsx(ag,{content:a.description,onChange:Be=>m({...a,description:Be}),placeholder:"Brief description of the template",minHeight:"120px"})]}),s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx(mt,{children:"Canva Links *"}),s.jsxs(de,{type:"button",variant:"outline",size:"sm",onClick:_e,className:"gap-1",children:[s.jsx(Qn,{className:"h-3 w-3"}),"Add Link"]})]}),s.jsx("div",{className:"space-y-3",children:a.links.map((Be,Pe)=>s.jsxs("div",{className:"flex gap-2 items-start p-3 border rounded-lg bg-muted/30",children:[s.jsxs("div",{className:"flex-1 space-y-2",children:[s.jsx(Et,{value:Be.title,onChange:ut=>pt(Pe,"title",ut.target.value),placeholder:"Link title (e.g., Instagram Post, Story)"}),s.jsx(Et,{value:Be.canva_share_link,onChange:ut=>pt(Pe,"canva_share_link",ut.target.value),placeholder:"https://www.canva.com/design/..."})]}),a.links.length>1&&s.jsx(de,{type:"button",variant:"ghost",size:"icon",className:"shrink-0 text-muted-foreground hover:text-destructive",onClick:()=>Ye(Pe),children:s.jsx(Ni,{className:"h-4 w-4"})})]},Pe))})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Category"}),Q?s.jsxs("div",{className:"flex gap-2",children:[s.jsx(Et,{value:z,onChange:Be=>W(Be.target.value),placeholder:"New category name",className:"flex-1"}),s.jsx(de,{type:"button",size:"sm",onClick:()=>z.trim()&&ge.mutate(z.trim()),disabled:ge.isPending,children:"Add"}),s.jsx(de,{type:"button",size:"sm",variant:"ghost",onClick:()=>{te(!1),W("")},children:s.jsx(Ni,{className:"h-4 w-4"})})]}):s.jsxs("div",{className:"flex gap-2",children:[s.jsxs(Kn,{value:a.category_id,onValueChange:Be=>m({...a,category_id:Be}),children:[s.jsx(qn,{className:"flex-1",children:s.jsx(Zn,{placeholder:"Select category"})}),s.jsx(Hn,{children:he.map(Be=>s.jsx(_r,{value:Be.id,children:Be.name},Be.id))})]}),s.jsx(de,{type:"button",variant:"outline",size:"icon",onClick:()=>te(!0),children:s.jsx(Qn,{className:"h-4 w-4"})})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Template Type"}),X?s.jsxs("div",{className:"flex gap-2",children:[s.jsx(Et,{value:V,onChange:Be=>K(Be.target.value),placeholder:"New type name",className:"flex-1"}),s.jsx(de,{type:"button",size:"sm",onClick:()=>V.trim()&&ke.mutate(V.trim()),disabled:ke.isPending,children:"Add"}),s.jsx(de,{type:"button",size:"sm",variant:"ghost",onClick:()=>{ie(!1),K("")},children:s.jsx(Ni,{className:"h-4 w-4"})})]}):s.jsxs("div",{className:"flex gap-2",children:[s.jsxs(Kn,{value:a.type_id,onValueChange:Be=>m({...a,type_id:Be}),children:[s.jsx(qn,{className:"flex-1",children:s.jsx(Zn,{placeholder:"Select type"})}),s.jsx(Hn,{children:xe.map(Be=>s.jsx(_r,{value:Be.id,children:Be.name},Be.id))})]}),s.jsx(de,{type:"button",variant:"outline",size:"icon",onClick:()=>ie(!0),children:s.jsx(Qn,{className:"h-4 w-4"})})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"publish_date",children:"Publish Date"}),s.jsx(Et,{id:"publish_date",type:"date",value:a.publish_date,onChange:Be=>m({...a,publish_date:Be.target.value})}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Templates are sorted by publish date (newest first) on the member page"})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Preview Image"}),s.jsxs("div",{className:"flex items-start gap-4",children:[O?s.jsxs("div",{className:"relative w-32 h-24 rounded-lg overflow-hidden border bg-muted",children:[s.jsx("img",{src:O,alt:"Preview",className:"w-full h-full object-cover"}),s.jsx(de,{type:"button",size:"icon",variant:"destructive",className:"absolute top-1 right-1 h-6 w-6",onClick:()=>{I(null),R("")},children:s.jsx(Ni,{className:"h-3 w-3"})})]}):s.jsx("div",{className:"w-32 h-24 rounded-lg border-2 border-dashed border-muted-foreground/25 flex items-center justify-center",children:s.jsx(Wm,{className:"h-8 w-8 text-muted-foreground/50"})}),s.jsxs("div",{className:"flex-1",children:[s.jsx(Et,{type:"file",accept:"image/*",onChange:bt,className:"cursor-pointer"}),s.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Upload a preview image for this template"})]})]})]}),s.jsxs("div",{className:"space-y-3",children:[s.jsx(mt,{children:"Video (Optional)"}),a.video_url&&!g?s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg bg-muted/30",children:[s.jsx(Ia,{className:"h-5 w-5 text-primary shrink-0"}),s.jsx("span",{className:"text-sm flex-1 truncate",children:"Video uploaded"}),s.jsx(de,{type:"button",variant:"ghost",size:"sm",onClick:()=>m({...a,video_url:""}),className:"text-destructive hover:text-destructive",children:"Remove"})]}),s.jsx("div",{className:"aspect-video max-w-md rounded-lg overflow-hidden border",children:s.jsx("iframe",{src:a.video_url,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})]}):C?s.jsxs("div",{className:"space-y-2 p-4 border rounded-lg bg-muted/30",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Ps,{className:"h-4 w-4 animate-spin"}),s.jsxs("span",{className:"text-sm",children:["Uploading video... ",j,"%"]})]}),s.jsx(vc,{value:j,className:"h-2"})]}):g?s.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg bg-muted/30",children:[s.jsx(Ia,{className:"h-5 w-5 text-muted-foreground shrink-0"}),s.jsx("span",{className:"text-sm flex-1 truncate",children:g.name}),s.jsxs("span",{className:"text-xs text-muted-foreground shrink-0",children:[(g.size/1024/1024).toFixed(1)," MB"]}),s.jsx(de,{type:"button",variant:"ghost",size:"icon",className:"shrink-0 text-muted-foreground hover:text-destructive h-8 w-8",onClick:()=>_(null),children:s.jsx(Ni,{className:"h-4 w-4"})})]}):s.jsxs("div",{className:"space-y-2",children:[s.jsxs("label",{className:"cursor-pointer",children:[s.jsx(Et,{type:"file",accept:"video/*",onChange:Oe,className:"hidden"}),s.jsxs("div",{className:"flex items-center justify-center gap-2 p-6 border-2 border-dashed rounded-lg hover:border-primary/50 transition-colors",children:[s.jsx(Ia,{className:"h-8 w-8 text-muted-foreground/50"}),s.jsx("span",{className:"text-sm text-muted-foreground",children:"Click to upload a video"})]})]}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Upload a video to embed on the template page (Bunny.net)"})]})]}),s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx(mt,{children:"Guide Files (PDFs)"}),s.jsxs("label",{className:"cursor-pointer",children:[s.jsx(Et,{type:"file",accept:".pdf,.doc,.docx",multiple:!0,onChange:nt,className:"hidden"}),s.jsx(de,{type:"button",variant:"outline",size:"sm",className:"gap-1",asChild:!0,children:s.jsxs("span",{children:[s.jsx(Vu,{className:"h-3 w-3"}),"Add Files"]})})]})]}),a.guides.length>0?s.jsx("div",{className:"space-y-2",children:a.guides.map((Be,Pe)=>s.jsxs("div",{className:"flex gap-2 items-center p-3 border rounded-lg bg-muted/30",children:[s.jsx(Ii,{className:"h-5 w-5 text-muted-foreground shrink-0"}),s.jsx(Et,{value:Be.name,onChange:ut=>gt(Pe,ut.target.value),placeholder:"Guide name",className:"flex-1"}),Be.file_size&&s.jsxs("span",{className:"text-xs text-muted-foreground shrink-0",children:[(Be.file_size/1024).toFixed(0)," KB"]}),s.jsx(de,{type:"button",variant:"ghost",size:"icon",className:"shrink-0 text-muted-foreground hover:text-destructive h-8 w-8",onClick:()=>Qt(Pe),children:s.jsx(Ni,{className:"h-4 w-4"})})]},Be.id||Pe))}):s.jsx("p",{className:"text-sm text-muted-foreground",children:"No guide files added. Upload PDFs to help agents understand how to use this template."})]}),s.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[s.jsx(de,{type:"button",variant:"outline",onClick:()=>{i(!1),je()},children:"Cancel"}),s.jsx(de,{type:"submit",disabled:Ce.isPending,children:Ce.isPending?"Saving...":o?"Update":"Create"})]})]})]})]})]}),s.jsx(at,{children:s.jsx(ct,{className:"p-0",children:ve?s.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading..."}):pe.length===0?s.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No templates yet. Add your first template!"}):s.jsxs(ni,{children:[s.jsx(si,{children:s.jsxs(Dr,{children:[s.jsx(Nt,{children:"Preview"}),s.jsx(Nt,{children:"Name"}),s.jsx(Nt,{children:"Links"}),s.jsx(Nt,{children:"Category"}),s.jsx(Nt,{children:"Type"}),s.jsx(Nt,{children:"Publish Date"}),s.jsx(Nt,{className:"text-right",children:"Actions"})]})}),s.jsx(ii,{children:pe.map(Be=>{var Pe,ut,jt,$t,Ht;return s.jsxs(Dr,{children:[s.jsx(xt,{children:s.jsx("div",{className:"w-16 h-12 rounded overflow-hidden bg-muted",children:Be.preview_image_url?s.jsx("img",{src:Be.preview_image_url,alt:Be.name,className:"w-full h-full object-cover"}):s.jsx("div",{className:"w-full h-full flex items-center justify-center",children:s.jsx(Wm,{className:"h-4 w-4 text-muted-foreground"})})})}),s.jsx(xt,{className:"font-medium",children:Be.name}),s.jsx(xt,{children:s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsxs(ir,{variant:"secondary",children:[((Pe=Be.links)==null?void 0:Pe.length)||0," link",(((ut=Be.links)==null?void 0:ut.length)||0)!==1?"s":""]}),(((jt=Be.guides)==null?void 0:jt.length)||0)>0&&s.jsxs(ir,{variant:"outline",className:"gap-1",children:[s.jsx(Ii,{className:"h-3 w-3"}),($t=Be.guides)==null?void 0:$t.length," guide",(((Ht=Be.guides)==null?void 0:Ht.length)||0)!==1?"s":""]})]})}),s.jsx(xt,{children:Be.category?s.jsx(ir,{variant:"secondary",children:Be.category.name}):s.jsx("span",{className:"text-muted-foreground",children:"-"})}),s.jsx(xt,{children:Be.type?s.jsx(ir,{variant:"outline",children:Be.type.name}):s.jsx("span",{className:"text-muted-foreground",children:"-"})}),s.jsx(xt,{className:"text-muted-foreground",children:new Date(Be.publish_date).toLocaleDateString()}),s.jsx(xt,{className:"text-right",children:s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(de,{size:"icon",variant:"ghost",onClick:()=>et(Be),children:s.jsx(io,{className:"h-4 w-4"})}),s.jsx(de,{size:"icon",variant:"ghost",className:"text-destructive hover:text-destructive",onClick:()=>{confirm("Delete this template?")&&Se.mutate(Be.id)},children:s.jsx(oi,{className:"h-4 w-4"})})]})})]},Be.id)})})]})})})]})})},n9e=[{value:"bunny_stream",label:"Bunny.net Stream (Upload)"},{value:"youtube",label:"YouTube"},{value:"vimeo",label:"Vimeo"},{value:"google_drive",label:"Google Drive"},{value:"amazon_s3",label:"Amazon S3"},{value:"loom",label:"Loom"},{value:"other",label:"Other"}],s9e=()=>{const{user:t}=rn(),{toast:e}=Ri(),r=Wn(),[n,i]=D.useState(!1),[o,c]=D.useState(null),[a,m]=D.useState({title:"",description:"",video_url:"",video_type:"youtube",duration:"",category_id:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),[g,_]=D.useState(null),[j,N]=D.useState(""),[C,P]=D.useState([]),[A,I]=D.useState([]),[O,R]=D.useState([]),[z,W]=D.useState(""),[V,K]=D.useState(!1),[Q,te]=D.useState(null),[X,ie]=D.useState(0),[he,xe]=D.useState(!1),[pe,ve]=D.useState(null),{data:ge=[]}=Sr({queryKey:["academy-categories"],queryFn:async()=>{const{data:Ie,error:Be}=await ae.from("academy_categories").select("*").order("sort_order",{ascending:!0});if(Be)throw Be;return Ie}}),{data:ke=[],isLoading:Ce}=Sr({queryKey:["academy-videos-admin"],queryFn:async()=>{const{data:Ie,error:Be}=await ae.from("academy_videos").select(` *, category:academy_categories(id, name) `).order("publish_date",{ascending:!1});if(Be)throw Be;const{data:Pe,error:ut}=await ae.from("academy_resources").select("*").order("sort_order");if(ut)throw ut;return Ie.map($t=>({...$t,resources:(Pe==null?void 0:Pe.filter(Ht=>Ht.video_id===$t.id))||[]}))}}),Se=zr({mutationFn:async Ie=>{const{data:Be,error:Pe}=await ae.from("academy_categories").insert({name:Ie,sort_order:ge.length}).select().single();if(Pe)throw Pe;return Be},onSuccess:Ie=>{r.invalidateQueries({queryKey:["academy-categories"]}),m({...a,category_id:Ie.id}),W(""),K(!1),e({title:"Category added"})},onError:Ie=>{e({title:"Error adding category",description:Ie.message,variant:"destructive"})}}),je=zr({mutationFn:async Ie=>{let Be=Ie.existingThumbnailUrl;if(Ie.thumbnail){const jt=Ie.thumbnail.name.split(".").pop(),$t=`thumbnails/${Date.now()}-${Math.random().toString(36).substring(7)}.${jt}`,{error:Ht}=await ae.storage.from("academy-resources").upload($t,Ie.thumbnail);if(Ht)throw Ht;const{data:Lt}=ae.storage.from("academy-resources").getPublicUrl($t);Be=Lt.publicUrl}const Pe={title:Ie.video.title,description:Ie.video.description||null,video_url:Ie.video.video_url,video_type:Ie.video.video_type,duration:Ie.video.duration||null,thumbnail_url:Be,category_id:Ie.video.category_id||null,publish_date:Ie.video.publish_date?new Date(Ie.video.publish_date).toISOString():new Date().toISOString(),is_published:Ie.video.is_published,created_by:t==null?void 0:t.id};let ut=Ie.videoId;if(ut){const{error:jt}=await ae.from("academy_videos").update(Pe).eq("id",ut);if(jt)throw jt}else{const{data:jt,error:$t}=await ae.from("academy_videos").insert(Pe).select().single();if($t)throw $t;ut=jt.id,XGe(Ie.video.title,jt.id)}if(Ie.resourcesToDelete.length>0){const{error:jt}=await ae.from("academy_resources").delete().in("id",Ie.resourcesToDelete);if(jt)throw jt}for(let jt=0;jt{r.invalidateQueries({queryKey:["academy-videos-admin"]}),r.invalidateQueries({queryKey:["academy-videos"]}),_e(),i(!1),e({title:o?"Video updated":"Video created"})},onError:Ie=>{e({title:"Error saving video",description:Ie.message,variant:"destructive"})}}),et=zr({mutationFn:async Ie=>{const{error:Be}=await ae.from("academy_videos").delete().eq("id",Ie);if(Be)throw Be},onSuccess:()=>{r.invalidateQueries({queryKey:["academy-videos-admin"]}),r.invalidateQueries({queryKey:["academy-videos"]}),e({title:"Video deleted"})},onError:Ie=>{e({title:"Error deleting video",description:Ie.message,variant:"destructive"})}}),bt=zr({mutationFn:async({id:Ie,is_published:Be})=>{const{error:Pe}=await ae.from("academy_videos").update({is_published:Be}).eq("id",Ie);if(Pe)throw Pe},onSuccess:()=>{r.invalidateQueries({queryKey:["academy-videos-admin"]}),r.invalidateQueries({queryKey:["academy-videos"]})},onError:Ie=>{e({title:"Error updating video",description:Ie.message,variant:"destructive"})}}),_e=()=>{m({title:"",description:"",video_url:"",video_type:"bunny_stream",duration:"",category_id:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),_(null),N(""),P([]),I([]),R([]),c(null),K(!1),W(""),te(null),ie(0),xe(!1),ve(null)},Ye=Ie=>{c(Ie),m({title:Ie.title,description:Ie.description||"",video_url:Ie.video_url,video_type:Ie.video_type,duration:Ie.duration||"",category_id:Ie.category_id||"",publish_date:Ie.publish_date?new Date(Ie.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],is_published:Ie.is_published}),N(Ie.thumbnail_url||""),I(Ie.resources||[]),P([]),R([]),i(!0)},pt=Ie=>{var Pe;const Be=(Pe=Ie.target.files)==null?void 0:Pe[0];Be&&(_(Be),N(URL.createObjectURL(Be)))},nt=Ie=>{const Be=Ie.target.files;if(Be){const Pe=Array.from(Be).map(ut=>({file:ut,title:ut.name.replace(/\.[^/.]+$/,"")}));P([...C,...Pe])}Ie.target.value=""},Qt=Ie=>{P(C.filter((Be,Pe)=>Pe!==Ie))},gt=Ie=>{R([...O,Ie]),I(A.filter(Be=>Be.id!==Ie))},Me=async()=>{if(!Q)return null;xe(!0),ie(0);try{const{data:Ie,error:Be}=await ae.functions.invoke("bunny-upload",{body:{action:"create",title:a.title||Q.name}});if(Be)throw new Error(Be.message);const{videoId:Pe,libraryId:ut}=Ie;ve(Pe);const{data:jt,error:$t}=await ae.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:Pe}});if($t)throw new Error($t.message);const Ht=new XMLHttpRequest;return await new Promise((Kt,Ar)=>{Ht.upload.addEventListener("progress",rt=>{if(rt.lengthComputable){const We=Math.round(rt.loaded/rt.total*100);ie(We)}}),Ht.addEventListener("load",()=>{Ht.status>=200&&Ht.status<300?Kt():Ar(new Error(`Upload failed with status ${Ht.status}`))}),Ht.addEventListener("error",()=>Ar(new Error("Upload failed"))),Ht.open("PUT",jt.uploadUrl),Ht.setRequestHeader("AccessKey",jt.apiKey),Ht.send(Q)}),`https://player.mediadelivery.net/embed/${ut}/${Pe}`}catch(Ie){return console.error("Bunny upload error:",Ie),e({title:"Video upload failed",description:Ie instanceof Error?Ie.message:"Unknown error",variant:"destructive"}),null}finally{xe(!1)}},Oe=async Ie=>{if(Ie.preventDefault(),!a.title.trim()){e({title:"Please enter a video title",variant:"destructive"});return}let Be=a.video_url;if(a.video_type==="bunny_stream"&&Q&&!o){const Pe=await Me();if(!Pe)return;Be=Pe}else if(!a.video_url.trim()&&a.video_type!=="bunny_stream"){e({title:"Please enter a video URL",variant:"destructive"});return}else if(a.video_type==="bunny_stream"&&!Q&&!a.video_url&&!o){e({title:"Please select a video file to upload",variant:"destructive"});return}je.mutate({video:{...a,video_url:Be},thumbnail:g,existingThumbnailUrl:(o==null?void 0:o.thumbnail_url)||null,videoId:o==null?void 0:o.id,newResources:C,resourcesToDelete:O})};return s.jsx(Jr,{title:"Manage Academy",children:s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsxs(at,{children:[s.jsx(xr,{className:"pb-2",children:s.jsx(wr,{className:"text-sm font-medium text-muted-foreground",children:"Total Videos"})}),s.jsx(ct,{children:s.jsx("div",{className:"text-2xl font-bold",children:ke.length})})]}),s.jsxs(at,{children:[s.jsx(xr,{className:"pb-2",children:s.jsx(wr,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),s.jsx(ct,{children:s.jsx("div",{className:"text-2xl font-bold",children:ke.filter(Ie=>Ie.is_published).length})})]})]}),s.jsxs(mn,{open:n,onOpenChange:Ie=>{i(Ie),Ie||_e()},children:[s.jsx(Do,{asChild:!0,children:s.jsxs(de,{className:"gap-2",children:[s.jsx(Qn,{className:"h-4 w-4"}),"Add Video"]})}),s.jsxs(pn,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[s.jsx(xn,{children:s.jsx(gn,{children:o?"Edit Video":"Add New Video"})}),s.jsxs("form",{onSubmit:Oe,className:"space-y-6 pt-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"title",children:"Title *"}),s.jsx(Et,{id:"title",value:a.title,onChange:Ie=>m({...a,title:Ie.target.value}),placeholder:"Video title",required:!0})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Description"}),s.jsx(ag,{content:a.description,onChange:Ie=>m({...a,description:Ie}),placeholder:"Brief description of the video",minHeight:"120px"})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Video Type"}),s.jsxs(Kn,{value:a.video_type,onValueChange:Ie=>{m({...a,video_type:Ie,video_url:""}),te(null)},disabled:he,children:[s.jsx(qn,{children:s.jsx(Zn,{})}),s.jsx(Hn,{children:n9e.map(Ie=>s.jsx(_r,{value:Ie.value,children:Ie.label},Ie.value))})]})]}),a.video_type==="bunny_stream"?s.jsxs("div",{className:"space-y-3",children:[s.jsxs(mt,{children:["Upload Video File ",!o&&"*"]}),o&&a.video_url&&s.jsxs("p",{className:"text-sm text-muted-foreground",children:["Current video: ",s.jsx("a",{href:a.video_url,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline",children:"View"})]}),!o&&s.jsxs(s.Fragment,{children:[s.jsx(Et,{type:"file",accept:"video/*",onChange:Ie=>{var Pe;const Be=(Pe=Ie.target.files)==null?void 0:Pe[0];Be&&te(Be)},disabled:he}),Q&&s.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[s.jsx(Ia,{className:"h-4 w-4"}),Q.name," (",(Q.size/(1024*1024)).toFixed(1)," MB)"]}),he&&s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Ps,{className:"h-4 w-4 animate-spin"}),s.jsx("span",{className:"text-sm",children:"Uploading to Bunny.net..."})]}),s.jsx(vc,{value:X,className:"h-2"}),s.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[X,"%"]})]})]})]}):s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"video_url",children:"Video URL *"}),s.jsx(Et,{id:"video_url",value:a.video_url,onChange:Ie=>m({...a,video_url:Ie.target.value}),placeholder:"https://...",required:!0})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"duration",children:"Duration"}),s.jsx(Et,{id:"duration",value:a.duration,onChange:Ie=>m({...a,duration:Ie.target.value}),placeholder:"e.g., 45:30"})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"publish_date",children:"Publish Date"}),s.jsx(Et,{id:"publish_date",type:"date",value:a.publish_date,onChange:Ie=>m({...a,publish_date:Ie.target.value})})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Category"}),V?s.jsxs("div",{className:"flex gap-2",children:[s.jsx(Et,{value:z,onChange:Ie=>W(Ie.target.value),placeholder:"New category name",className:"flex-1"}),s.jsx(de,{type:"button",size:"sm",onClick:()=>z.trim()&&Se.mutate(z.trim()),disabled:Se.isPending,children:"Add"}),s.jsx(de,{type:"button",size:"sm",variant:"ghost",onClick:()=>{K(!1),W("")},children:s.jsx(Ni,{className:"h-4 w-4"})})]}):s.jsxs("div",{className:"flex gap-2",children:[s.jsxs(Kn,{value:a.category_id,onValueChange:Ie=>m({...a,category_id:Ie}),children:[s.jsx(qn,{className:"flex-1",children:s.jsx(Zn,{placeholder:"Select category"})}),s.jsx(Hn,{children:ge.map(Ie=>s.jsx(_r,{value:Ie.id,children:Ie.name},Ie.id))})]}),s.jsx(de,{type:"button",variant:"outline",size:"sm",onClick:()=>K(!0),children:s.jsx(Qn,{className:"h-4 w-4"})})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Thumbnail Image"}),s.jsxs("div",{className:"flex items-start gap-4",children:[j&&s.jsx("img",{src:j,alt:"Thumbnail preview",className:"w-32 h-20 object-cover rounded-md border"}),s.jsxs("div",{className:"flex-1",children:[s.jsx(Et,{type:"file",accept:"image/*",onChange:pt,className:"cursor-pointer"}),s.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Recommended: 16:9 aspect ratio"})]})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx(mt,{children:"Resource Files"}),s.jsx(de,{type:"button",variant:"outline",size:"sm",asChild:!0,children:s.jsxs("label",{className:"cursor-pointer gap-1",children:[s.jsx(Vu,{className:"h-3 w-3"}),"Add Files",s.jsx("input",{type:"file",multiple:!0,accept:".pdf,.pptx,.ppt,.xlsx,.xls,.docx,.doc,.zip",onChange:nt,className:"hidden"})]})})]}),(A.length>0||C.length>0)&&s.jsxs("div",{className:"space-y-2 mt-2",children:[A.map(Ie=>s.jsxs("div",{className:"flex items-center gap-2 p-2 border rounded-md bg-muted/30",children:[s.jsx(Ii,{className:"h-4 w-4 text-muted-foreground"}),s.jsx("span",{className:"flex-1 text-sm truncate",children:Ie.title}),s.jsx(ir,{variant:"outline",className:"text-xs",children:Ie.file_type}),s.jsx(de,{type:"button",variant:"ghost",size:"sm",onClick:()=>gt(Ie.id),className:"text-destructive hover:text-destructive",children:s.jsx(Ni,{className:"h-4 w-4"})})]},Ie.id)),C.map((Ie,Be)=>s.jsxs("div",{className:"flex items-center gap-2 p-2 border rounded-md bg-muted/30",children:[s.jsx(Ii,{className:"h-4 w-4 text-muted-foreground"}),s.jsx(Et,{value:Ie.title,onChange:Pe=>{const ut=[...C];ut[Be].title=Pe.target.value,P(ut)},className:"flex-1 h-8",placeholder:"Resource title"}),s.jsx(ir,{variant:"secondary",className:"text-xs",children:"New"}),s.jsx(de,{type:"button",variant:"ghost",size:"sm",onClick:()=>Qt(Be),className:"text-destructive hover:text-destructive",children:s.jsx(Ni,{className:"h-4 w-4"})})]},Be))]}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Supported: PDF, PowerPoint, Excel, Word, ZIP"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(ri,{id:"is_published",checked:a.is_published,onCheckedChange:Ie=>m({...a,is_published:Ie})}),s.jsx(mt,{htmlFor:"is_published",children:"Published"})]}),s.jsxs(zi,{children:[s.jsx(de,{type:"button",variant:"outline",onClick:()=>i(!1),disabled:he,children:"Cancel"}),s.jsx(de,{type:"submit",disabled:je.isPending||he,children:he?s.jsxs(s.Fragment,{children:[s.jsx(Ps,{className:"h-4 w-4 mr-2 animate-spin"}),"Uploading..."]}):je.isPending?"Saving...":o?"Update Video":"Add Video"})]})]})]})]})]}),s.jsx(at,{children:s.jsx(ct,{className:"p-0",children:Ce?s.jsx("div",{className:"flex justify-center py-8",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):ke.length===0?s.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[s.jsx(Ia,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),s.jsx("p",{children:"No videos yet"}),s.jsx("p",{className:"text-sm",children:"Add your first academy video"})]}):s.jsxs(ni,{children:[s.jsx(si,{children:s.jsxs(Dr,{children:[s.jsx(Nt,{children:"Title"}),s.jsx(Nt,{children:"Category"}),s.jsx(Nt,{children:"Duration"}),s.jsx(Nt,{children:"Resources"}),s.jsx(Nt,{children:"Publish Date"}),s.jsx(Nt,{children:"Status"}),s.jsx(Nt,{className:"w-[120px]",children:"Actions"})]})}),s.jsx(ii,{children:ke.map(Ie=>s.jsxs(Dr,{children:[s.jsx(xt,{children:s.jsxs("div",{className:"flex items-center gap-3",children:[Ie.thumbnail_url?s.jsx("img",{src:Ie.thumbnail_url,alt:"",className:"w-16 h-10 object-cover rounded"}):s.jsx("div",{className:"w-16 h-10 bg-muted rounded flex items-center justify-center",children:s.jsx(Ia,{className:"h-4 w-4 text-muted-foreground"})}),s.jsxs("div",{children:[s.jsx("p",{className:"font-medium",children:Ie.title}),s.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:Ie.video_type.replace("_"," ")})]})]})}),s.jsx(xt,{children:Ie.category?s.jsx(ir,{variant:"outline",children:Ie.category.name}):s.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),s.jsx(xt,{children:Ie.duration||"-"}),s.jsx(xt,{children:Ie.resources&&Ie.resources.length>0?s.jsxs(ir,{variant:"secondary",children:[Ie.resources.length," file(s)"]}):s.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),s.jsx(xt,{children:new Date(Ie.publish_date).toLocaleDateString()}),s.jsx(xt,{children:s.jsx(ri,{checked:Ie.is_published,onCheckedChange:Be=>bt.mutate({id:Ie.id,is_published:Be})})}),s.jsx(xt,{children:s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsx(de,{variant:"ghost",size:"sm",onClick:()=>Ye(Ie),children:s.jsx(io,{className:"h-4 w-4"})}),s.jsx(de,{variant:"ghost",size:"sm",onClick:()=>et.mutate(Ie.id),className:"text-destructive hover:text-destructive",children:s.jsx(oi,{className:"h-4 w-4"})})]})})]},Ie.id))})]})})})]})})};function i9e(){var je,et,bt;const t=Wn(),[e,r]=D.useState(!1),[n,i]=D.useState(null),[o,c]=D.useState({name:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),[a,m]=D.useState(null),[g,_]=D.useState(""),[j,N]=D.useState([]),[C,P]=D.useState([]),[A,I]=D.useState(null),{data:O,isLoading:R}=Sr({queryKey:["resource-kits"],queryFn:async()=>{const{data:_e,error:Ye}=await ae.from("resource_kits").select("*").order("publish_date",{ascending:!1});if(Ye)throw Ye;return _e}}),{data:z}=Sr({queryKey:["resource-kit-files"],queryFn:async()=>{const{data:_e,error:Ye}=await ae.from("resource_kit_files").select("*").order("sort_order",{ascending:!0});if(Ye)throw Ye;return _e}}),{data:W}=Sr({queryKey:["resource-kit-links"],queryFn:async()=>{const{data:_e,error:Ye}=await ae.from("resource_kit_links").select("*").order("sort_order",{ascending:!0});if(Ye)throw Ye;return _e}}),V=()=>{c({name:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),m(null),_(""),N([]),P([]),i(null)},K=_e=>{i(_e),c({name:_e.name,description:_e.description||"",publish_date:_e.publish_date.split("T")[0],is_published:_e.is_published}),_(_e.featured_image_url||"");const Ye=(z==null?void 0:z.filter(nt=>nt.kit_id===_e.id))||[];N(Ye.map(nt=>({id:nt.id,name:nt.name,file_url:nt.file_url,file_type:nt.file_type,file_size:nt.file_size,sort_order:nt.sort_order})));const pt=(W==null?void 0:W.filter(nt=>nt.kit_id===_e.id))||[];P(pt.map(nt=>({id:nt.id,title:nt.title,canva_share_link:nt.canva_share_link,sort_order:nt.sort_order}))),r(!0)},Q=_e=>{var pt;const Ye=(pt=_e.target.files)==null?void 0:pt[0];Ye&&(m(Ye),_(URL.createObjectURL(Ye)))},te=()=>{N([...j,{name:"",file_url:"",sort_order:j.length}])},X=_e=>{N(j.filter((Ye,pt)=>pt!==_e))},ie=(_e,Ye,pt)=>{const nt=[...j];nt[_e]={...nt[_e],[Ye]:pt},N(nt)},he=()=>{P([...C,{title:"",canva_share_link:"",sort_order:C.length}])},xe=_e=>{P(C.filter((Ye,pt)=>pt!==_e))},pe=(_e,Ye,pt)=>{const nt=[...C];nt[_e]={...nt[_e],[Ye]:pt},P(nt)},ve=(_e,Ye)=>{var nt;const pt=(nt=Ye.target.files)==null?void 0:nt[0];if(pt){const Qt=[...j],gt=pt.name.replace(/\.[^/.]+$/,"");Qt[_e]={...Qt[_e],file:pt,file_type:pt.type,file_size:pt.size,name:Qt[_e].name||gt},N(Qt)}},ge=zr({mutationFn:async()=>{let _e=(n==null?void 0:n.featured_image_url)||null;if(a){const gt=a.name.split(".").pop(),Me=`${Date.now()}.${gt}`,{error:Oe}=await ae.storage.from("resource-kits").upload(`featured/${Me}`,a);if(Oe)throw Oe;const{data:Ie}=ae.storage.from("resource-kits").getPublicUrl(`featured/${Me}`);_e=Ie.publicUrl}const Ye={name:o.name,description:o.description||null,featured_image_url:_e,publish_date:o.publish_date,is_published:o.is_published};let pt;const nt=!n,Qt=(n==null?void 0:n.is_published)||!1;if(n){const{error:gt}=await ae.from("resource_kits").update(Ye).eq("id",n.id);if(gt)throw gt;pt=n.id;const Me=(z==null?void 0:z.filter(jt=>jt.kit_id===n.id).map(jt=>jt.id))||[],Oe=j.filter(jt=>jt.id).map(jt=>jt.id),Ie=Me.filter(jt=>!Oe.includes(jt));Ie.length>0&&await ae.from("resource_kit_files").delete().in("id",Ie);const Be=(W==null?void 0:W.filter(jt=>jt.kit_id===n.id).map(jt=>jt.id))||[],Pe=C.filter(jt=>jt.id).map(jt=>jt.id),ut=Be.filter(jt=>!Pe.includes(jt));ut.length>0&&await ae.from("resource_kit_links").delete().in("id",ut)}else{const{data:gt,error:Me}=await ae.from("resource_kits").insert(Ye).select().single();if(Me)throw Me;pt=gt.id}for(let gt=0;gt{t.invalidateQueries({queryKey:["resource-kits"]}),t.invalidateQueries({queryKey:["resource-kit-files"]}),t.invalidateQueries({queryKey:["resource-kit-links"]}),Dt.success(n?"Resource kit updated":"Resource kit created"),_e.isPublished&&(_e.isNewKit||!_e.wasPublished)&&JGe(_e.kitName,_e.kitId),r(!1),V()},onError:_e=>{Dt.error("Failed to save resource kit: "+_e.message)}}),ke=zr({mutationFn:async _e=>{const{error:Ye}=await ae.from("resource_kits").delete().eq("id",_e);if(Ye)throw Ye},onSuccess:()=>{t.invalidateQueries({queryKey:["resource-kits"]}),t.invalidateQueries({queryKey:["resource-kit-files"]}),Dt.success("Resource kit deleted")},onError:_e=>{Dt.error("Failed to delete: "+_e.message)}}),Ce=_e=>{if(_e.preventDefault(),!o.name){Dt.error("Please enter a name");return}ge.mutate()},Se=_e=>(z==null?void 0:z.filter(Ye=>Ye.kit_id===_e).length)||0;return s.jsx(Jr,{title:"Toolbox Management",description:"Create and manage resource kits for agents",children:s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsxs(at,{children:[s.jsx(xr,{className:"pb-2",children:s.jsx(wr,{className:"text-sm font-medium text-muted-foreground",children:"Total Kits"})}),s.jsx(ct,{children:s.jsx("div",{className:"text-2xl font-bold",children:(O==null?void 0:O.length)||0})})]}),s.jsxs(at,{children:[s.jsx(xr,{className:"pb-2",children:s.jsx(wr,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),s.jsx(ct,{children:s.jsx("div",{className:"text-2xl font-bold",children:(O==null?void 0:O.filter(_e=>_e.is_published).length)||0})})]})]}),s.jsxs(de,{onClick:()=>{V(),r(!0)},children:[s.jsx(Qn,{className:"h-4 w-4 mr-2"}),"Add Resource Kit"]})]}),s.jsx(at,{children:s.jsx(ct,{className:"p-0",children:s.jsxs(ni,{children:[s.jsx(si,{children:s.jsxs(Dr,{children:[s.jsx(Nt,{children:"Name"}),s.jsx(Nt,{children:"Files"}),s.jsx(Nt,{children:"Publish Date"}),s.jsx(Nt,{children:"Status"}),s.jsx(Nt,{className:"text-right",children:"Actions"})]})}),s.jsx(ii,{children:R?s.jsx(Dr,{children:s.jsx(xt,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):(O==null?void 0:O.length)===0?s.jsx(Dr,{children:s.jsx(xt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No resource kits yet. Create your first one!"})}):O==null?void 0:O.map(_e=>s.jsxs(Dr,{children:[s.jsx(xt,{children:s.jsxs("div",{className:"flex items-center gap-3",children:[_e.featured_image_url?s.jsx("img",{src:_e.featured_image_url,alt:_e.name,className:"w-10 h-10 rounded object-cover"}):s.jsx("div",{className:"w-10 h-10 rounded bg-muted flex items-center justify-center",children:s.jsx(O1,{className:"h-5 w-5 text-muted-foreground"})}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium",children:_e.name}),_e.description&&s.jsx("div",{className:"text-sm text-muted-foreground line-clamp-1",children:_e.description})]})]})}),s.jsx(xt,{children:s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsx(Ii,{className:"h-4 w-4 text-muted-foreground"}),Se(_e.id)]})}),s.jsx(xt,{children:Vn(new Date(_e.publish_date),"MMM d, yyyy")}),s.jsx(xt,{children:s.jsx("span",{className:`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${_e.is_published?"bg-green-100 text-green-800":"bg-yellow-100 text-yellow-800"}`,children:_e.is_published?"Published":"Draft"})}),s.jsx(xt,{className:"text-right",children:s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(de,{variant:"ghost",size:"icon",onClick:()=>{const Ye=(z==null?void 0:z.filter(nt=>nt.kit_id===_e.id))||[],pt=(W==null?void 0:W.filter(nt=>nt.kit_id===_e.id))||[];I({..._e,files:Ye,links:pt})},children:s.jsx(Rc,{className:"h-4 w-4"})}),s.jsx(de,{variant:"ghost",size:"icon",onClick:()=>K(_e),children:s.jsx(io,{className:"h-4 w-4"})}),s.jsx(de,{variant:"ghost",size:"icon",onClick:()=>{confirm("Delete this resource kit?")&&ke.mutate(_e.id)},children:s.jsx(oi,{className:"h-4 w-4 text-destructive"})})]})})]},_e.id))})]})})}),s.jsx(mn,{open:e,onOpenChange:r,children:s.jsxs(pn,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[s.jsx(xn,{children:s.jsx(gn,{children:n?"Edit Resource Kit":"Add Resource Kit"})}),s.jsxs("form",{onSubmit:Ce,className:"space-y-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Featured Image"}),s.jsxs("div",{className:"flex items-center gap-4",children:[g?s.jsx("img",{src:g,alt:"Preview",className:"w-24 h-24 rounded object-cover"}):s.jsx("div",{className:"w-24 h-24 rounded bg-muted flex items-center justify-center",children:s.jsx(O1,{className:"h-8 w-8 text-muted-foreground"})}),s.jsx(Et,{type:"file",accept:"image/*",onChange:Q})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"name",children:"Name *"}),s.jsx(Et,{id:"name",value:o.name,onChange:_e=>c({...o,name:_e.target.value}),placeholder:"Resource Kit Name"})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Description"}),s.jsx(ag,{content:o.description,onChange:_e=>c({...o,description:_e}),placeholder:"Brief description of this resource kit",minHeight:"120px"})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"publish_date",children:"Publish Date"}),s.jsx(Et,{id:"publish_date",type:"date",value:o.publish_date,onChange:_e=>c({...o,publish_date:_e.target.value})})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Published"}),s.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[s.jsx(ri,{checked:o.is_published,onCheckedChange:_e=>c({...o,is_published:_e})}),s.jsx("span",{className:"text-sm text-muted-foreground",children:o.is_published?"Visible to agents":"Hidden from agents"})]})]})]}),s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsx(mt,{children:"Resource Files"}),s.jsxs(de,{type:"button",variant:"outline",size:"sm",onClick:te,children:[s.jsx(Qn,{className:"h-4 w-4 mr-1"}),"Add File"]})]}),j.length===0?s.jsx("div",{className:"text-sm text-muted-foreground py-4 text-center border rounded-md border-dashed",children:'No files added yet. Click "Add File" to include resources.'}):s.jsx("div",{className:"space-y-3",children:j.map((_e,Ye)=>s.jsxs("div",{className:"border rounded-md p-3 space-y-2",children:[s.jsxs("div",{className:"flex justify-between items-start",children:[s.jsxs("span",{className:"text-sm font-medium",children:["File ",Ye+1]}),s.jsx(de,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>X(Ye),children:s.jsx(Ni,{className:"h-4 w-4"})})]}),s.jsx(Et,{placeholder:"File name (e.g., Getting Started Guide)",value:_e.name,onChange:pt=>ie(Ye,"name",pt.target.value)}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Et,{type:"file",onChange:pt=>ve(Ye,pt),className:"flex-1"}),_e.file_url&&!_e.file&&s.jsx("a",{href:_e.file_url,target:"_blank",rel:"noopener noreferrer",className:"text-sm text-primary hover:underline whitespace-nowrap",children:"Current file"}),_e.file&&s.jsx("span",{className:"text-sm text-green-600 whitespace-nowrap",children:"New file selected"})]})]},Ye))})]}),s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsx(mt,{children:"Canva Links"}),s.jsxs(de,{type:"button",variant:"outline",size:"sm",onClick:he,children:[s.jsx(Qn,{className:"h-4 w-4 mr-1"}),"Add Canva Link"]})]}),C.length===0?s.jsx("div",{className:"text-sm text-muted-foreground py-4 text-center border rounded-md border-dashed",children:'No Canva links added yet. Click "Add Canva Link" to include templates.'}):s.jsx("div",{className:"space-y-3",children:C.map((_e,Ye)=>s.jsxs("div",{className:"border rounded-md p-3 space-y-2",children:[s.jsxs("div",{className:"flex justify-between items-start",children:[s.jsxs("span",{className:"text-sm font-medium",children:["Canva Link ",Ye+1]}),s.jsx(de,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>xe(Ye),children:s.jsx(Ni,{className:"h-4 w-4"})})]}),s.jsx(Et,{placeholder:"Link title (e.g., Social Media Post Template)",value:_e.title,onChange:pt=>pe(Ye,"title",pt.target.value)}),s.jsx(Et,{placeholder:"Canva share link (e.g., https://www.canva.com/design/...)",value:_e.canva_share_link,onChange:pt=>pe(Ye,"canva_share_link",pt.target.value)})]},Ye))})]}),s.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[s.jsx(de,{type:"button",variant:"outline",onClick:()=>r(!1),children:"Cancel"}),s.jsx(de,{type:"submit",disabled:ge.isPending,children:ge.isPending?"Saving...":n?"Update":"Create"})]})]})]})}),s.jsx(mn,{open:!!A,onOpenChange:()=>I(null),children:s.jsxs(pn,{className:"max-w-lg",children:[s.jsx(xn,{children:s.jsx(gn,{children:A==null?void 0:A.name})}),s.jsxs("div",{className:"space-y-4",children:[(A==null?void 0:A.featured_image_url)&&s.jsx("img",{src:A.featured_image_url,alt:A.name,className:"w-full h-48 object-cover rounded-lg"}),(A==null?void 0:A.description)&&s.jsx("p",{className:"text-muted-foreground",children:A.description}),s.jsxs("div",{children:[s.jsxs("h4",{className:"font-medium mb-2",children:["Resource Files (",((je=A==null?void 0:A.files)==null?void 0:je.length)||0,")"]}),((et=A==null?void 0:A.files)==null?void 0:et.length)===0?s.jsx("p",{className:"text-sm text-muted-foreground",children:"No files in this kit"}):s.jsx("div",{className:"space-y-2",children:(bt=A==null?void 0:A.files)==null?void 0:bt.map(_e=>s.jsxs("a",{href:_e.file_url,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 p-2 rounded-md hover:bg-muted transition-colors",children:[s.jsx(Ii,{className:"h-4 w-4 text-primary"}),s.jsx("span",{className:"text-sm",children:_e.name})]},_e.id))})]}),(A==null?void 0:A.links)&&A.links.length>0&&s.jsxs("div",{children:[s.jsxs("h4",{className:"font-medium mb-2",children:["Canva Links (",A.links.length,")"]}),s.jsx("div",{className:"space-y-2",children:A.links.map(_e=>s.jsxs("a",{href:_e.canva_share_link,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 p-2 rounded-md hover:bg-muted transition-colors",children:[s.jsx(Go,{className:"h-4 w-4 text-primary"}),s.jsx("span",{className:"text-sm",children:_e.title})]},_e.id))})]})]})]})})]})})}const a9e=()=>{const{user:t}=rn(),{toast:e}=Ri(),r=Wn(),[n,i]=D.useState(!1),[o,c]=D.useState(null),[a,m]=D.useState({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,links:[{title:"",canva_share_link:"",sort_order:0}]}),[g,_]=D.useState(null),[j,N]=D.useState(""),{data:C=[],isLoading:P}=Sr({queryKey:["social-swag-admin"],queryFn:async()=>{const{data:te,error:X}=await ae.from("social_swag").select("*").order("publish_date",{ascending:!1});if(X)throw X;const{data:ie,error:he}=await ae.from("social_swag_links").select("*").order("sort_order");if(he)throw he;return te.map(pe=>({...pe,links:(ie==null?void 0:ie.filter(ve=>ve.swag_id===pe.id))||[]}))}}),A=zr({mutationFn:async te=>{let X=te.existingImageUrl;if(te.image){const ge=te.image.name.split(".").pop(),ke=`${Date.now()}-${Math.random().toString(36).substring(7)}.${ge}`,{error:Ce}=await ae.storage.from("template-previews").upload(ke,te.image);if(Ce)throw Ce;const{data:Se}=ae.storage.from("template-previews").getPublicUrl(ke);X=Se.publicUrl}const ie={title:te.item.title,description:te.item.description||null,preview_image_url:X,publish_date:te.item.publish_date?new Date(te.item.publish_date).toISOString():new Date().toISOString(),is_published:te.item.is_published,created_by:t==null?void 0:t.id};let he=te.itemId;const xe=!he,pe=(o==null?void 0:o.is_published)||!1;if(he){const{error:ge}=await ae.from("social_swag").update(ie).eq("id",he);if(ge)throw ge;await ae.from("social_swag_links").delete().eq("swag_id",he)}else{const{data:ge,error:ke}=await ae.from("social_swag").insert(ie).select().single();if(ke)throw ke;he=ge.id}const ve=te.item.links.filter(ge=>ge.title.trim()&&ge.canva_share_link.trim());if(ve.length>0){const ge=ve.map((Ce,Se)=>({swag_id:he,title:Ce.title.trim(),canva_share_link:Ce.canva_share_link.trim(),sort_order:Se})),{error:ke}=await ae.from("social_swag_links").insert(ge);if(ke)throw ke}return{itemId:he,itemTitle:te.item.title,isNewItem:xe,wasPublished:pe,isPublished:te.item.is_published}},onSuccess:te=>{r.invalidateQueries({queryKey:["social-swag-admin"]}),r.invalidateQueries({queryKey:["social-swag"]}),e({title:o?"Item updated":"Item created"}),te.isPublished&&(te.isNewItem||!te.wasPublished)&&e9e(te.itemTitle,te.itemId),i(!1),O()},onError:te=>{e({title:"Error saving item",description:te.message,variant:"destructive"})}}),I=zr({mutationFn:async te=>{const{error:X}=await ae.from("social_swag").delete().eq("id",te);if(X)throw X},onSuccess:()=>{r.invalidateQueries({queryKey:["social-swag-admin"]}),r.invalidateQueries({queryKey:["social-swag"]}),e({title:"Item deleted"})},onError:te=>{e({title:"Error deleting item",description:te.message,variant:"destructive"})}}),O=()=>{m({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,links:[{title:"",canva_share_link:"",sort_order:0}]}),_(null),N(""),c(null)},R=te=>{c(te),m({title:te.title,description:te.description||"",publish_date:te.publish_date?new Date(te.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],is_published:te.is_published,links:te.links&&te.links.length>0?te.links.map(X=>({id:X.id,title:X.title,canva_share_link:X.canva_share_link,sort_order:X.sort_order})):[{title:"",canva_share_link:"",sort_order:0}]}),N(te.preview_image_url||""),i(!0)},z=te=>{var ie;const X=(ie=te.target.files)==null?void 0:ie[0];X&&(_(X),N(URL.createObjectURL(X)))},W=()=>{m({...a,links:[...a.links,{title:"",canva_share_link:"",sort_order:a.links.length}]})},V=te=>{if(a.links.length<=1)return;const X=a.links.filter((ie,he)=>he!==te);m({...a,links:X})},K=(te,X,ie)=>{const he=[...a.links];he[te]={...he[te],[X]:ie},m({...a,links:he})},Q=te=>{if(te.preventDefault(),!a.title.trim()){e({title:"Title is required",variant:"destructive"});return}A.mutate({item:a,image:g,existingImageUrl:(o==null?void 0:o.preview_image_url)||null,itemId:o==null?void 0:o.id})};return s.jsx(Jr,{title:"Manage Social Swag",children:s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsxs(at,{children:[s.jsx(xr,{className:"pb-2",children:s.jsx(wr,{className:"text-sm font-medium text-muted-foreground",children:"Total Items"})}),s.jsx(ct,{children:s.jsx("div",{className:"text-2xl font-bold",children:C.length})})]}),s.jsxs(at,{children:[s.jsx(xr,{className:"pb-2",children:s.jsx(wr,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),s.jsx(ct,{children:s.jsx("div",{className:"text-2xl font-bold",children:C.filter(te=>te.is_published).length})})]})]}),s.jsxs(mn,{open:n,onOpenChange:te=>{i(te),te||O()},children:[s.jsx(Do,{asChild:!0,children:s.jsxs(de,{className:"gap-2",children:[s.jsx(Qn,{className:"h-4 w-4"}),"Add Item"]})}),s.jsxs(pn,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[s.jsx(xn,{children:s.jsx(gn,{children:o?"Edit Item":"Add New Item"})}),s.jsxs("form",{onSubmit:Q,className:"space-y-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"title",children:"Title *"}),s.jsx(Et,{id:"title",value:a.title,onChange:te=>m({...a,title:te.target.value}),placeholder:"Enter title"})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Description"}),s.jsx(ag,{content:a.description,onChange:te=>m({...a,description:te}),placeholder:"Enter description",minHeight:"120px"})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"publish_date",children:"Publish Date"}),s.jsx(Et,{id:"publish_date",type:"date",value:a.publish_date,onChange:te=>m({...a,publish_date:te.target.value})})]}),s.jsxs("div",{className:"flex items-center space-x-2",children:[s.jsx(ri,{id:"is_published",checked:a.is_published,onCheckedChange:te=>m({...a,is_published:te})}),s.jsx(mt,{htmlFor:"is_published",children:"Published"})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Preview Image"}),j?s.jsxs("div",{className:"relative",children:[s.jsx("img",{src:j,alt:"Preview",className:"w-full max-h-48 object-contain rounded-lg border"}),s.jsx(de,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:()=>{_(null),N("")},children:s.jsx(Ni,{className:"h-3 w-3"})})]}):s.jsxs("div",{className:"border-2 border-dashed rounded-lg p-4 text-center",children:[s.jsx(Wm,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),s.jsx(Et,{type:"file",accept:"image/*",onChange:z,className:"cursor-pointer"})]})]}),s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx(mt,{children:"Canva Links"}),s.jsxs(de,{type:"button",variant:"outline",size:"sm",onClick:W,children:[s.jsx(Qn,{className:"h-3 w-3 mr-1"}),"Add Link"]})]}),a.links.map((te,X)=>s.jsx(at,{children:s.jsxs(ct,{className:"pt-4 pb-4 space-y-3",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("span",{className:"text-sm font-medium text-muted-foreground",children:["Link ",X+1]}),a.links.length>1&&s.jsx(de,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>V(X),children:s.jsx(Ni,{className:"h-3 w-3"})})]}),s.jsx(Et,{placeholder:"Link title (e.g., Instagram Post)",value:te.title,onChange:ie=>K(X,"title",ie.target.value)}),s.jsx(Et,{placeholder:"Canva share link",value:te.canva_share_link,onChange:ie=>K(X,"canva_share_link",ie.target.value)})]})},X))]}),s.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[s.jsx(de,{type:"button",variant:"outline",onClick:()=>i(!1),children:"Cancel"}),s.jsx(de,{type:"submit",disabled:A.isPending,children:A.isPending?"Saving...":o?"Update":"Create"})]})]})]})]})]}),s.jsx(at,{children:s.jsx(ct,{className:"p-0",children:P?s.jsx("div",{className:"flex justify-center py-8",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):C.length===0?s.jsx("div",{className:"text-center py-8 text-muted-foreground",children:'No items yet. Click "Add Item" to create your first one.'}):s.jsxs(ni,{children:[s.jsx(si,{children:s.jsxs(Dr,{children:[s.jsx(Nt,{className:"w-16",children:"Preview"}),s.jsx(Nt,{children:"Title"}),s.jsx(Nt,{children:"Links"}),s.jsx(Nt,{children:"Publish Date"}),s.jsx(Nt,{children:"Status"}),s.jsx(Nt,{className:"text-right",children:"Actions"})]})}),s.jsx(ii,{children:C.map(te=>{var X;return s.jsxs(Dr,{children:[s.jsx(xt,{children:te.preview_image_url?s.jsx("img",{src:te.preview_image_url,alt:"",className:"w-12 h-12 object-cover rounded"}):s.jsx("div",{className:"w-12 h-12 bg-muted rounded flex items-center justify-center",children:s.jsx(Wm,{className:"h-4 w-4 text-muted-foreground"})})}),s.jsx(xt,{className:"font-medium",children:te.title}),s.jsxs(xt,{children:[((X=te.links)==null?void 0:X.length)||0," links"]}),s.jsx(xt,{children:new Date(te.publish_date).toLocaleDateString()}),s.jsx(xt,{children:s.jsx(ir,{variant:te.is_published?"default":"secondary",children:te.is_published?"Published":"Draft"})}),s.jsx(xt,{className:"text-right",children:s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(de,{variant:"ghost",size:"icon",onClick:()=>window.open(`/social-swag/${te.id}`,"_blank"),children:s.jsx(Rc,{className:"h-4 w-4"})}),s.jsx(de,{variant:"ghost",size:"icon",onClick:()=>R(te),children:s.jsx(io,{className:"h-4 w-4"})}),s.jsx(de,{variant:"ghost",size:"icon",onClick:()=>{confirm("Are you sure you want to delete this item?")&&I.mutate(te.id)},children:s.jsx(oi,{className:"h-4 w-4"})})]})})]},te.id)})})]})})})]})})},o9e=()=>{const{toast:t}=Ri(),e=Wn(),[r,n]=D.useState("categories"),[i,o]=D.useState(!1),[c,a]=D.useState(null),[m,g]=D.useState({name:"",description:"",icon:""}),[_,j]=D.useState(!1),[N,C]=D.useState(null),[P,A]=D.useState({name:"",description:"",icon:""}),[I,O]=D.useState(!1),[R,z]=D.useState(null),[W,V]=D.useState(""),{data:K=[],isLoading:Q}=Sr({queryKey:["admin-community-categories"],queryFn:async()=>{const{data:Oe,error:Ie}=await ae.from("community_categories").select("*").order("sort_order");if(Ie)throw Ie;return Oe}}),{data:te=[],isLoading:X}=Sr({queryKey:["admin-private-groups"],queryFn:async()=>{const{data:Oe,error:Ie}=await ae.from("community_private_groups").select("*").order("sort_order");if(Ie)throw Ie;return Oe}}),{data:ie=[]}=Sr({queryKey:["admin-group-members",R==null?void 0:R.id],queryFn:async()=>{if(!R)return[];const{data:Oe,error:Ie}=await ae.from("community_private_group_members").select("*").eq("group_id",R.id);if(Ie)throw Ie;return Oe},enabled:!!R}),{data:he=[]}=Sr({queryKey:["admin-all-profiles"],queryFn:async()=>{const{data:Oe,error:Ie}=await ae.from("profiles").select("id, name, email, brokerage_id").order("name");if(Ie)throw Ie;return Oe}}),{data:xe=[]}=Sr({queryKey:["admin-all-brokerages"],queryFn:async()=>{const{data:Oe,error:Ie}=await ae.from("brokerages").select("*").order("name");if(Ie)throw Ie;return Oe}}),pe=zr({mutationFn:async Oe=>{if(Oe.id){const{error:Ie}=await ae.from("community_categories").update({name:Oe.name,description:Oe.description||null,icon:Oe.icon||null}).eq("id",Oe.id);if(Ie)throw Ie}else{const Ie=Math.max(...K.map(Pe=>Pe.sort_order),0),{error:Be}=await ae.from("community_categories").insert({name:Oe.name,description:Oe.description||null,icon:Oe.icon||null,sort_order:Ie+1});if(Be)throw Be}},onSuccess:()=>{e.invalidateQueries({queryKey:["admin-community-categories"]}),o(!1),a(null),g({name:"",description:"",icon:""}),t({title:c?"Category updated!":"Category created!"})},onError:Oe=>{t({title:"Error",description:Oe.message,variant:"destructive"})}}),ve=zr({mutationFn:async Oe=>{const{error:Ie}=await ae.from("community_categories").delete().eq("id",Oe);if(Ie)throw Ie},onSuccess:()=>{e.invalidateQueries({queryKey:["admin-community-categories"]}),t({title:"Category deleted"})}}),ge=zr({mutationFn:async({id:Oe,direction:Ie})=>{const Be=K.findIndex(Pe=>Pe.id===Oe);if(Ie==="up"&&Be>0){const Pe=K[Be-1],ut=K[Be];await ae.from("community_categories").update({sort_order:ut.sort_order}).eq("id",Pe.id),await ae.from("community_categories").update({sort_order:Pe.sort_order}).eq("id",ut.id)}else if(Ie==="down"&&Bee.invalidateQueries({queryKey:["admin-community-categories"]})}),ke=zr({mutationFn:async Oe=>{if(Oe.id){const{error:Ie}=await ae.from("community_private_groups").update({name:Oe.name,description:Oe.description||null,icon:Oe.icon||null}).eq("id",Oe.id);if(Ie)throw Ie}else{const Ie=Math.max(...te.map(Pe=>Pe.sort_order),0),{error:Be}=await ae.from("community_private_groups").insert({name:Oe.name,description:Oe.description||null,icon:Oe.icon||null,sort_order:Ie+1});if(Be)throw Be}},onSuccess:()=>{e.invalidateQueries({queryKey:["admin-private-groups"]}),j(!1),C(null),A({name:"",description:"",icon:""}),t({title:N?"Private group updated!":"Private group created!"})},onError:Oe=>{t({title:"Error",description:Oe.message,variant:"destructive"})}}),Ce=zr({mutationFn:async Oe=>{const{error:Ie}=await ae.from("community_private_groups").delete().eq("id",Oe);if(Ie)throw Ie},onSuccess:()=>{e.invalidateQueries({queryKey:["admin-private-groups"]}),t({title:"Private group deleted"})}}),Se=zr({mutationFn:async({id:Oe,direction:Ie})=>{const Be=te.findIndex(Pe=>Pe.id===Oe);if(Ie==="up"&&Be>0){const Pe=te[Be-1],ut=te[Be];await ae.from("community_private_groups").update({sort_order:ut.sort_order}).eq("id",Pe.id),await ae.from("community_private_groups").update({sort_order:Pe.sort_order}).eq("id",ut.id)}else if(Ie==="down"&&Bee.invalidateQueries({queryKey:["admin-private-groups"]})}),je=zr({mutationFn:async({groupId:Oe,userId:Ie,isMember:Be})=>{if(Be){const{error:Pe}=await ae.from("community_private_group_members").delete().eq("group_id",Oe).eq("user_id",Ie);if(Pe)throw Pe}else{const{error:Pe}=await ae.from("community_private_group_members").insert({group_id:Oe,user_id:Ie});if(Pe)throw Pe}},onSuccess:()=>{e.invalidateQueries({queryKey:["admin-group-members",R==null?void 0:R.id]})}}),et=zr({mutationFn:async({groupId:Oe,brokerageId:Ie,isMember:Be})=>{if(Be){const{error:Pe}=await ae.from("community_private_group_members").delete().eq("group_id",Oe).eq("brokerage_id",Ie);if(Pe)throw Pe}else{const{error:Pe}=await ae.from("community_private_group_members").insert({group_id:Oe,brokerage_id:Ie});if(Pe)throw Pe}},onSuccess:()=>{e.invalidateQueries({queryKey:["admin-group-members",R==null?void 0:R.id]})}}),bt=Oe=>{a(Oe),g({name:Oe.name,description:Oe.description||"",icon:Oe.icon||""}),o(!0)},_e=()=>{a(null),g({name:"",description:"",icon:""}),o(!0)},Ye=Oe=>{C(Oe),A({name:Oe.name,description:Oe.description||"",icon:Oe.icon||""}),j(!0)},pt=()=>{C(null),A({name:"",description:"",icon:""}),j(!0)},nt=Oe=>{z(Oe),V(""),O(!0)},Qt=Oe=>ie.some(Ie=>Ie.user_id===Oe),gt=Oe=>ie.some(Ie=>Ie.brokerage_id===Oe),Me=he.filter(Oe=>Oe.name.toLowerCase().includes(W.toLowerCase())||Oe.email.toLowerCase().includes(W.toLowerCase()));return s.jsx(Jr,{title:"Community Management",children:s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{children:[s.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Community Management"}),s.jsx("p",{className:"text-muted-foreground mt-1",children:"Manage categories and private groups for community discussions"})]}),s.jsxs(go,{value:r,onValueChange:n,children:[s.jsxs(ao,{children:[s.jsx(Bn,{value:"categories",children:"Public Categories"}),s.jsxs(Bn,{value:"private-groups",children:[s.jsx(mM,{className:"h-4 w-4 mr-1"}),"Private Groups"]})]}),s.jsxs(xs,{value:"categories",className:"space-y-4",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("p",{className:"text-sm text-muted-foreground",children:"Categories visible to all community members"}),s.jsxs(de,{onClick:_e,children:[s.jsx(Qn,{className:"h-4 w-4 mr-2"}),"Add Category"]})]}),s.jsx(at,{children:s.jsx(ct,{className:"pt-6",children:s.jsxs(ni,{children:[s.jsx(si,{children:s.jsxs(Dr,{children:[s.jsx(Nt,{className:"w-[50px]",children:"Order"}),s.jsx(Nt,{className:"w-[80px]",children:"Icon"}),s.jsx(Nt,{children:"Name"}),s.jsx(Nt,{children:"Description"}),s.jsx(Nt,{className:"w-[100px]",children:"Actions"})]})}),s.jsx(ii,{children:Q?s.jsx(Dr,{children:s.jsx(xt,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):K.length===0?s.jsx(Dr,{children:s.jsx(xt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No categories yet. Create your first one!"})}):K.map((Oe,Ie)=>s.jsxs(Dr,{children:[s.jsx(xt,{children:s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx(de,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Ie===0,onClick:()=>ge.mutate({id:Oe.id,direction:"up"}),children:"↑"}),s.jsx(de,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Ie===K.length-1,onClick:()=>ge.mutate({id:Oe.id,direction:"down"}),children:"↓"})]})}),s.jsx(xt,{className:"text-2xl",children:Oe.icon||"📁"}),s.jsx(xt,{className:"font-medium",children:Oe.name}),s.jsx(xt,{className:"text-muted-foreground",children:Oe.description||"—"}),s.jsx(xt,{children:s.jsxs("div",{className:"flex gap-1",children:[s.jsx(de,{variant:"ghost",size:"icon",onClick:()=>bt(Oe),children:s.jsx(io,{className:"h-4 w-4"})}),s.jsx(de,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>{confirm("Delete this category? Posts will be uncategorized.")&&ve.mutate(Oe.id)},children:s.jsx(oi,{className:"h-4 w-4"})})]})})]},Oe.id))})]})})})]}),s.jsxs(xs,{value:"private-groups",className:"space-y-4",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("p",{className:"text-sm text-muted-foreground",children:"Private groups visible only to assigned members or brokerages"}),s.jsxs(de,{onClick:pt,children:[s.jsx(Qn,{className:"h-4 w-4 mr-2"}),"Add Private Group"]})]}),s.jsx(at,{children:s.jsx(ct,{className:"pt-6",children:s.jsxs(ni,{children:[s.jsx(si,{children:s.jsxs(Dr,{children:[s.jsx(Nt,{className:"w-[50px]",children:"Order"}),s.jsx(Nt,{className:"w-[80px]",children:"Icon"}),s.jsx(Nt,{children:"Name"}),s.jsx(Nt,{children:"Description"}),s.jsx(Nt,{className:"w-[120px]",children:"Members"}),s.jsx(Nt,{className:"w-[140px]",children:"Actions"})]})}),s.jsx(ii,{children:X?s.jsx(Dr,{children:s.jsx(xt,{colSpan:6,className:"text-center py-8",children:"Loading..."})}):te.length===0?s.jsx(Dr,{children:s.jsx(xt,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No private groups yet. Create your first one!"})}):te.map((Oe,Ie)=>s.jsxs(Dr,{children:[s.jsx(xt,{children:s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx(de,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Ie===0,onClick:()=>Se.mutate({id:Oe.id,direction:"up"}),children:"↑"}),s.jsx(de,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Ie===te.length-1,onClick:()=>Se.mutate({id:Oe.id,direction:"down"}),children:"↓"})]})}),s.jsx(xt,{className:"text-2xl",children:Oe.icon||"🔒"}),s.jsx(xt,{className:"font-medium",children:s.jsxs("div",{className:"flex items-center gap-2",children:[Oe.name,s.jsxs(ir,{variant:"secondary",className:"text-xs",children:[s.jsx(mM,{className:"h-3 w-3 mr-1"}),"Private"]})]})}),s.jsx(xt,{className:"text-muted-foreground",children:Oe.description||"—"}),s.jsx(xt,{children:s.jsxs(de,{variant:"outline",size:"sm",onClick:()=>nt(Oe),children:[s.jsx(_i,{className:"h-4 w-4 mr-1"}),"Manage"]})}),s.jsx(xt,{children:s.jsxs("div",{className:"flex gap-1",children:[s.jsx(de,{variant:"ghost",size:"icon",onClick:()=>Ye(Oe),children:s.jsx(io,{className:"h-4 w-4"})}),s.jsx(de,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>{confirm("Delete this private group? All posts in this group will be deleted.")&&Ce.mutate(Oe.id)},children:s.jsx(oi,{className:"h-4 w-4"})})]})})]},Oe.id))})]})})})]})]}),s.jsx(mn,{open:i,onOpenChange:o,children:s.jsxs(pn,{children:[s.jsx(xn,{children:s.jsx(gn,{children:c?"Edit Category":"Create Category"})}),s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-sm font-medium",children:"Icon (emoji)"}),s.jsx(Et,{value:m.icon,onChange:Oe=>g(Ie=>({...Ie,icon:Oe.target.value})),placeholder:"💬",className:"mt-1"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-sm font-medium",children:"Name *"}),s.jsx(Et,{value:m.name,onChange:Oe=>g(Ie=>({...Ie,name:Oe.target.value})),placeholder:"Category name",className:"mt-1"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-sm font-medium",children:"Description"}),s.jsx(mi,{value:m.description,onChange:Oe=>g(Ie=>({...Ie,description:Oe.target.value})),placeholder:"Brief description of this category",className:"mt-1"})]}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(de,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),s.jsx(de,{onClick:()=>pe.mutate({...m,id:c==null?void 0:c.id}),disabled:!m.name.trim(),children:c?"Save Changes":"Create Category"})]})]})]})}),s.jsx(mn,{open:_,onOpenChange:j,children:s.jsxs(pn,{children:[s.jsx(xn,{children:s.jsx(gn,{children:N?"Edit Private Group":"Create Private Group"})}),s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-sm font-medium",children:"Icon (emoji)"}),s.jsx(Et,{value:P.icon,onChange:Oe=>A(Ie=>({...Ie,icon:Oe.target.value})),placeholder:"🔒",className:"mt-1"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-sm font-medium",children:"Name *"}),s.jsx(Et,{value:P.name,onChange:Oe=>A(Ie=>({...Ie,name:Oe.target.value})),placeholder:"e.g., Pioneers",className:"mt-1"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-sm font-medium",children:"Description"}),s.jsx(mi,{value:P.description,onChange:Oe=>A(Ie=>({...Ie,description:Oe.target.value})),placeholder:"Brief description of this private group",className:"mt-1"})]}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(de,{variant:"outline",onClick:()=>j(!1),children:"Cancel"}),s.jsx(de,{onClick:()=>ke.mutate({...P,id:N==null?void 0:N.id}),disabled:!P.name.trim(),children:N?"Save Changes":"Create Private Group"})]})]})]})}),s.jsx(mn,{open:I,onOpenChange:O,children:s.jsxs(pn,{className:"max-w-2xl",children:[s.jsx(xn,{children:s.jsxs(gn,{children:["Manage Members: ",R==null?void 0:R.name]})}),s.jsxs("div",{className:"space-y-4",children:[s.jsxs(go,{defaultValue:"brokerages",children:[s.jsxs(ao,{className:"w-full",children:[s.jsx(Bn,{value:"brokerages",className:"flex-1",children:"By Brokerage"}),s.jsx(Bn,{value:"users",className:"flex-1",children:"Individual Users"})]}),s.jsxs(xs,{value:"brokerages",className:"space-y-4",children:[s.jsx("p",{className:"text-sm text-muted-foreground",children:"Select brokerages to grant all their agents access to this private group."}),s.jsx(qu,{className:"h-[300px] border rounded-md p-4",children:s.jsxs("div",{className:"space-y-2",children:[xe.map(Oe=>s.jsxs("div",{className:"flex items-center justify-between p-2 hover:bg-muted rounded-md",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(dx,{checked:gt(Oe.id),onCheckedChange:()=>{R&&et.mutate({groupId:R.id,brokerageId:Oe.id,isMember:gt(Oe.id)})}}),s.jsx("span",{className:"font-medium",children:Oe.name})]}),s.jsxs(ir,{variant:"secondary",children:[he.filter(Ie=>Ie.brokerage_id===Oe.id).length," agents"]})]},Oe.id)),xe.length===0&&s.jsx("p",{className:"text-center text-muted-foreground py-4",children:"No brokerages found"})]})})]}),s.jsxs(xs,{value:"users",className:"space-y-4",children:[s.jsxs("div",{className:"relative",children:[s.jsx(ba,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),s.jsx(Et,{placeholder:"Search users...",value:W,onChange:Oe=>V(Oe.target.value),className:"pl-9"})]}),s.jsx(qu,{className:"h-[300px] border rounded-md p-4",children:s.jsxs("div",{className:"space-y-2",children:[Me.map(Oe=>s.jsx("div",{className:"flex items-center justify-between p-2 hover:bg-muted rounded-md",children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(dx,{checked:Qt(Oe.id),onCheckedChange:()=>{R&&je.mutate({groupId:R.id,userId:Oe.id,isMember:Qt(Oe.id)})}}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium",children:Oe.name}),s.jsx("div",{className:"text-sm text-muted-foreground",children:Oe.email})]})]})},Oe.id)),Me.length===0&&s.jsx("p",{className:"text-center text-muted-foreground py-4",children:"No users found"})]})})]})]}),s.jsx("div",{className:"flex justify-end",children:s.jsx(de,{onClick:()=>O(!1),children:"Done"})})]})]})})]})})},UJ=t=>{switch(t){case"academy_video":return s.jsx(Sf,{className:"h-3 w-3"});case"template":return s.jsx(Ii,{className:"h-3 w-3"});case"toolbox":return s.jsx(O1,{className:"h-3 w-3"});case"newsletter":return s.jsx(gT,{className:"h-3 w-3"});case"social_swag":return s.jsx(cu,{className:"h-3 w-3"});default:return s.jsx(oa,{className:"h-3 w-3"})}},l9e=t=>{switch(t){case"academy_video":return"Academy";case"template":return"Template";case"toolbox":return"Toolbox";case"newsletter":return"Newsletter";case"social_swag":return"Social Swag";default:return t}},c9e=t=>{switch(t){case"view":return"Viewed";case"click_canva":return"Clicked Canva";case"click_pdf":return"Downloaded PDF";case"click_video":return"Watched Video";case"click_link":return"Clicked Link";case"click_drive":return"Clicked Drive";default:return t}},u9e=()=>{const{toast:t}=Ri(),[e,r]=D.useState([]),[n,i]=D.useState([]),[o,c]=D.useState([]),[a,m]=D.useState(!0),[g,_]=D.useState(""),[j,N]=D.useState(null),[C,P]=D.useState([]),[A,I]=D.useState([]);D.useEffect(()=>{O()},[]);const O=async()=>{try{m(!0);const{data:V,error:K}=await ae.from("activity_logs").select(` id, user_id, app_name, launched_at, profiles ( name, email, brokerages ( name ) ) `).order("launched_at",{ascending:!1}).limit(5e3);if(K)throw K;const{data:Q,error:te}=await ae.from("content_engagement_logs").select(` id, user_id, resource_type, resource_id, resource_title, action_type, created_at `).order("created_at",{ascending:!1}).limit(5e3);if(te)throw te;const X=[...new Set((Q==null?void 0:Q.map(ke=>ke.user_id))||[])],{data:ie}=await ae.from("profiles").select(` id, name, email, brokerages ( name ) `).in("id",X),he=new Map((ie==null?void 0:ie.map(ke=>[ke.id,ke]))||[]),xe=(V==null?void 0:V.map(ke=>{var Ce,Se,je,et;return{id:ke.id,user_id:ke.user_id,app_name:ke.app_name,launched_at:ke.launched_at,user_name:((Ce=ke.profiles)==null?void 0:Ce.name)||"Unknown",user_email:((Se=ke.profiles)==null?void 0:Se.email)||"Unknown",brokerage_name:((et=(je=ke.profiles)==null?void 0:je.brokerages)==null?void 0:et.name)||null}}))||[],pe=(Q==null?void 0:Q.map(ke=>{var Se;const Ce=he.get(ke.user_id);return{id:ke.id,user_id:ke.user_id,resource_type:ke.resource_type,resource_id:ke.resource_id,resource_title:ke.resource_title,action_type:ke.action_type,created_at:ke.created_at,user_name:(Ce==null?void 0:Ce.name)||"Unknown",user_email:(Ce==null?void 0:Ce.email)||"Unknown",brokerage_name:((Se=Ce==null?void 0:Ce.brokerages)==null?void 0:Se.name)||null}}))||[];r(xe),i(pe);const ve=new Map;xe.forEach(ke=>{if(!ve.has(ke.user_id))ve.set(ke.user_id,{user_id:ke.user_id,user_name:ke.user_name,user_email:ke.user_email,brokerage_name:ke.brokerage_name,last_activity_type:"app",last_activity_name:ke.app_name,last_activity_at:ke.launched_at,total_app_launches:1,total_content_views:0});else{const Ce=ve.get(ke.user_id);Ce.total_app_launches++,new Date(ke.launched_at)>new Date(Ce.last_activity_at)&&(Ce.last_activity_type="app",Ce.last_activity_name=ke.app_name,Ce.last_activity_at=ke.launched_at)}}),pe.forEach(ke=>{if(!ve.has(ke.user_id))ve.set(ke.user_id,{user_id:ke.user_id,user_name:ke.user_name,user_email:ke.user_email,brokerage_name:ke.brokerage_name,last_activity_type:ke.resource_type,last_activity_name:ke.resource_title,last_activity_at:ke.created_at,total_app_launches:0,total_content_views:1});else{const Ce=ve.get(ke.user_id);Ce.total_content_views++,new Date(ke.created_at)>new Date(Ce.last_activity_at)&&(Ce.last_activity_type=ke.resource_type,Ce.last_activity_name=ke.resource_title,Ce.last_activity_at=ke.created_at)}});const ge=Array.from(ve.values()).sort((ke,Ce)=>new Date(Ce.last_activity_at).getTime()-new Date(ke.last_activity_at).getTime());c(ge)}catch(V){console.error("Error loading activity:",V),t({title:"Error",description:"Failed to load activity logs",variant:"destructive"})}finally{m(!1)}},R=V=>{N({id:V.user_id,name:V.user_name,email:V.user_email});const K=e.filter(te=>te.user_id===V.user_id),Q=n.filter(te=>te.user_id===V.user_id);P(K),I(Q)},z=()=>{N(null),P([]),I([])},W=o.filter(V=>{var Q;if(!g)return!0;const K=g.toLowerCase();return V.user_name.toLowerCase().includes(K)||V.user_email.toLowerCase().includes(K)||((Q=V.brokerage_name)==null?void 0:Q.toLowerCase().includes(K))});return a?s.jsx(at,{children:s.jsx(ct,{className:"flex items-center justify-center py-8",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):s.jsxs(s.Fragment,{children:[s.jsxs(at,{children:[s.jsxs(xr,{children:[s.jsx(wr,{children:"User Activity"}),s.jsx(us,{children:"App launches and content engagement - click to see full history"})]}),s.jsxs(ct,{children:[s.jsx("div",{className:"mb-4",children:s.jsxs("div",{className:"relative",children:[s.jsx(ba,{className:"absolute left-3 top-3 h-4 w-4 text-muted-foreground"}),s.jsx(Et,{placeholder:"Search by name, email, or brokerage...",value:g,onChange:V=>_(V.target.value),className:"pl-9"})]})}),s.jsx("div",{className:"rounded-md border",children:s.jsxs(ni,{children:[s.jsx(si,{children:s.jsxs(Dr,{children:[s.jsx(Nt,{children:"User"}),s.jsx(Nt,{children:"Brokerage"}),s.jsx(Nt,{children:"Last Activity"}),s.jsx(Nt,{children:"Last Active"}),s.jsx(Nt,{className:"text-right",children:"Apps"}),s.jsx(Nt,{className:"text-right",children:"Content"})]})}),s.jsx(ii,{children:W.length===0?s.jsx(Dr,{children:s.jsx(xt,{colSpan:6,className:"text-center text-muted-foreground",children:"No activity found"})}):W.map(V=>s.jsxs(Dr,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>R(V),children:[s.jsx(xt,{children:s.jsxs("div",{children:[s.jsx("div",{className:"font-medium",children:V.user_name}),s.jsx("div",{className:"text-sm text-muted-foreground",children:V.user_email})]})}),s.jsx(xt,{children:V.brokerage_name?s.jsx(ir,{variant:"outline",children:V.brokerage_name}):s.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),s.jsx(xt,{children:s.jsx("div",{className:"flex items-center gap-2",children:V.last_activity_type==="app"?s.jsxs(ir,{variant:"secondary",children:[s.jsx(oa,{className:"h-3 w-3 mr-1"}),V.last_activity_name]}):s.jsxs(ir,{variant:"outline",className:"flex items-center gap-1",children:[UJ(V.last_activity_type),s.jsx("span",{className:"max-w-32 truncate",children:V.last_activity_name})]})})}),s.jsx(xt,{className:"text-sm text-muted-foreground",children:Bu(new Date(V.last_activity_at),{addSuffix:!0})}),s.jsx(xt,{className:"text-right",children:s.jsx(ir,{variant:"outline",children:V.total_app_launches})}),s.jsx(xt,{className:"text-right",children:s.jsx(ir,{variant:"outline",children:V.total_content_views})})]},V.user_id))})]})})]})]}),s.jsx(mn,{open:!!j,onOpenChange:V=>!V&&z(),children:s.jsxs(pn,{className:"max-w-3xl max-h-[80vh] overflow-hidden flex flex-col",children:[s.jsxs(xn,{children:[s.jsxs(gn,{children:[j==null?void 0:j.name,"'s Activity"]}),s.jsx(fi,{children:j==null?void 0:j.email})]}),s.jsxs(go,{defaultValue:"content",className:"flex-1 overflow-hidden flex flex-col",children:[s.jsxs(ao,{className:"grid w-full grid-cols-2",children:[s.jsxs(Bn,{value:"content",children:["Content (",A.length,")"]}),s.jsxs(Bn,{value:"apps",children:["App Launches (",C.length,")"]})]}),s.jsx(xs,{value:"content",className:"flex-1 overflow-auto mt-4",children:s.jsx("div",{className:"rounded-md border",children:s.jsxs(ni,{children:[s.jsx(si,{children:s.jsxs(Dr,{children:[s.jsx(Nt,{children:"Type"}),s.jsx(Nt,{children:"Resource"}),s.jsx(Nt,{children:"Action"}),s.jsx(Nt,{children:"Time"})]})}),s.jsx(ii,{children:A.length===0?s.jsx(Dr,{children:s.jsx(xt,{colSpan:4,className:"text-center text-muted-foreground",children:"No content engagement"})}):A.map(V=>s.jsxs(Dr,{children:[s.jsx(xt,{children:s.jsxs(ir,{variant:"outline",className:"flex items-center gap-1 w-fit",children:[UJ(V.resource_type),l9e(V.resource_type)]})}),s.jsx(xt,{className:"max-w-48",children:s.jsx("span",{className:"truncate block",children:V.resource_title})}),s.jsx(xt,{children:s.jsx(ir,{variant:"secondary",children:c9e(V.action_type)})}),s.jsx(xt,{className:"text-sm text-muted-foreground",children:Bu(new Date(V.created_at),{addSuffix:!0})})]},V.id))})]})})}),s.jsx(xs,{value:"apps",className:"flex-1 overflow-auto mt-4",children:s.jsx("div",{className:"rounded-md border",children:s.jsxs(ni,{children:[s.jsx(si,{children:s.jsxs(Dr,{children:[s.jsx(Nt,{children:"App"}),s.jsx(Nt,{children:"Time"})]})}),s.jsx(ii,{children:C.length===0?s.jsx(Dr,{children:s.jsx(xt,{colSpan:2,className:"text-center text-muted-foreground",children:"No app launches"})}):C.map(V=>s.jsxs(Dr,{children:[s.jsx(xt,{children:s.jsx(ir,{variant:"secondary",children:V.app_name})}),s.jsx(xt,{className:"text-sm text-muted-foreground",children:Bu(new Date(V.launched_at),{addSuffix:!0})})]},V.id))})]})})})]})]})})]})},d9e=()=>{const{toast:t}=Ri(),[e,r]=D.useState({totalUsers:0,activeUsers:0,pendingUsers:0,totalBrokerages:0,totalLaunches:0,launchesThisWeek:0,launchesThisMonth:0,uniqueActiveThisWeek:0}),[n,i]=D.useState(!0);D.useEffect(()=>{o()},[]);const o=async()=>{try{i(!0);const{count:c}=await ae.from("profiles").select("*",{count:"exact",head:!0}),{count:a}=await ae.from("profiles").select("*",{count:"exact",head:!0}).not("last_login","is",null),m=(c||0)-(a||0),{count:g}=await ae.from("brokerages").select("*",{count:"exact",head:!0}),{count:_}=await ae.from("activity_logs").select("*",{count:"exact",head:!0}),j=new Date;j.setDate(j.getDate()-7);const{count:N}=await ae.from("activity_logs").select("*",{count:"exact",head:!0}).gte("launched_at",j.toISOString()),C=new Date;C.setMonth(C.getMonth()-1);const{count:P}=await ae.from("activity_logs").select("*",{count:"exact",head:!0}).gte("launched_at",C.toISOString()),{data:A}=await ae.from("activity_logs").select("user_id").gte("launched_at",j.toISOString()),I=new Set(A==null?void 0:A.map(O=>O.user_id)).size;r({totalUsers:c||0,activeUsers:a||0,pendingUsers:m,totalBrokerages:g||0,totalLaunches:_||0,launchesThisWeek:N||0,launchesThisMonth:P||0,uniqueActiveThisWeek:I})}catch(c){console.error("Error loading analytics:",c),t({title:"Error",description:"Failed to load analytics",variant:"destructive"})}finally{i(!1)}};return n?s.jsx(at,{children:s.jsx(ct,{className:"flex items-center justify-center py-8",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):s.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:[s.jsxs(at,{children:[s.jsxs(xr,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[s.jsx(wr,{className:"text-sm font-medium",children:"Total Users"}),s.jsx(_i,{className:"h-4 w-4 text-muted-foreground"})]}),s.jsxs(ct,{children:[s.jsx("div",{className:"text-2xl font-bold",children:e.totalUsers}),s.jsxs("p",{className:"text-xs text-muted-foreground",children:[e.activeUsers," active, ",e.pendingUsers," pending"]})]})]}),s.jsxs(at,{children:[s.jsxs(xr,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[s.jsx(wr,{className:"text-sm font-medium",children:"Active Users"}),s.jsx(gc,{className:"h-4 w-4 text-muted-foreground"})]}),s.jsxs(ct,{children:[s.jsx("div",{className:"text-2xl font-bold",children:e.activeUsers}),s.jsx("p",{className:"text-xs text-muted-foreground",children:e.totalUsers>0?`${Math.round(e.activeUsers/e.totalUsers*100)}% of total`:"0% of total"})]})]}),s.jsxs(at,{children:[s.jsxs(xr,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[s.jsx(wr,{className:"text-sm font-medium",children:"Pending Invites"}),s.jsx(No,{className:"h-4 w-4 text-muted-foreground"})]}),s.jsxs(ct,{children:[s.jsx("div",{className:"text-2xl font-bold",children:e.pendingUsers}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Awaiting setup"})]})]}),s.jsxs(at,{children:[s.jsxs(xr,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[s.jsx(wr,{className:"text-sm font-medium",children:"Brokerages"}),s.jsx(yc,{className:"h-4 w-4 text-muted-foreground"})]}),s.jsxs(ct,{children:[s.jsx("div",{className:"text-2xl font-bold",children:e.totalBrokerages}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Total brokerages"})]})]}),s.jsxs(at,{children:[s.jsxs(xr,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[s.jsx(wr,{className:"text-sm font-medium",children:"Total App Launches"}),s.jsx(Qw,{className:"h-4 w-4 text-muted-foreground"})]}),s.jsxs(ct,{children:[s.jsx("div",{className:"text-2xl font-bold",children:e.totalLaunches}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"All time"})]})]}),s.jsxs(at,{children:[s.jsxs(xr,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[s.jsx(wr,{className:"text-sm font-medium",children:"Launches This Week"}),s.jsx(Qw,{className:"h-4 w-4 text-muted-foreground"})]}),s.jsxs(ct,{children:[s.jsx("div",{className:"text-2xl font-bold",children:e.launchesThisWeek}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Last 7 days"})]})]}),s.jsxs(at,{children:[s.jsxs(xr,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[s.jsx(wr,{className:"text-sm font-medium",children:"Launches This Month"}),s.jsx(Qw,{className:"h-4 w-4 text-muted-foreground"})]}),s.jsxs(ct,{children:[s.jsx("div",{className:"text-2xl font-bold",children:e.launchesThisMonth}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Last 30 days"})]})]}),s.jsxs(at,{children:[s.jsxs(xr,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[s.jsx(wr,{className:"text-sm font-medium",children:"Active This Week"}),s.jsx(r0,{className:"h-4 w-4 text-muted-foreground"})]}),s.jsxs(ct,{children:[s.jsx("div",{className:"text-2xl font-bold",children:e.uniqueActiveThisWeek}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Unique users"})]})]})]})},VJ={event:"Event",template:"Template",academy_video:"Academy Video",resource_kit:"Resource Kit",newsletter:"Newsletter",social_swag:"Social Swag"},qJ={event:"bg-blue-100 text-blue-800",template:"bg-purple-100 text-purple-800",academy_video:"bg-green-100 text-green-800",resource_kit:"bg-orange-100 text-orange-800",newsletter:"bg-pink-100 text-pink-800",social_swag:"bg-yellow-100 text-yellow-800"};function Rye({brokerageOnly:t=!1,brokerageId:e}){const[r,n]=D.useState([]),[i,o]=D.useState(!0),[c,a]=D.useState(""),[m,g]=D.useState("all");D.useEffect(()=>{_()},[e]);const _=async()=>{o(!0);try{let O=[];if(t&&e){const{data:X}=await ae.from("profiles").select("id").eq("brokerage_id",e);if(O=(X==null?void 0:X.map(ie=>ie.id))||[],O.length===0){n([]),o(!1);return}}let R=ae.from("resource_shares").select("*").order("created_at",{ascending:!1});t&&O.length>0&&(R=R.or(`sender_id.in.(${O.join(",")}),recipient_id.in.(${O.join(",")})`));const{data:z,error:W}=await R;if(W)throw W;const V=new Set;z==null||z.forEach(X=>{V.add(X.sender_id),V.add(X.recipient_id)});const{data:K}=await ae.from("profiles").select("id, name, email").in("id",Array.from(V)),Q=new Map((K==null?void 0:K.map(X=>[X.id,X]))||[]),te=(z==null?void 0:z.map(X=>({...X,sender:Q.get(X.sender_id),recipient:Q.get(X.recipient_id)})))||[];n(te)}catch(O){console.error("Error loading shares:",O)}finally{o(!1)}},j=r.filter(O=>{var W,V;const R=c===""||O.resource_title.toLowerCase().includes(c.toLowerCase())||((W=O.sender)==null?void 0:W.name.toLowerCase().includes(c.toLowerCase()))||((V=O.recipient)==null?void 0:V.name.toLowerCase().includes(c.toLowerCase())),z=m==="all"||O.resource_type===m;return R&&z}),N=r.length,C=new Set(r.map(O=>O.sender_id)).size,P=new Set(r.map(O=>O.recipient_id)).size,A=r.length>0?Math.round(r.filter(O=>O.is_read).length/r.length*100):0,I=r.reduce((O,R)=>(O[R.resource_type]=(O[R.resource_type]||0)+1,O),{});return i?s.jsxs("div",{className:"space-y-4",children:[s.jsx("div",{className:"grid gap-4 md:grid-cols-4",children:[...Array(4)].map((O,R)=>s.jsxs(at,{children:[s.jsx(xr,{className:"pb-2",children:s.jsx(Dn,{className:"h-4 w-20"})}),s.jsx(ct,{children:s.jsx(Dn,{className:"h-8 w-16"})})]},R))}),s.jsx(at,{children:s.jsx(ct,{className:"p-6",children:s.jsx(Dn,{className:"h-[300px]"})})})]}):s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"grid gap-4 md:grid-cols-4",children:[s.jsxs(at,{children:[s.jsxs(xr,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[s.jsx(wr,{className:"text-sm font-medium",children:"Total Shares"}),s.jsx(ph,{className:"h-4 w-4 text-muted-foreground"})]}),s.jsx(ct,{children:s.jsx("div",{className:"text-2xl font-bold",children:N})})]}),s.jsxs(at,{children:[s.jsxs(xr,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[s.jsx(wr,{className:"text-sm font-medium",children:"Active Sharers"}),s.jsx(_i,{className:"h-4 w-4 text-muted-foreground"})]}),s.jsx(ct,{children:s.jsx("div",{className:"text-2xl font-bold",children:C})})]}),s.jsxs(at,{children:[s.jsxs(xr,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[s.jsx(wr,{className:"text-sm font-medium",children:"Recipients Reached"}),s.jsx(r0,{className:"h-4 w-4 text-muted-foreground"})]}),s.jsx(ct,{children:s.jsx("div",{className:"text-2xl font-bold",children:P})})]}),s.jsxs(at,{children:[s.jsxs(xr,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[s.jsx(wr,{className:"text-sm font-medium",children:"Read Rate"}),s.jsx(Ii,{className:"h-4 w-4 text-muted-foreground"})]}),s.jsx(ct,{children:s.jsxs("div",{className:"text-2xl font-bold",children:[A,"%"]})})]})]}),s.jsxs(at,{children:[s.jsx(xr,{children:s.jsx(wr,{className:"text-sm font-medium",children:"Shares by Resource Type"})}),s.jsx(ct,{children:s.jsxs("div",{className:"flex flex-wrap gap-2",children:[Object.entries(I).map(([O,R])=>s.jsxs(ir,{variant:"secondary",className:qJ[O],children:[VJ[O],": ",R]},O)),Object.keys(I).length===0&&s.jsx("span",{className:"text-muted-foreground text-sm",children:"No shares yet"})]})})]}),s.jsxs(at,{children:[s.jsxs(xr,{children:[s.jsx(wr,{children:"Share History"}),s.jsxs(us,{children:["All resource shares ",t?"in your brokerage":"across the platform"]})]}),s.jsxs(ct,{children:[s.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 mb-4",children:[s.jsxs("div",{className:"relative flex-1",children:[s.jsx(ba,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),s.jsx(Et,{placeholder:"Search by resource, sender, or recipient...",value:c,onChange:O=>a(O.target.value),className:"pl-9"})]}),s.jsxs(Kn,{value:m,onValueChange:g,children:[s.jsx(qn,{className:"w-[180px]",children:s.jsx(Zn,{placeholder:"Resource type"})}),s.jsxs(Hn,{children:[s.jsx(_r,{value:"all",children:"All Types"}),s.jsx(_r,{value:"event",children:"Events"}),s.jsx(_r,{value:"template",children:"Templates"}),s.jsx(_r,{value:"academy_video",children:"Academy Videos"}),s.jsx(_r,{value:"resource_kit",children:"Resource Kits"}),s.jsx(_r,{value:"newsletter",children:"Newsletters"}),s.jsx(_r,{value:"social_swag",children:"Social Swag"})]})]})]}),s.jsx(qu,{className:"h-[400px]",children:s.jsxs(ni,{children:[s.jsx(si,{children:s.jsxs(Dr,{children:[s.jsx(Nt,{children:"Resource"}),s.jsx(Nt,{children:"Type"}),s.jsx(Nt,{children:"Sender"}),s.jsx(Nt,{children:"Recipient"}),s.jsx(Nt,{children:"Status"}),s.jsx(Nt,{children:"Date"})]})}),s.jsx(ii,{children:j.length===0?s.jsx(Dr,{children:s.jsx(xt,{colSpan:6,className:"text-center text-muted-foreground py-8",children:"No shares found"})}):j.map(O=>{var R,z;return s.jsxs(Dr,{children:[s.jsx(xt,{className:"font-medium max-w-[200px] truncate",children:O.resource_title}),s.jsx(xt,{children:s.jsx(ir,{variant:"secondary",className:qJ[O.resource_type],children:VJ[O.resource_type]})}),s.jsx(xt,{children:((R=O.sender)==null?void 0:R.name)||"Unknown"}),s.jsx(xt,{children:((z=O.recipient)==null?void 0:z.name)||"Unknown"}),s.jsx(xt,{children:s.jsx(ir,{variant:O.is_read?"default":"outline",children:O.is_read?"Read":"Unread"})}),s.jsx(xt,{className:"text-muted-foreground",children:Vn(new Date(O.created_at),"MMM d, yyyy")})]},O.id)})})]})})]})]})]})}const h9e=()=>s.jsx(Jr,{title:"Analytics",children:s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{children:[s.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Analytics & Activity"}),s.jsx("p",{className:"text-muted-foreground mt-1",children:"Platform-wide usage statistics and user activity"})]}),s.jsxs(go,{defaultValue:"analytics",className:"space-y-4",children:[s.jsxs(ao,{children:[s.jsx(Bn,{value:"analytics",children:"Analytics"}),s.jsx(Bn,{value:"activity",children:"Activity"}),s.jsx(Bn,{value:"shares",children:"Shares"})]}),s.jsx(xs,{value:"analytics",className:"space-y-4",children:s.jsx(d9e,{})}),s.jsx(xs,{value:"activity",className:"space-y-4",children:s.jsx(u9e,{})}),s.jsx(xs,{value:"shares",className:"space-y-4",children:s.jsx(Rye,{})})]})]})});function f9e(){const t=Wn(),[e,r]=D.useState(!1),[n,i]=D.useState(null),[o,c]=D.useState({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,category_id:""}),[a,m]=D.useState(null),[g,_]=D.useState(""),[j,N]=D.useState([]),[C,P]=D.useState([]),[A,I]=D.useState([]),[O,R]=D.useState(!1),[z,W]=D.useState(null),[V,K]=D.useState(""),{data:Q,isLoading:te}=Sr({queryKey:["brokerage-resources"],queryFn:async()=>{const{data:Pe,error:ut}=await ae.from("brokerage_resources").select("*").order("publish_date",{ascending:!1});if(ut)throw ut;return Pe}}),{data:X}=Sr({queryKey:["brokerage-resource-pdfs"],queryFn:async()=>{const{data:Pe,error:ut}=await ae.from("brokerage_resource_pdfs").select("*").order("sort_order",{ascending:!0});if(ut)throw ut;return Pe}}),{data:ie}=Sr({queryKey:["brokerage-resource-videos"],queryFn:async()=>{const{data:Pe,error:ut}=await ae.from("brokerage_resource_videos").select("*").order("sort_order",{ascending:!0});if(ut)throw ut;return Pe}}),{data:he}=Sr({queryKey:["brokerage-resource-links"],queryFn:async()=>{const{data:Pe,error:ut}=await ae.from("brokerage_resource_links").select("*").order("sort_order",{ascending:!0});if(ut)throw ut;return Pe}}),{data:xe,isLoading:pe}=Sr({queryKey:["brokerage-resource-categories"],queryFn:async()=>{const{data:Pe,error:ut}=await ae.from("brokerage_resource_categories").select("*").order("sort_order",{ascending:!0});if(ut)throw ut;return Pe}}),ve=()=>{c({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,category_id:""}),m(null),_(""),N([]),P([]),I([]),i(null),K("")},ge=Pe=>{i(Pe),c({title:Pe.title,description:Pe.description||"",publish_date:Pe.publish_date.split("T")[0],is_published:Pe.is_published,category_id:Pe.category_id||""}),_(Pe.preview_image_url||""),K("");const ut=(X==null?void 0:X.filter(Ht=>Ht.resource_id===Pe.id))||[];N(ut.map(Ht=>({id:Ht.id,name:Ht.name,file_url:Ht.file_url,file_size:Ht.file_size,sort_order:Ht.sort_order})));const jt=(ie==null?void 0:ie.filter(Ht=>Ht.resource_id===Pe.id))||[];P(jt.map(Ht=>({id:Ht.id,title:Ht.title,video_url:Ht.video_url,sort_order:Ht.sort_order})));const $t=(he==null?void 0:he.filter(Ht=>Ht.resource_id===Pe.id))||[];I($t.map(Ht=>({id:Ht.id,title:Ht.title,canva_share_link:Ht.canva_share_link,sort_order:Ht.sort_order}))),r(!0)},ke=Pe=>{var jt;const ut=(jt=Pe.target.files)==null?void 0:jt[0];ut&&(m(ut),_(URL.createObjectURL(ut)))},Ce=()=>{N([...j,{name:"",file_url:"",sort_order:j.length}])},Se=Pe=>{N(j.filter((ut,jt)=>jt!==Pe))},je=(Pe,ut,jt)=>{const $t=[...j];if(ut==="file"&&jt instanceof File){const Ht=jt.name.replace(/\.[^/.]+$/,"");$t[Pe]={...$t[Pe],file:jt,file_size:jt.size,name:$t[Pe].name||Ht}}else $t[Pe]={...$t[Pe],[ut]:jt};N($t)},et=()=>{P([...C,{title:"",video_url:"",sort_order:C.length}])},bt=Pe=>{P(C.filter((ut,jt)=>jt!==Pe))},_e=(Pe,ut,jt)=>{const $t=[...C];ut==="file"&&jt instanceof File?$t[Pe]={...$t[Pe],file:jt}:$t[Pe]={...$t[Pe],[ut]:jt},P($t)},Ye=()=>{I([...A,{title:"",canva_share_link:"",sort_order:A.length}])},pt=Pe=>{I(A.filter((ut,jt)=>jt!==Pe))},nt=(Pe,ut,jt)=>{const $t=[...A];$t[Pe]={...$t[Pe],[ut]:jt},I($t)},Qt=async(Pe,ut)=>{try{const jt=await ae.functions.invoke("bunny-upload",{body:{action:"create",title:Pe.name}});if(jt.error)throw jt.error;const{videoId:$t,uploadUrl:Ht,libraryId:Lt}=jt.data,Kt=await ae.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:$t,libraryId:Lt}});if(Kt.error)throw Kt.error;const{uploadUrl:Ar,apiKey:rt}=Kt.data,We=new XMLHttpRequest;return We.open("PUT",Ar,!0),We.setRequestHeader("AccessKey",rt),We.upload.onprogress=_t=>{if(_t.lengthComputable){const Gt=Math.round(_t.loaded/_t.total*100),rr=[...C];rr[ut]={...rr[ut],uploadProgress:Gt},P(rr)}},await new Promise((_t,Gt)=>{We.onload=()=>We.status>=200&&We.status<300?_t():Gt(new Error("Upload failed")),We.onerror=()=>Gt(new Error("Upload failed")),We.send(Pe)}),`https://iframe.mediadelivery.net/embed/${Lt}/${$t}`}catch(jt){throw console.error("Bunny upload error:",jt),jt}},gt=zr({mutationFn:async Pe=>{const{data:ut,error:jt}=await ae.from("brokerage_resource_categories").insert({name:Pe,sort_order:(xe==null?void 0:xe.length)||0}).select().single();if(jt)throw jt;return ut},onSuccess:Pe=>{t.invalidateQueries({queryKey:["brokerage-resource-categories"]}),c({...o,category_id:Pe.id}),K(""),Dt.success("Category created")},onError:Pe=>{Dt.error("Failed to create category: "+Pe.message)}}),Me=zr({mutationFn:async()=>{R(!0);let Pe=(n==null?void 0:n.preview_image_url)||null;if(a){const $t=a.name.split(".").pop(),Ht=`${Date.now()}.${$t}`,{error:Lt}=await ae.storage.from("brokerage-resources").upload(`previews/${Ht}`,a);if(Lt)throw Lt;const{data:Kt}=ae.storage.from("brokerage-resources").getPublicUrl(`previews/${Ht}`);Pe=Kt.publicUrl}const ut={title:o.title,description:o.description||null,preview_image_url:Pe,publish_date:o.publish_date,is_published:o.is_published,category_id:o.category_id||null};let jt;if(n){const{error:$t}=await ae.from("brokerage_resources").update(ut).eq("id",n.id);if($t)throw $t;jt=n.id;const Ht=(X==null?void 0:X.filter(pr=>pr.resource_id===n.id).map(pr=>pr.id))||[],Lt=j.filter(pr=>pr.id).map(pr=>pr.id),Kt=Ht.filter(pr=>!Lt.includes(pr));Kt.length>0&&await ae.from("brokerage_resource_pdfs").delete().in("id",Kt);const Ar=(ie==null?void 0:ie.filter(pr=>pr.resource_id===n.id).map(pr=>pr.id))||[],rt=C.filter(pr=>pr.id).map(pr=>pr.id),We=Ar.filter(pr=>!rt.includes(pr));We.length>0&&await ae.from("brokerage_resource_videos").delete().in("id",We);const _t=(he==null?void 0:he.filter(pr=>pr.resource_id===n.id).map(pr=>pr.id))||[],Gt=A.filter(pr=>pr.id).map(pr=>pr.id),rr=_t.filter(pr=>!Gt.includes(pr));rr.length>0&&await ae.from("brokerage_resource_links").delete().in("id",rr)}else{const{data:$t,error:Ht}=await ae.from("brokerage_resources").insert(ut).select().single();if(Ht)throw Ht;jt=$t.id}for(let $t=0;$t{t.invalidateQueries({queryKey:["brokerage-resources"]}),t.invalidateQueries({queryKey:["brokerage-resource-pdfs"]}),t.invalidateQueries({queryKey:["brokerage-resource-videos"]}),t.invalidateQueries({queryKey:["brokerage-resource-links"]}),Dt.success(n?"Resource updated":"Resource created"),r(!1),ve(),R(!1)},onError:Pe=>{Dt.error("Failed to save resource: "+Pe.message),R(!1)}}),Oe=zr({mutationFn:async Pe=>{const{error:ut}=await ae.from("brokerage_resources").delete().eq("id",Pe);if(ut)throw ut},onSuccess:()=>{t.invalidateQueries({queryKey:["brokerage-resources"]}),t.invalidateQueries({queryKey:["brokerage-resource-pdfs"]}),t.invalidateQueries({queryKey:["brokerage-resource-videos"]}),t.invalidateQueries({queryKey:["brokerage-resource-links"]}),Dt.success("Resource deleted")},onError:Pe=>{Dt.error("Failed to delete: "+Pe.message)}}),Ie=Pe=>{if(Pe.preventDefault(),!o.title){Dt.error("Please enter a title");return}Me.mutate()},Be=Pe=>{const ut=(X==null?void 0:X.filter(Ht=>Ht.resource_id===Pe).length)||0,jt=(ie==null?void 0:ie.filter(Ht=>Ht.resource_id===Pe).length)||0,$t=(he==null?void 0:he.filter(Ht=>Ht.resource_id===Pe).length)||0;return{pdfCount:ut,videoCount:jt,linkCount:$t}};return s.jsx(Jr,{title:"Brokerage Resources Management",description:"Create and manage resources for brokerage managers",children:s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsxs(at,{children:[s.jsx(xr,{className:"pb-2",children:s.jsx(wr,{className:"text-sm font-medium text-muted-foreground",children:"Total Resources"})}),s.jsx(ct,{children:s.jsx("div",{className:"text-2xl font-bold",children:(Q==null?void 0:Q.length)||0})})]}),s.jsxs(at,{children:[s.jsx(xr,{className:"pb-2",children:s.jsx(wr,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),s.jsx(ct,{children:s.jsx("div",{className:"text-2xl font-bold",children:(Q==null?void 0:Q.filter(Pe=>Pe.is_published).length)||0})})]})]}),s.jsxs(de,{onClick:()=>{ve(),r(!0)},children:[s.jsx(Qn,{className:"h-4 w-4 mr-2"}),"Add Resource"]})]}),s.jsx(at,{children:s.jsx(ct,{className:"p-0",children:s.jsxs(ni,{children:[s.jsx(si,{children:s.jsxs(Dr,{children:[s.jsx(Nt,{children:"Title"}),s.jsx(Nt,{children:"Category"}),s.jsx(Nt,{children:"Content"}),s.jsx(Nt,{children:"Publish Date"}),s.jsx(Nt,{children:"Status"}),s.jsx(Nt,{className:"text-right",children:"Actions"})]})}),s.jsx(ii,{children:te?s.jsx(Dr,{children:s.jsx(xt,{colSpan:6,className:"text-center py-8",children:"Loading..."})}):(Q==null?void 0:Q.length)===0?s.jsx(Dr,{children:s.jsx(xt,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No brokerage resources yet. Create your first one!"})}):Q==null?void 0:Q.map(Pe=>{const{pdfCount:ut,videoCount:jt,linkCount:$t}=Be(Pe.id),Ht=xe==null?void 0:xe.find(Lt=>Lt.id===Pe.category_id);return s.jsxs(Dr,{children:[s.jsx(xt,{children:s.jsxs("div",{className:"flex items-center gap-3",children:[Pe.preview_image_url?s.jsx("img",{src:Pe.preview_image_url,alt:Pe.title,className:"w-10 h-10 rounded object-cover"}):s.jsx("div",{className:"w-10 h-10 rounded bg-muted flex items-center justify-center",children:s.jsx(Hm,{className:"h-5 w-5 text-muted-foreground"})}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium",children:Pe.title}),Pe.description&&s.jsx("div",{className:"text-sm text-muted-foreground line-clamp-1",children:Pe.description})]})]})}),s.jsx(xt,{children:Ht?s.jsx("span",{className:"inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-muted",children:Ht.name}):s.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),s.jsx(xt,{children:s.jsxs("div",{className:"flex items-center gap-3 text-sm text-muted-foreground",children:[s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(Ii,{className:"h-3.5 w-3.5"}),ut]}),s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(Ia,{className:"h-3.5 w-3.5"}),jt]}),s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(Go,{className:"h-3.5 w-3.5"}),$t]})]})}),s.jsx(xt,{children:Vn(new Date(Pe.publish_date),"MMM d, yyyy")}),s.jsx(xt,{children:s.jsx("span",{className:`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${Pe.is_published?"bg-green-100 text-green-800":"bg-yellow-100 text-yellow-800"}`,children:Pe.is_published?"Published":"Draft"})}),s.jsx(xt,{className:"text-right",children:s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(de,{variant:"ghost",size:"icon",onClick:()=>{const Lt=(X==null?void 0:X.filter(rt=>rt.resource_id===Pe.id))||[],Kt=(ie==null?void 0:ie.filter(rt=>rt.resource_id===Pe.id))||[],Ar=(he==null?void 0:he.filter(rt=>rt.resource_id===Pe.id))||[];W({...Pe,pdfs:Lt,videos:Kt,links:Ar})},children:s.jsx(Rc,{className:"h-4 w-4"})}),s.jsx(de,{variant:"ghost",size:"icon",onClick:()=>ge(Pe),children:s.jsx(io,{className:"h-4 w-4"})}),s.jsx(de,{variant:"ghost",size:"icon",onClick:()=>{confirm("Delete this resource?")&&Oe.mutate(Pe.id)},children:s.jsx(oi,{className:"h-4 w-4 text-destructive"})})]})})]},Pe.id)})})]})})}),s.jsx(mn,{open:e,onOpenChange:r,children:s.jsxs(pn,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[s.jsx(xn,{children:s.jsx(gn,{children:n?"Edit Brokerage Resource":"Add Brokerage Resource"})}),s.jsxs("form",{onSubmit:Ie,className:"space-y-6",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Preview Image"}),s.jsxs("div",{className:"flex items-center gap-4",children:[g?s.jsx("img",{src:g,alt:"Preview",className:"w-24 h-24 rounded object-cover"}):s.jsx("div",{className:"w-24 h-24 rounded bg-muted flex items-center justify-center",children:s.jsx(Hm,{className:"h-8 w-8 text-muted-foreground"})}),s.jsx(Et,{type:"file",accept:"image/*",onChange:ke})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"title",children:"Title *"}),s.jsx(Et,{id:"title",value:o.title,onChange:Pe=>c({...o,title:Pe.target.value}),placeholder:"Resource Title"})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs(mt,{className:"flex items-center gap-2",children:[s.jsx(joe,{className:"h-4 w-4"}),"Category"]}),s.jsxs("div",{className:"flex gap-2",children:[s.jsxs(Kn,{value:o.category_id,onValueChange:Pe=>c({...o,category_id:Pe}),children:[s.jsx(qn,{className:"flex-1",children:s.jsx(Zn,{placeholder:"Select a category"})}),s.jsx(Hn,{children:xe==null?void 0:xe.map(Pe=>s.jsx(_r,{value:Pe.id,children:Pe.name},Pe.id))})]}),o.category_id&&s.jsx(de,{type:"button",variant:"ghost",size:"icon",onClick:()=>c({...o,category_id:""}),children:s.jsx(Ni,{className:"h-4 w-4"})})]}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(Et,{placeholder:"Or create new category...",value:V,onChange:Pe=>K(Pe.target.value),className:"flex-1"}),s.jsxs(de,{type:"button",variant:"outline",size:"sm",disabled:!V.trim()||gt.isPending,onClick:()=>gt.mutate(V.trim()),children:[s.jsx(Qn,{className:"h-4 w-4 mr-1"}),"Add"]})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Description"}),s.jsx(ag,{content:o.description,onChange:Pe=>c({...o,description:Pe}),placeholder:"Brief description of this resource",minHeight:"120px"})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"publish_date",children:"Publish Date"}),s.jsx(Et,{id:"publish_date",type:"date",value:o.publish_date,onChange:Pe=>c({...o,publish_date:Pe.target.value})})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Published"}),s.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[s.jsx(ri,{checked:o.is_published,onCheckedChange:Pe=>c({...o,is_published:Pe})}),s.jsx("span",{className:"text-sm text-muted-foreground",children:o.is_published?"Visible to brokerage managers":"Hidden from brokerage managers"})]})]})]}),s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs(mt,{className:"flex items-center gap-2",children:[s.jsx(Ii,{className:"h-4 w-4"}),"PDF Documents (",j.length,")"]}),s.jsxs(de,{type:"button",variant:"outline",size:"sm",onClick:Ce,children:[s.jsx(Qn,{className:"h-4 w-4 mr-1"}),"Add PDF"]})]}),j.map((Pe,ut)=>s.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg bg-muted/50",children:[s.jsx(Et,{placeholder:"PDF Name",value:Pe.name,onChange:jt=>je(ut,"name",jt.target.value),className:"flex-1"}),s.jsx(Et,{type:"file",accept:".pdf",onChange:jt=>{var Ht;const $t=(Ht=jt.target.files)==null?void 0:Ht[0];$t&&je(ut,"file",$t)},className:"flex-1"}),Pe.file_url&&!Pe.file&&s.jsx("span",{className:"text-xs text-muted-foreground",children:"Uploaded"}),s.jsx(de,{type:"button",variant:"ghost",size:"icon",onClick:()=>Se(ut),children:s.jsx(Ni,{className:"h-4 w-4"})})]},ut))]}),s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs(mt,{className:"flex items-center gap-2",children:[s.jsx(Ia,{className:"h-4 w-4"}),"Videos (",C.length,")"]}),s.jsxs(de,{type:"button",variant:"outline",size:"sm",onClick:et,children:[s.jsx(Qn,{className:"h-4 w-4 mr-1"}),"Add Video"]})]}),C.map((Pe,ut)=>s.jsxs("div",{className:"space-y-2 p-3 border rounded-lg bg-muted/50",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Et,{placeholder:"Video Title",value:Pe.title,onChange:jt=>_e(ut,"title",jt.target.value),className:"flex-1"}),s.jsx(de,{type:"button",variant:"ghost",size:"icon",onClick:()=>bt(ut),children:s.jsx(Ni,{className:"h-4 w-4"})})]}),s.jsx(Et,{type:"file",accept:"video/*",onChange:jt=>{var Ht;const $t=(Ht=jt.target.files)==null?void 0:Ht[0];$t&&_e(ut,"file",$t)}}),Pe.uploadProgress!==void 0&&Pe.uploadProgress>0&&s.jsx("div",{className:"w-full bg-muted rounded-full h-2",children:s.jsx("div",{className:"bg-primary h-2 rounded-full transition-all",style:{width:`${Pe.uploadProgress}%`}})}),Pe.video_url&&!Pe.file&&s.jsx("span",{className:"text-xs text-muted-foreground",children:"Video uploaded"})]},ut))]}),s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs(mt,{className:"flex items-center gap-2",children:[s.jsx(Go,{className:"h-4 w-4"}),"Canva Links (",A.length,")"]}),s.jsxs(de,{type:"button",variant:"outline",size:"sm",onClick:Ye,children:[s.jsx(Qn,{className:"h-4 w-4 mr-1"}),"Add Link"]})]}),A.map((Pe,ut)=>s.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg bg-muted/50",children:[s.jsx(Et,{placeholder:"Link Title",value:Pe.title,onChange:jt=>nt(ut,"title",jt.target.value),className:"flex-1"}),s.jsx(Et,{placeholder:"Canva Share Link",value:Pe.canva_share_link,onChange:jt=>nt(ut,"canva_share_link",jt.target.value),className:"flex-1"}),s.jsx(de,{type:"button",variant:"ghost",size:"icon",onClick:()=>pt(ut),children:s.jsx(Ni,{className:"h-4 w-4"})})]},ut))]}),s.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[s.jsx(de,{type:"button",variant:"outline",onClick:()=>r(!1),children:"Cancel"}),s.jsx(de,{type:"submit",disabled:Me.isPending||O,children:Me.isPending||O?"Saving...":n?"Update":"Create"})]})]})]})}),s.jsx(mn,{open:!!z,onOpenChange:()=>W(null),children:s.jsxs(pn,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[s.jsx(xn,{children:s.jsx(gn,{children:z==null?void 0:z.title})}),z&&s.jsxs("div",{className:"space-y-4",children:[z.preview_image_url&&s.jsx("img",{src:z.preview_image_url,alt:z.title,className:"w-full h-48 object-cover rounded-lg"}),z.description&&s.jsx("p",{className:"text-muted-foreground",children:z.description}),z.pdfs&&z.pdfs.length>0&&s.jsxs("div",{children:[s.jsxs("h4",{className:"font-medium mb-2 flex items-center gap-2",children:[s.jsx(Ii,{className:"h-4 w-4"}),"PDF Documents (",z.pdfs.length,")"]}),s.jsx("div",{className:"space-y-1",children:z.pdfs.map(Pe=>s.jsx("a",{href:Pe.file_url,target:"_blank",rel:"noopener noreferrer",className:"block p-2 border rounded hover:bg-muted",children:Pe.name},Pe.id))})]}),z.videos&&z.videos.length>0&&s.jsxs("div",{children:[s.jsxs("h4",{className:"font-medium mb-2 flex items-center gap-2",children:[s.jsx(Ia,{className:"h-4 w-4"}),"Videos (",z.videos.length,")"]}),s.jsx("div",{className:"space-y-2",children:z.videos.map(Pe=>s.jsx("div",{className:"p-2 border rounded",children:s.jsx("p",{className:"font-medium text-sm",children:Pe.title})},Pe.id))})]}),z.links&&z.links.length>0&&s.jsxs("div",{children:[s.jsxs("h4",{className:"font-medium mb-2 flex items-center gap-2",children:[s.jsx(Go,{className:"h-4 w-4"}),"Canva Links (",z.links.length,")"]}),s.jsx("div",{className:"space-y-1",children:z.links.map(Pe=>s.jsx("a",{href:Pe.canva_share_link,target:"_blank",rel:"noopener noreferrer",className:"block p-2 border rounded hover:bg-muted",children:Pe.title},Pe.id))})]})]})]})})]})})}const Dye=[{value:"events",label:"After Events Section"},{value:"academy",label:"After Academy Section"},{value:"toolbox",label:"After Toolbox Section"},{value:"templates",label:"After Templates Section"},{value:"apps",label:"After Apps Section"}];function p9e(){const[t,e]=D.useState([]),[r,n]=D.useState(!0),[i,o]=D.useState(!1),[c,a]=D.useState(!1),[m,g]=D.useState(null),[_,j]=D.useState(!1),[N,C]=D.useState(!1),[P,A]=D.useState(""),[I,O]=D.useState(""),[R,z]=D.useState(""),[W,V]=D.useState(""),[K,Q]=D.useState("Learn More"),[te,X]=D.useState("top"),[ie,he]=D.useState(""),[xe,pe]=D.useState(!0),[ve,ge]=D.useState(""),[ke,Ce]=D.useState("");D.useEffect(()=>{Se()},[]);const Se=async()=>{try{const{data:gt,error:Me}=await ae.from("dashboard_banners").select("*").order("placement").order("sort_order");if(Me)throw Me;e(gt||[])}catch(gt){Dt.error("Failed to load banners: "+gt.message)}finally{n(!1)}},je=()=>{A(""),O(""),z(""),V(""),Q("Learn More"),X("top"),he(""),pe(!0),ge(""),Ce(""),g(null)},et=gt=>{g(gt),A(gt.title),O(gt.description||""),z(gt.image_url),V(gt.link_url||""),Q(gt.link_text||"Learn More"),X(gt.placement),he(gt.section_after||""),pe(gt.is_active),ge(gt.start_date?Vn(new Date(gt.start_date),"yyyy-MM-dd'T'HH:mm"):""),Ce(gt.end_date?Vn(new Date(gt.end_date),"yyyy-MM-dd'T'HH:mm"):""),o(!0)},bt=async gt=>{var Oe;const Me=(Oe=gt.target.files)==null?void 0:Oe[0];if(Me){j(!0);try{const Ie=Me.name.split(".").pop(),Be=`${Date.now()}.${Ie}`,{error:Pe}=await ae.storage.from("banner-images").upload(Be,Me);if(Pe)throw Pe;const{data:{publicUrl:ut}}=ae.storage.from("banner-images").getPublicUrl(Be);z(ut),Dt.success("Image uploaded successfully")}catch(Ie){Dt.error("Failed to upload image: "+Ie.message)}finally{j(!1)}}},_e=async()=>{if(!P.trim()||!R){Dt.error("Please fill in required fields (title and image)");return}C(!0);try{const gt={title:P.trim(),description:I.trim()||null,image_url:R,link_url:W.trim()||null,link_text:K.trim()||"Learn More",placement:te,section_after:te==="between"?ie:null,is_active:xe,start_date:ve?new Date(ve).toISOString():null,end_date:ke?new Date(ke).toISOString():null};if(m){const{error:Me}=await ae.from("dashboard_banners").update(gt).eq("id",m.id);if(Me)throw Me;Dt.success("Banner updated successfully")}else{const Me=t.filter(Ie=>Ie.placement===te).length,{error:Oe}=await ae.from("dashboard_banners").insert({...gt,sort_order:Me});if(Oe)throw Oe;Dt.success("Banner created successfully")}o(!1),je(),Se()}catch(gt){Dt.error("Failed to save banner: "+gt.message)}finally{C(!1)}},Ye=async()=>{if(m)try{const{error:gt}=await ae.from("dashboard_banners").delete().eq("id",m.id);if(gt)throw gt;Dt.success("Banner deleted successfully"),a(!1),g(null),Se()}catch(gt){Dt.error("Failed to delete banner: "+gt.message)}},pt=async gt=>{try{const{error:Me}=await ae.from("dashboard_banners").update({is_active:!gt.is_active}).eq("id",gt.id);if(Me)throw Me;Dt.success(gt.is_active?"Banner deactivated":"Banner activated"),Se()}catch(Me){Dt.error("Failed to update banner: "+Me.message)}},nt=t.filter(gt=>gt.placement==="top"),Qt=t.filter(gt=>gt.placement==="between");return r?s.jsx(Jr,{title:"Dashboard Management",children:s.jsx("div",{className:"flex items-center justify-center h-64",children:s.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})})}):s.jsxs(Jr,{title:"Dashboard Management",description:"Configure dashboard modules and banners",children:[s.jsxs("div",{className:"space-y-8",children:[s.jsxs(at,{children:[s.jsxs(xr,{className:"flex flex-row items-center justify-between",children:[s.jsxs("div",{children:[s.jsxs(wr,{className:"flex items-center gap-2",children:[s.jsx(Wm,{className:"h-5 w-5"}),"Hero Banners (Top of Dashboard)"]}),s.jsx(us,{children:"These banners appear in a rotating carousel at the top of the dashboard"})]}),s.jsxs(mn,{open:i&&te==="top",onOpenChange:gt=>{gt||je(),o(gt),gt&&X("top")},children:[s.jsx(Do,{asChild:!0,children:s.jsxs(de,{onClick:()=>{je(),X("top")},children:[s.jsx(Qn,{className:"mr-2 h-4 w-4"}),"Add Hero Banner"]})}),s.jsxs(pn,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[s.jsxs(xn,{children:[s.jsxs(gn,{children:[m?"Edit":"Create"," Banner"]}),s.jsx(fi,{children:"Configure the banner's content and display settings"})]}),s.jsx(HJ,{title:P,setTitle:A,description:I,setDescription:O,imageUrl:R,linkUrl:W,setLinkUrl:V,linkText:K,setLinkText:Q,placement:te,setPlacement:X,sectionAfter:ie,setSectionAfter:he,isActive:xe,setIsActive:pe,startDate:ve,setStartDate:ge,endDate:ke,setEndDate:Ce,handleImageUpload:bt,uploading:_,showPlacementOptions:!1}),s.jsxs(zi,{children:[s.jsx(de,{variant:"outline",onClick:()=>{o(!1),je()},children:"Cancel"}),s.jsx(de,{onClick:_e,disabled:N,children:N?"Saving...":m?"Update Banner":"Create Banner"})]})]})]})]}),s.jsx(ct,{children:nt.length===0?s.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No hero banners yet. Add your first banner above."}):s.jsx("div",{className:"space-y-3",children:nt.map(gt=>s.jsx(WJ,{banner:gt,onEdit:()=>et(gt),onDelete:()=>{g(gt),a(!0)},onToggleActive:()=>pt(gt)},gt.id))})})]}),s.jsxs(at,{children:[s.jsxs(xr,{className:"flex flex-row items-center justify-between",children:[s.jsxs("div",{children:[s.jsxs(wr,{className:"flex items-center gap-2",children:[s.jsx(Wm,{className:"h-5 w-5"}),"Section Banners"]}),s.jsx(us,{children:"These banners appear between dashboard content sections"})]}),s.jsxs(mn,{open:i&&te==="between",onOpenChange:gt=>{gt||je(),o(gt),gt&&X("between")},children:[s.jsx(Do,{asChild:!0,children:s.jsxs(de,{onClick:()=>{je(),X("between")},children:[s.jsx(Qn,{className:"mr-2 h-4 w-4"}),"Add Section Banner"]})}),s.jsxs(pn,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[s.jsxs(xn,{children:[s.jsxs(gn,{children:[m?"Edit":"Create"," Section Banner"]}),s.jsx(fi,{children:"Configure where this banner appears between sections"})]}),s.jsx(HJ,{title:P,setTitle:A,description:I,setDescription:O,imageUrl:R,linkUrl:W,setLinkUrl:V,linkText:K,setLinkText:Q,placement:te,setPlacement:X,sectionAfter:ie,setSectionAfter:he,isActive:xe,setIsActive:pe,startDate:ve,setStartDate:ge,endDate:ke,setEndDate:Ce,handleImageUpload:bt,uploading:_,showPlacementOptions:!0}),s.jsxs(zi,{children:[s.jsx(de,{variant:"outline",onClick:()=>{o(!1),je()},children:"Cancel"}),s.jsx(de,{onClick:_e,disabled:N,children:N?"Saving...":m?"Update Banner":"Create Banner"})]})]})]})]}),s.jsx(ct,{children:Qt.length===0?s.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No section banners yet. Add your first banner above."}):s.jsx("div",{className:"space-y-3",children:Qt.map(gt=>s.jsx(WJ,{banner:gt,onEdit:()=>et(gt),onDelete:()=>{g(gt),a(!0)},onToggleActive:()=>pt(gt),showSection:!0},gt.id))})})]})]}),s.jsx(mn,{open:c,onOpenChange:a,children:s.jsxs(pn,{children:[s.jsxs(xn,{children:[s.jsx(gn,{children:"Delete Banner"}),s.jsxs(fi,{children:['Are you sure you want to delete "',m==null?void 0:m.title,'"? This action cannot be undone.']})]}),s.jsxs(zi,{children:[s.jsx(de,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),s.jsx(de,{variant:"destructive",onClick:Ye,children:"Delete"})]})]})})]})}function HJ({title:t,setTitle:e,description:r,setDescription:n,imageUrl:i,linkUrl:o,setLinkUrl:c,linkText:a,setLinkText:m,placement:g,setPlacement:_,sectionAfter:j,setSectionAfter:N,isActive:C,setIsActive:P,startDate:A,setStartDate:I,endDate:O,setEndDate:R,handleImageUpload:z,uploading:W,showPlacementOptions:V}){return s.jsxs("div",{className:"space-y-4 py-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"title",children:"Title *"}),s.jsx(Et,{id:"title",placeholder:"Banner headline...",value:t,onChange:K=>e(K.target.value)})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"description",children:"Description"}),s.jsx(mi,{id:"description",placeholder:"Optional banner description...",value:r,onChange:K=>n(K.target.value),rows:2})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Banner Image *"}),s.jsxs("div",{className:"flex items-center gap-4",children:[s.jsx(Et,{type:"file",accept:"image/*",onChange:z,disabled:W,className:"flex-1"}),W&&s.jsx("span",{className:"text-sm text-muted-foreground",children:"Uploading..."})]}),i&&s.jsx("div",{className:"mt-2 relative rounded-lg overflow-hidden border",children:s.jsx("img",{src:i,alt:"Preview",className:"w-full h-40 object-cover"})})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"linkUrl",children:"Link URL (optional)"}),s.jsx(Et,{id:"linkUrl",placeholder:"https://...",value:o,onChange:K=>c(K.target.value)})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"linkText",children:"Button Text"}),s.jsx(Et,{id:"linkText",placeholder:"Learn More",value:a,onChange:K=>m(K.target.value)})]})]}),V&&s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Placement"}),s.jsxs(Kn,{value:j,onValueChange:N,children:[s.jsx(qn,{children:s.jsx(Zn,{placeholder:"Select section placement..."})}),s.jsx(Hn,{children:Dye.map(K=>s.jsx(_r,{value:K.value,children:K.label},K.value))})]})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsxs(mt,{htmlFor:"startDate",className:"flex items-center gap-2",children:[s.jsx(ko,{className:"h-4 w-4"}),"Start Date (optional)"]}),s.jsx(Et,{id:"startDate",type:"datetime-local",value:A,onChange:K=>I(K.target.value)})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs(mt,{htmlFor:"endDate",className:"flex items-center gap-2",children:[s.jsx(ko,{className:"h-4 w-4"}),"End Date (optional)"]}),s.jsx(Et,{id:"endDate",type:"datetime-local",value:O,onChange:K=>R(K.target.value)})]})]}),s.jsx("div",{className:"flex items-center justify-between pt-2",children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(ri,{id:"isActive",checked:C,onCheckedChange:P}),s.jsx(mt,{htmlFor:"isActive",children:"Active"})]})})]})}function WJ({banner:t,onEdit:e,onDelete:r,onToggleActive:n,showSection:i=!1}){var c;const o=(c=Dye.find(a=>a.value===t.section_after))==null?void 0:c.label;return s.jsxs("div",{className:"flex items-center gap-4 p-3 border rounded-lg bg-card hover:bg-accent/50 transition-colors",children:[s.jsx(foe,{className:"h-5 w-5 text-muted-foreground cursor-grab"}),s.jsx("img",{src:t.image_url,alt:t.title,className:"w-24 h-14 object-cover rounded"}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("h4",{className:"font-medium truncate",children:t.title}),!t.is_active&&s.jsx(ir,{variant:"secondary",children:"Inactive"}),t.start_date&&new Date(t.start_date)>new Date&&s.jsx(ir,{variant:"outline",children:"Scheduled"})]}),t.description&&s.jsx("p",{className:"text-sm text-muted-foreground truncate",children:t.description}),i&&o&&s.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:o})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[t.link_url&&s.jsx("a",{href:t.link_url,target:"_blank",rel:"noopener noreferrer",children:s.jsx(de,{variant:"ghost",size:"icon",children:s.jsx(oa,{className:"h-4 w-4"})})}),s.jsx(de,{variant:"ghost",size:"icon",onClick:n,children:t.is_active?s.jsx(Rc,{className:"h-4 w-4"}):s.jsx(Z6,{className:"h-4 w-4"})}),s.jsx(de,{variant:"ghost",size:"icon",onClick:e,children:s.jsx(io,{className:"h-4 w-4"})}),s.jsx(de,{variant:"ghost",size:"icon",onClick:r,children:s.jsx(oi,{className:"h-4 w-4 text-destructive"})})]})]})}const HP={open:{label:"Open",icon:No,color:"bg-yellow-500"},in_progress:{label:"In Progress",icon:lu,color:"bg-blue-500"},resolved:{label:"Resolved",icon:gc,color:"bg-green-500"},closed:{label:"Closed",icon:W2,color:"bg-muted-foreground"}},GJ={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function m9e(){var K,Q;const{user:t}=rn(),e=Wn(),[r,n]=D.useState(null),[i,o]=D.useState(""),[c,a]=D.useState("all"),[m,g]=D.useState("all"),[_,j]=D.useState(!1),{data:N=[],isLoading:C}=Sr({queryKey:["admin-support-tickets",c,m],queryFn:async()=>{let te=ae.from("support_tickets").select("*, profiles!support_tickets_user_id_fkey(name, email)").order("created_at",{ascending:!1});c!=="all"&&(te=te.eq("status",c)),m!=="all"&&(te=te.eq("category",m));const{data:X,error:ie}=await te;if(ie)throw ie;return X}}),{data:P=[]}=Sr({queryKey:["admin-users-notifications"],queryFn:async()=>{const{data:te,error:X}=await ae.from("user_roles").select("user_id").eq("role","admin");if(X)throw X;const ie=te.map(ke=>ke.user_id),{data:he,error:xe}=await ae.from("profiles").select("id, name, email").in("id",ie);if(xe)throw xe;const{data:pe,error:ve}=await ae.from("support_notification_settings").select("user_id, receive_notifications");if(ve)throw ve;const ge=new Map((pe==null?void 0:pe.map(ke=>[ke.user_id,ke.receive_notifications]))||[]);return he.map(ke=>({...ke,receives_notifications:ge.get(ke.id)||!1}))}}),{data:A=[]}=Sr({queryKey:["admin-ticket-replies",r==null?void 0:r.id],queryFn:async()=>{if(!r)return[];const{data:te,error:X}=await ae.from("support_ticket_replies").select("*, profiles(name)").eq("ticket_id",r.id).order("created_at",{ascending:!0});if(X)throw X;return te},enabled:!!r}),I=zr({mutationFn:async({userId:te,enabled:X})=>{const{data:ie}=await ae.from("support_notification_settings").select("id").eq("user_id",te).maybeSingle();if(ie){const{error:he}=await ae.from("support_notification_settings").update({receive_notifications:X}).eq("user_id",te);if(he)throw he}else{const{error:he}=await ae.from("support_notification_settings").insert({user_id:te,receive_notifications:X});if(he)throw he}},onSuccess:()=>{e.invalidateQueries({queryKey:["admin-users-notifications"]}),Dt.success("Notification settings updated")},onError:()=>{Dt.error("Failed to update settings")}}),O=zr({mutationFn:async({ticketId:te,status:X})=>{const{error:ie}=await ae.from("support_tickets").update({status:X}).eq("id",te);if(ie)throw ie},onSuccess:()=>{e.invalidateQueries({queryKey:["admin-support-tickets"]}),r&&n({...r,status:r.status}),Dt.success("Status updated")},onError:()=>{Dt.error("Failed to update status")}}),R=zr({mutationFn:async({ticketId:te,assignedTo:X})=>{const{error:ie}=await ae.from("support_tickets").update({assigned_to:X}).eq("id",te);if(ie)throw ie},onSuccess:()=>{e.invalidateQueries({queryKey:["admin-support-tickets"]}),Dt.success("Ticket assigned")},onError:()=>{Dt.error("Failed to assign ticket")}}),z=zr({mutationFn:async te=>{var ie,he;if(!r||!t)throw new Error("Missing data");const{error:X}=await ae.from("support_ticket_replies").insert({ticket_id:r.id,user_id:t.id,content:te,is_admin_reply:!0});if(X)throw X;try{await ae.functions.invoke("support-reply-notify",{body:{ticketId:r.id,ticketSubject:r.subject,replyContent:te,userEmail:(ie=r.profiles)==null?void 0:ie.email,userName:(he=r.profiles)==null?void 0:he.name}})}catch(xe){console.error("Failed to send reply notification:",xe)}},onSuccess:()=>{e.invalidateQueries({queryKey:["admin-ticket-replies",r==null?void 0:r.id]}),o(""),Dt.success("Reply sent!")},onError:()=>{Dt.error("Failed to send reply")}}),W=()=>{i.trim()&&z.mutate(i)};D.useEffect(()=>{const te=ae.channel("admin-tickets").on("postgres_changes",{event:"*",schema:"public",table:"support_tickets"},()=>{e.invalidateQueries({queryKey:["admin-support-tickets"]})}).subscribe();return()=>{ae.removeChannel(te)}},[e]);const V=N.filter(te=>te.status==="open").length;return r?(HP[r.status].icon,s.jsx(Jr,{children:s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"flex items-center gap-4",children:[s.jsx(de,{variant:"ghost",size:"icon",onClick:()=>n(null),children:s.jsx(Ka,{className:"h-5 w-5"})}),s.jsxs("div",{className:"flex-1",children:[s.jsx("h1",{className:"text-2xl font-bold",children:r.subject}),s.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[s.jsx(ir,{variant:"secondary",children:GJ[r.category]}),s.jsxs("span",{className:"text-sm text-muted-foreground",children:["from ",((K=r.profiles)==null?void 0:K.name)||"Unknown"," (",(Q=r.profiles)==null?void 0:Q.email,")"]})]})]})]}),s.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[s.jsxs(at,{children:[s.jsx(xr,{className:"pb-2",children:s.jsx(wr,{className:"text-sm",children:"Status"})}),s.jsx(ct,{children:s.jsxs(Kn,{value:r.status,onValueChange:te=>{O.mutate({ticketId:r.id,status:te}),n({...r,status:te})},children:[s.jsx(qn,{children:s.jsx(Zn,{})}),s.jsxs(Hn,{children:[s.jsx(_r,{value:"open",children:"Open"}),s.jsx(_r,{value:"in_progress",children:"In Progress"}),s.jsx(_r,{value:"resolved",children:"Resolved"}),s.jsx(_r,{value:"closed",children:"Closed"})]})]})})]}),s.jsxs(at,{children:[s.jsx(xr,{className:"pb-2",children:s.jsx(wr,{className:"text-sm",children:"Assigned To"})}),s.jsx(ct,{children:s.jsxs(Kn,{value:r.assigned_to||"unassigned",onValueChange:te=>{const X=te==="unassigned"?null:te;R.mutate({ticketId:r.id,assignedTo:X}),n({...r,assigned_to:X})},children:[s.jsx(qn,{children:s.jsx(Zn,{placeholder:"Unassigned"})}),s.jsxs(Hn,{children:[s.jsx(_r,{value:"unassigned",children:"Unassigned"}),P.map(te=>s.jsx(_r,{value:te.id,children:te.name},te.id))]})]})})]})]}),s.jsxs(at,{children:[s.jsx(xr,{children:s.jsxs(us,{children:["Created on ",Vn(new Date(r.created_at),"MMM d, yyyy 'at' h:mm a")]})}),s.jsx(ct,{children:s.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:r.description})})]}),s.jsxs(at,{children:[s.jsx(xr,{children:s.jsx(wr,{className:"text-lg",children:"Conversation"})}),s.jsxs(ct,{children:[s.jsx(qu,{className:"h-[300px] pr-4",children:A.length===0?s.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No replies yet"}):s.jsx("div",{className:"space-y-4",children:A.map(te=>{var X,ie;return s.jsxs("div",{className:`p-4 rounded-lg ${te.is_admin_reply?"bg-primary/10 ml-4":"bg-muted mr-4"}`,children:[s.jsxs("div",{className:"flex justify-between items-start mb-2",children:[s.jsx("span",{className:"font-medium text-sm",children:te.is_admin_reply?`${((X=te.profiles)==null?void 0:X.name)||"Admin"} (Support)`:((ie=te.profiles)==null?void 0:ie.name)||"User"}),s.jsx("span",{className:"text-xs text-muted-foreground",children:Vn(new Date(te.created_at),"MMM d, h:mm a")})]}),s.jsx("p",{className:"text-sm whitespace-pre-wrap",children:te.content})]},te.id)})})}),s.jsx(xf,{className:"my-4"}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(mi,{placeholder:"Type your reply...",value:i,onChange:te=>o(te.target.value),className:"min-h-[80px]"}),s.jsx(de,{onClick:W,disabled:!i.trim()||z.isPending,className:"self-end",children:s.jsx(Dc,{className:"h-4 w-4"})})]})]})]})]})})):s.jsx(Jr,{children:s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{children:[s.jsx("h1",{className:"text-2xl font-bold",children:"Support Tickets"}),s.jsxs("p",{className:"text-muted-foreground",children:["Manage support requests from agents",V>0&&s.jsxs(ir,{variant:"destructive",className:"ml-2",children:[V," open"]})]})]}),s.jsxs(mn,{open:_,onOpenChange:j,children:[s.jsx(Do,{asChild:!0,children:s.jsxs(de,{variant:"outline",children:[s.jsx(eg,{className:"h-4 w-4 mr-2"}),"Notification Settings"]})}),s.jsxs(pn,{children:[s.jsxs(xn,{children:[s.jsx(gn,{children:"Email Notification Settings"}),s.jsx(fi,{children:"Choose which admins receive email notifications for new support tickets."})]}),s.jsx("div",{className:"space-y-4 mt-4",children:P.map(te=>s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(bf,{className:"h-4 w-4 text-muted-foreground"}),s.jsxs("div",{children:[s.jsx("p",{className:"font-medium",children:te.name}),s.jsx("p",{className:"text-sm text-muted-foreground",children:te.email})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[te.receives_notifications?s.jsx(QR,{className:"h-4 w-4 text-primary"}):s.jsx(H6,{className:"h-4 w-4 text-muted-foreground"}),s.jsx(ri,{checked:te.receives_notifications,onCheckedChange:X=>I.mutate({userId:te.id,enabled:X})})]})]},te.id))})]})]})]}),s.jsxs(go,{defaultValue:"all",className:"w-full",children:[s.jsxs("div",{className:"flex flex-wrap gap-4 items-center",children:[s.jsxs(ao,{children:[s.jsx(Bn,{value:"all",onClick:()=>a("all"),children:"All"}),s.jsx(Bn,{value:"open",onClick:()=>a("open"),children:"Open"}),s.jsx(Bn,{value:"in_progress",onClick:()=>a("in_progress"),children:"In Progress"}),s.jsx(Bn,{value:"resolved",onClick:()=>a("resolved"),children:"Resolved"})]}),s.jsxs(Kn,{value:m,onValueChange:g,children:[s.jsx(qn,{className:"w-[180px]",children:s.jsx(Zn,{placeholder:"All Categories"})}),s.jsxs(Hn,{children:[s.jsx(_r,{value:"all",children:"All Categories"}),s.jsx(_r,{value:"general",children:"General Support"}),s.jsx(_r,{value:"technology",children:"Technology Support"}),s.jsx(_r,{value:"crm",children:"CRM Support"}),s.jsx(_r,{value:"marketing",children:"Marketing Support"})]})]})]}),s.jsx(xs,{value:"all",className:"mt-4",children:C?s.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading tickets..."}):N.length===0?s.jsx(at,{children:s.jsxs(ct,{className:"text-center py-12",children:[s.jsx(lu,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),s.jsx("h3",{className:"text-lg font-medium mb-2",children:"No tickets found"}),s.jsx("p",{className:"text-muted-foreground",children:"No support tickets match the current filters."})]})}):s.jsx("div",{className:"space-y-3",children:N.map(te=>{var ie,he;const X=HP[te.status].icon;return s.jsx(at,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>n(te),children:s.jsx(ct,{className:"p-4",children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("h3",{className:"font-medium truncate",children:te.subject}),s.jsxs("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:[s.jsx(ir,{variant:"outline",className:"text-xs",children:GJ[te.category]}),s.jsxs("span",{className:"text-xs text-muted-foreground",children:[(ie=te.profiles)==null?void 0:ie.name," • ",Vn(new Date(te.created_at),"MMM d, yyyy")]}),te.assigned_to&&s.jsxs(ir,{variant:"secondary",className:"text-xs gap-1",children:[s.jsx(bf,{className:"h-3 w-3"}),((he=P.find(xe=>xe.id===te.assigned_to))==null?void 0:he.name)||"Assigned"]})]})]}),s.jsxs(ir,{className:HP[te.status].color,children:[s.jsx(X,{className:"h-3 w-3 mr-1"}),HP[te.status].label]})]})})},te.id)})})})]})]})})}const g9e=bc.create({name:"color",addOptions(){return{types:["textStyle"]}},addGlobalAttributes(){return[{types:this.options.types,attributes:{color:{default:null,parseHTML:t=>{var e;return(e=t.style.color)===null||e===void 0?void 0:e.replace(/['"]+/g,"")},renderHTML:t=>t.color?{style:`color: ${t.color}`}:{}}}}]},addCommands(){return{setColor:t=>({chain:e})=>e().setMark("textStyle",{color:t}).run(),unsetColor:()=>({chain:t})=>t().setMark("textStyle",{color:null}).removeEmptyTextStyle().run()}}});function y9e({content:t,onChange:e,variables:r}){const n=iye({extensions:[dye,bye.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),wye.configure({types:["heading","paragraph"]}),jye,g9e],content:t,onUpdate:({editor:c})=>{e(c.getHTML())}});D.useEffect(()=>{n&&t!==n.getHTML()&&n.commands.setContent(t)},[t,n]);const i=c=>{n&&n.chain().focus().insertContent(`{{${c.key}}}`).run()},o=()=>{if(!n)return;const c=n.getAttributes("link").href,a=window.prompt("URL",c);if(a!==null){if(a===""){n.chain().focus().extendMarkRange("link").unsetLink().run();return}n.chain().focus().extendMarkRange("link").setLink({href:a}).run()}};return n?s.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-1 p-2 border-b bg-muted/30",children:[s.jsx(de,{type:"button",variant:"ghost",size:"sm",onClick:()=>n.chain().focus().toggleBold().run(),className:n.isActive("bold")?"bg-muted":"",children:s.jsx(aoe,{className:"h-4 w-4"})}),s.jsx(de,{type:"button",variant:"ghost",size:"sm",onClick:()=>n.chain().focus().toggleItalic().run(),className:n.isActive("italic")?"bg-muted":"",children:s.jsx(poe,{className:"h-4 w-4"})}),s.jsx("div",{className:"w-px h-6 bg-border mx-1"}),s.jsx(de,{type:"button",variant:"ghost",size:"sm",onClick:()=>n.chain().focus().toggleBulletList().run(),className:n.isActive("bulletList")?"bg-muted":"",children:s.jsx(Aj,{className:"h-4 w-4"})}),s.jsx(de,{type:"button",variant:"ghost",size:"sm",onClick:()=>n.chain().focus().toggleOrderedList().run(),className:n.isActive("orderedList")?"bg-muted":"",children:s.jsx(yoe,{className:"h-4 w-4"})}),s.jsx("div",{className:"w-px h-6 bg-border mx-1"}),s.jsx(de,{type:"button",variant:"ghost",size:"sm",onClick:()=>n.chain().focus().setTextAlign("left").run(),className:n.isActive({textAlign:"left"})?"bg-muted":"",children:s.jsx(toe,{className:"h-4 w-4"})}),s.jsx(de,{type:"button",variant:"ghost",size:"sm",onClick:()=>n.chain().focus().setTextAlign("center").run(),className:n.isActive({textAlign:"center"})?"bg-muted":"",children:s.jsx(eoe,{className:"h-4 w-4"})}),s.jsx(de,{type:"button",variant:"ghost",size:"sm",onClick:()=>n.chain().focus().setTextAlign("right").run(),className:n.isActive({textAlign:"right"})?"bg-muted":"",children:s.jsx(roe,{className:"h-4 w-4"})}),s.jsx("div",{className:"w-px h-6 bg-border mx-1"}),s.jsx(de,{type:"button",variant:"ghost",size:"sm",onClick:o,className:n.isActive("link")?"bg-muted":"",children:s.jsx(Go,{className:"h-4 w-4"})}),s.jsx(de,{type:"button",variant:"ghost",size:"sm",onClick:()=>n.chain().focus().toggleCodeBlock().run(),className:n.isActive("codeBlock")?"bg-muted":"",children:s.jsx(loe,{className:"h-4 w-4"})}),s.jsx("div",{className:"w-px h-6 bg-border mx-1"}),s.jsx(de,{type:"button",variant:"ghost",size:"sm",onClick:()=>n.chain().focus().undo().run(),disabled:!n.can().undo(),children:s.jsx(Noe,{className:"h-4 w-4"})}),s.jsx(de,{type:"button",variant:"ghost",size:"sm",onClick:()=>n.chain().focus().redo().run(),disabled:!n.can().redo(),children:s.jsx(boe,{className:"h-4 w-4"})}),s.jsx("div",{className:"flex-1"}),r.length>0&&s.jsxs(rg,{children:[s.jsx(ng,{asChild:!0,children:s.jsxs(de,{type:"button",variant:"outline",size:"sm",className:"gap-2",children:[s.jsx(H2e,{className:"h-4 w-4"}),"Insert Variable"]})}),s.jsx(Op,{align:"end",className:"w-64",children:r.map(c=>s.jsxs(Ro,{onClick:()=>i(c),className:"flex flex-col items-start",children:[s.jsx("span",{className:"font-medium",children:c.label}),s.jsx("span",{className:"text-xs text-muted-foreground font-mono",children:`{{${c.key}}}`}),c.description&&s.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:c.description})]},c.key))})]})]}),s.jsx(nye,{editor:n,className:"prose prose-sm max-w-none p-4 min-h-[300px] focus:outline-none [&_.ProseMirror]:outline-none [&_.ProseMirror]:min-h-[280px]"}),r.length>0&&s.jsxs("div",{className:"border-t p-3 bg-muted/20",children:[s.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Available variables (click to copy):"}),s.jsx("div",{className:"flex flex-wrap gap-2",children:r.map(c=>s.jsx(ir,{variant:"secondary",className:"cursor-pointer hover:bg-secondary/80 font-mono text-xs",onClick:()=>{navigator.clipboard.writeText(`{{${c.key}}}`)},children:`{{${c.key}}}`},c.key))})]})]}):null}function x9e(){const t=Wn(),[e,r]=D.useState(null),[n,i]=D.useState(null),[o,c]=D.useState(""),[a,m]=D.useState(""),[g,_]=D.useState(""),[j,N]=D.useState(!0),[C,P]=D.useState("visual"),{data:A,isLoading:I}=Sr({queryKey:["email-templates"],queryFn:async()=>{const{data:V,error:K}=await ae.from("email_templates").select("*").order("name");if(K)throw K;return V.map(Q=>({...Q,available_variables:Q.available_variables||[]}))}}),O=zr({mutationFn:async V=>{const{error:K}=await ae.from("email_templates").update({subject:V.subject,body_html:V.body_html,description:V.description,is_active:V.is_active}).eq("id",V.id);if(K)throw K},onSuccess:()=>{t.invalidateQueries({queryKey:["email-templates"]}),Dt.success("Email template updated successfully"),r(null)},onError:V=>{Dt.error("Failed to update template: "+V.message)}}),R=V=>{r(V),c(V.subject),m(V.body_html),_(V.description||""),N(V.is_active),P("visual")},z=()=>{e&&O.mutate({id:e.id,subject:o,body_html:a,description:g,is_active:j})},W=(V,K)=>{let Q=V;return K.forEach(te=>{const X=`{{${te.key}}}`,ie=`[${te.label}]`;Q=Q.replace(new RegExp(X.replace(/[{}]/g,"\\$&"),"g"),ie)}),Q};return e?s.jsxs(Jr,{title:"Edit Email Template",children:[s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"flex items-center gap-4",children:[s.jsxs(de,{variant:"ghost",onClick:()=>r(null),children:[s.jsx(Ka,{className:"h-4 w-4 mr-2"}),"Back to Templates"]}),s.jsx("div",{className:"flex-1"}),s.jsxs(de,{variant:"outline",onClick:()=>i(e),children:[s.jsx(Rc,{className:"h-4 w-4 mr-2"}),"Preview"]}),s.jsxs(de,{onClick:z,disabled:O.isPending,children:[s.jsx(K2,{className:"h-4 w-4 mr-2"}),O.isPending?"Saving...":"Save Changes"]})]}),s.jsxs(at,{children:[s.jsx(xr,{children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsxs(wr,{className:"flex items-center gap-2",children:[s.jsx(Fo,{className:"h-5 w-5"}),e.name]}),s.jsxs(us,{className:"mt-1",children:["Template slug: ",s.jsx("code",{className:"bg-muted px-1 rounded",children:e.slug})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(mt,{htmlFor:"active-toggle",children:"Active"}),s.jsx(ri,{id:"active-toggle",checked:j,onCheckedChange:N})]})]})}),s.jsxs(ct,{className:"space-y-6",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"description",children:"Description"}),s.jsx(mi,{id:"description",value:g,onChange:V=>_(V.target.value),placeholder:"Brief description of when this email is sent",rows:2})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"subject",children:"Email Subject"}),s.jsx(Et,{id:"subject",value:o,onChange:V=>c(V.target.value),placeholder:"Email subject line"}),s.jsxs("p",{className:"text-xs text-muted-foreground",children:["You can use variables like ","{{name}}"," in the subject"]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx(mt,{children:"Email Body"}),s.jsx(go,{value:C,onValueChange:V=>P(V),children:s.jsxs(ao,{className:"h-8",children:[s.jsxs(Bn,{value:"visual",className:"text-xs px-3 h-6",children:[s.jsx(voe,{className:"h-3 w-3 mr-1"}),"Visual"]}),s.jsxs(Bn,{value:"html",className:"text-xs px-3 h-6",children:[s.jsx(loe,{className:"h-3 w-3 mr-1"}),"HTML"]})]})})]}),C==="visual"?s.jsx(y9e,{content:a,onChange:m,variables:e.available_variables}):s.jsx(mi,{value:a,onChange:V=>m(V.target.value),className:"font-mono text-sm min-h-[400px]",placeholder:"HTML email body"})]})]})]})]}),s.jsx(mn,{open:!!n,onOpenChange:()=>i(null),children:s.jsxs(pn,{className:"max-w-3xl max-h-[90vh] overflow-auto",children:[s.jsxs(xn,{children:[s.jsx(gn,{children:"Email Preview"}),s.jsxs(fi,{children:["Subject: ",o.replace(/\{\{(\w+)\}\}/g,"[$1]")]})]}),s.jsx("div",{className:"border rounded-lg p-4 bg-white",children:s.jsx("div",{dangerouslySetInnerHTML:{__html:W(a,e.available_variables)}})})]})})]}):s.jsx(Jr,{title:"Email Templates",children:s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{children:[s.jsx("h1",{className:"text-2xl font-bold",children:"Email Templates"}),s.jsx("p",{className:"text-muted-foreground mt-1",children:"Manage and customize system email templates"})]}),I?s.jsx("div",{className:"grid gap-4",children:[...Array(4)].map((V,K)=>s.jsx(at,{children:s.jsxs(xr,{children:[s.jsx(Dn,{className:"h-5 w-48"}),s.jsx(Dn,{className:"h-4 w-96"})]})},K))}):s.jsx("div",{className:"grid gap-4",children:A==null?void 0:A.map(V=>s.jsxs(at,{className:"hover:shadow-md transition-shadow",children:[s.jsx(xr,{children:s.jsxs("div",{className:"flex items-start justify-between",children:[s.jsxs("div",{className:"space-y-1",children:[s.jsxs(wr,{className:"flex items-center gap-2 text-lg",children:[s.jsx(Fo,{className:"h-5 w-5 text-muted-foreground"}),V.name,!V.is_active&&s.jsx(ir,{variant:"secondary",children:"Inactive"})]}),s.jsx(us,{children:V.description})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs(de,{variant:"outline",size:"sm",onClick:()=>i(V),children:[s.jsx(Rc,{className:"h-4 w-4 mr-2"}),"Preview"]}),s.jsxs(de,{size:"sm",onClick:()=>R(V),children:[s.jsx(P_,{className:"h-4 w-4 mr-2"}),"Edit"]})]})]})}),s.jsx(ct,{children:s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[s.jsx("span",{className:"text-muted-foreground",children:"Subject:"}),s.jsx("code",{className:"bg-muted px-2 py-0.5 rounded text-sm",children:V.subject})]}),s.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[s.jsx("span",{className:"text-muted-foreground",children:"Variables:"}),s.jsx("div",{className:"flex flex-wrap gap-1",children:V.available_variables.map(K=>s.jsx(ir,{variant:"outline",className:"font-mono text-xs",children:`{{${K.key}}}`},K.key))})]})]})})]},V.id))}),s.jsx(mn,{open:!!n&&!e,onOpenChange:()=>i(null),children:s.jsxs(pn,{className:"max-w-3xl max-h-[90vh] overflow-auto",children:[s.jsxs(xn,{children:[s.jsxs(gn,{children:["Email Preview: ",n==null?void 0:n.name]}),s.jsxs(fi,{children:["Subject: ",n==null?void 0:n.subject.replace(/\{\{(\w+)\}\}/g,"[$1]")]})]}),n&&s.jsx("div",{className:"border rounded-lg p-4 bg-white",children:s.jsx("div",{dangerouslySetInnerHTML:{__html:W(n.body_html,n.available_variables)}})})]})})]})})}const v9e=({brokerageId:t})=>{const{toast:e}=Ri(),[r,n]=D.useState([]),[i,o]=D.useState(!0),[c,a]=D.useState(""),[m,g]=D.useState(!1),[_,j]=D.useState(!1),[N,C]=D.useState({email:"",name:"",password:""}),[P,A]=D.useState(!1),[I,O]=D.useState(null),[R,z]=D.useState(!1),[W,V]=D.useState(!1),[K,Q]=D.useState(!1),[te,X]=D.useState(""),[ie,he]=D.useState(!1),[xe,pe]=D.useState([]);D.useEffect(()=>{ge(),ve()},[t]);const ve=async()=>{try{const{data:nt,error:Qt}=await ae.from("user_roles").select("user_id, profiles!inner(brokerage_id)").eq("role","brokerage_manager").eq("profiles.brokerage_id",t);if(Qt)throw Qt;pe((nt==null?void 0:nt.map(gt=>gt.user_id))||[])}catch(nt){console.error("Error loading brokerage managers:",nt)}},ge=async()=>{try{o(!0);const{data:nt,error:Qt}=await ae.functions.invoke("get-brokerage-agents",{body:{brokerageId:t}});if(Qt)throw Qt;n(nt.agents||[])}catch(nt){console.error("Error loading agents:",nt),e({title:"Error",description:"Failed to load agents",variant:"destructive"})}finally{o(!1)}},ke=async()=>{if(!N.email||!N.name||!N.password){e({title:"Error",description:"Please fill in all fields",variant:"destructive"});return}j(!0);try{const{data:{session:nt}}=await ae.auth.getSession(),Qt=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${nt==null?void 0:nt.access_token}`},body:JSON.stringify({...N,brokerageId:t})}),gt=await Qt.json();if(!Qt.ok)throw new Error(gt.error||"Failed to create agent");e({title:"Success",description:`Agent ${N.email} created successfully`}),C({email:"",name:"",password:""}),g(!1),ge()}catch(nt){console.error("Error creating agent:",nt),e({title:"Error",description:nt.message||"Failed to create agent",variant:"destructive"})}finally{j(!1)}},Ce=async nt=>{try{const{data:{session:Qt}}=await ae.auth.getSession(),gt=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Qt==null?void 0:Qt.access_token}`},body:JSON.stringify({userId:nt})}),Me=await gt.json();if(!gt.ok)throw new Error(Me.error||"Failed to resend welcome email");e({title:"Success",description:"Welcome email sent successfully"})}catch(Qt){console.error("Error resending welcome email:",Qt),e({title:"Error",description:Qt.message||"Failed to resend welcome email",variant:"destructive"})}},Se=nt=>{O(nt),A(!0)},je=async()=>{if(!te){e({title:"Error",description:"Please select an agent to promote",variant:"destructive"});return}he(!0);try{const{data:{session:nt}}=await ae.auth.getSession(),Qt=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${nt==null?void 0:nt.access_token}`},body:JSON.stringify({userId:te,role:"brokerage_manager",action:"add"})}),gt=await Qt.json();if(!Qt.ok)throw new Error(gt.error||"Failed to add brokerage manager");e({title:"Success",description:"Brokerage manager added successfully"}),Q(!1),X(""),ve()}catch(nt){console.error("Error adding brokerage manager:",nt),e({title:"Error",description:nt.message||"Failed to add brokerage manager",variant:"destructive"})}finally{he(!1)}},et=async nt=>{try{const{data:{session:Qt}}=await ae.auth.getSession(),gt=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Qt==null?void 0:Qt.access_token}`},body:JSON.stringify({userId:nt,role:"brokerage_manager",action:"remove"})}),Me=await gt.json();if(!gt.ok)throw new Error(Me.error||"Failed to remove brokerage manager");e({title:"Success",description:"Brokerage manager role removed"}),ve()}catch(Qt){console.error("Error removing brokerage manager:",Qt),e({title:"Error",description:Qt.message||"Failed to remove brokerage manager",variant:"destructive"})}},bt=nt=>xe.includes(nt),_e=async()=>{if(I){z(!0);try{const{data:{session:nt}}=await ae.auth.getSession(),Qt=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/remove-agent",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${nt==null?void 0:nt.access_token}`},body:JSON.stringify({userId:I.id,brokerageId:t})}),gt=await Qt.json();if(!Qt.ok)throw new Error(gt.error||"Failed to remove agent");e({title:"Success",description:`${I.name} has been removed from your brokerage`}),A(!1),O(null),ge()}catch(nt){console.error("Error removing agent:",nt),e({title:"Error",description:nt.message||"Failed to remove agent",variant:"destructive"})}finally{z(!1)}}},Ye=r.filter(nt=>{if(!c)return!0;const Qt=c.toLowerCase();return nt.name.toLowerCase().includes(Qt)||nt.email.toLowerCase().includes(Qt)}),pt=Ye.filter(nt=>nt.claimed&&!bt(nt.id));return i?s.jsx(at,{children:s.jsx(ct,{className:"flex items-center justify-center py-8",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):s.jsxs(s.Fragment,{children:[s.jsxs(at,{children:[s.jsx(xr,{children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx(wr,{children:"Agents"}),s.jsx(us,{children:"Manage your brokerage's agents"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs(de,{variant:"outline",onClick:()=>Q(!0),children:[s.jsx(n2,{className:"mr-2 h-4 w-4"}),"Add Brokerage Manager"]}),s.jsxs(de,{variant:"outline",onClick:()=>V(!0),children:[s.jsx(JR,{className:"mr-2 h-4 w-4"}),"Import CSV"]}),s.jsxs(de,{onClick:()=>g(!0),children:[s.jsx(yM,{className:"mr-2 h-4 w-4"}),"Add Agent"]})]})]})}),s.jsxs(ct,{children:[s.jsx("div",{className:"mb-4",children:s.jsxs("div",{className:"relative",children:[s.jsx(ba,{className:"absolute left-3 top-3 h-4 w-4 text-muted-foreground"}),s.jsx(Et,{placeholder:"Search agents...",value:c,onChange:nt=>a(nt.target.value),className:"pl-9"})]})}),s.jsx("div",{className:"rounded-md border",children:s.jsxs(ni,{children:[s.jsx(si,{children:s.jsxs(Dr,{children:[s.jsx(Nt,{children:"Name"}),s.jsx(Nt,{children:"Email"}),s.jsx(Nt,{children:"Status"}),s.jsx(Nt,{children:"Tags"}),s.jsx(Nt,{children:"Actions"})]})}),s.jsx(ii,{children:Ye.length===0?s.jsx(Dr,{children:s.jsx(xt,{colSpan:5,className:"text-center text-muted-foreground",children:"No agents found"})}):Ye.map(nt=>s.jsxs(Dr,{children:[s.jsx(xt,{className:"font-medium",children:nt.name}),s.jsx(xt,{children:nt.email}),s.jsx(xt,{children:s.jsxs("div",{className:"flex items-center gap-2",children:[nt.claimed?s.jsx(ir,{variant:"default",children:"Active"}):s.jsx(ir,{variant:"secondary",children:"Pending"}),bt(nt.id)&&s.jsxs(ir,{variant:"outline",className:"border-primary text-primary",children:[s.jsx(U2e,{className:"mr-1 h-3 w-3"}),"Manager"]})]})}),s.jsx(xt,{children:s.jsx("div",{className:"flex flex-wrap gap-1",children:nt.tags.map(Qt=>s.jsx(ir,{variant:"outline",children:Qt},Qt))})}),s.jsx(xt,{children:s.jsxs("div",{className:"flex items-center gap-2",children:[!nt.claimed&&s.jsx(de,{size:"sm",variant:"ghost",onClick:()=>Ce(nt.id),title:"Resend welcome email",children:s.jsx(Fo,{className:"h-4 w-4"})}),bt(nt.id)&&s.jsx(de,{size:"sm",variant:"ghost",onClick:()=>et(nt.id),title:"Remove manager role",className:"text-orange-500 hover:text-orange-600",children:s.jsx(n2,{className:"h-4 w-4"})}),s.jsx(de,{size:"sm",variant:"ghost",onClick:()=>Se(nt),className:"text-destructive hover:text-destructive",title:"Remove agent",children:s.jsx(oi,{className:"h-4 w-4"})})]})})]},nt.id))})]})})]})]}),s.jsx(mn,{open:m,onOpenChange:g,children:s.jsxs(pn,{children:[s.jsxs(xn,{children:[s.jsx(gn,{children:"Add New Agent"}),s.jsx(fi,{children:"Create a new agent account. They'll receive an email to set up their account."})]}),s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"name",children:"Name"}),s.jsx(Et,{id:"name",value:N.name,onChange:nt=>C({...N,name:nt.target.value}),placeholder:"John Doe"})]}),s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"email",children:"Email"}),s.jsx(Et,{id:"email",type:"email",value:N.email,onChange:nt=>C({...N,email:nt.target.value}),placeholder:"john@example.com"})]}),s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"password",children:"Temporary Password"}),s.jsx(Et,{id:"password",type:"password",value:N.password,onChange:nt=>C({...N,password:nt.target.value}),placeholder:"Temporary password"})]})]}),s.jsxs(zi,{children:[s.jsx(de,{variant:"outline",onClick:()=>g(!1),children:"Cancel"}),s.jsx(de,{onClick:ke,disabled:_,children:_?"Creating...":"Create Agent"})]})]})}),s.jsx(mn,{open:P,onOpenChange:A,children:s.jsxs(pn,{children:[s.jsxs(xn,{children:[s.jsx(gn,{children:"Remove Agent"}),s.jsxs(fi,{children:["Are you sure you want to remove ",s.jsx("strong",{children:I==null?void 0:I.name})," from your brokerage? This will revoke their access to the dashboard."]})]}),s.jsxs(zi,{children:[s.jsx(de,{variant:"outline",onClick:()=>A(!1),children:"Cancel"}),s.jsx(de,{variant:"destructive",onClick:_e,disabled:R,children:R?"Removing...":"Remove Agent"})]})]})}),s.jsx(gme,{open:W,onOpenChange:V,fixedBrokerageId:t,onSuccess:ge}),s.jsx(mn,{open:K,onOpenChange:Q,children:s.jsxs(pn,{children:[s.jsxs(xn,{children:[s.jsx(gn,{children:"Add Brokerage Manager"}),s.jsx(fi,{children:"Promote an existing active agent to brokerage manager. They will be able to manage agents and view analytics."})]}),s.jsx("div",{className:"space-y-4",children:s.jsxs("div",{children:[s.jsx(mt,{children:"Select Agent"}),s.jsxs(Kn,{value:te,onValueChange:X,children:[s.jsx(qn,{children:s.jsx(Zn,{placeholder:"Select an agent to promote..."})}),s.jsx(Hn,{children:pt.length===0?s.jsx(_r,{value:"none",disabled:!0,children:"No eligible agents found"}):pt.map(nt=>s.jsxs(_r,{value:nt.id,children:[nt.name," (",nt.email,")"]},nt.id))})]}),pt.length===0&&s.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"All active agents are already brokerage managers, or there are no active agents yet."})]})}),s.jsxs(zi,{children:[s.jsx(de,{variant:"outline",onClick:()=>Q(!1),children:"Cancel"}),s.jsx(de,{onClick:je,disabled:ie||!te,children:ie?"Adding...":"Add as Manager"})]})]})})]})},_9e={academy_video:"Academy Video",template:"Template",toolbox:"Toolbox Resource",newsletter:"Newsletter",social_swag:"Social Swag",event:"Event"},b9e={view:"Viewed",click_canva:"Opened Canva",click_pdf:"Downloaded PDF",click_video:"Watched Video",click_link:"Clicked Link",register:"Registered"},w9e=t=>{switch(t){case"academy_video":return s.jsx(Ia,{className:"h-4 w-4"});case"template":return s.jsx(Ii,{className:"h-4 w-4"});case"toolbox":return s.jsx(Ii,{className:"h-4 w-4"});case"newsletter":return s.jsx(gT,{className:"h-4 w-4"});case"social_swag":return s.jsx(cu,{className:"h-4 w-4"});case"event":return s.jsx(ko,{className:"h-4 w-4"});default:return s.jsx(oa,{className:"h-4 w-4"})}},j9e=({brokerageId:t})=>{const{toast:e}=Ri(),[r,n]=D.useState([]),[i,o]=D.useState([]),[c,a]=D.useState([]),[m,g]=D.useState(!0),[_,j]=D.useState(null);D.useEffect(()=>{N()},[t]);const N=async()=>{try{g(!0);const{data:A,error:I}=await ae.from("profiles").select("id, name, email").eq("brokerage_id",t);if(I)throw I;const O=A.map(he=>he.id),R=new Map(A.map(he=>[he.id,he]));if(O.length===0){n([]),o([]),a([]);return}const{data:z,error:W}=await ae.from("activity_logs").select("*").in("user_id",O).order("launched_at",{ascending:!1});if(W)throw W;const V=z.map(he=>{var xe,pe;return{id:he.id,user_id:he.user_id,app_name:he.app_name,launched_at:he.launched_at,user_name:((xe=R.get(he.user_id))==null?void 0:xe.name)||"Unknown",user_email:((pe=R.get(he.user_id))==null?void 0:pe.email)||"Unknown"}});n(V);const{data:K,error:Q}=await ae.from("content_engagement_logs").select("*").in("user_id",O).order("created_at",{ascending:!1});if(Q)throw Q;const te=(K||[]).map(he=>{var xe,pe;return{id:he.id,user_id:he.user_id,resource_type:he.resource_type,resource_id:he.resource_id,resource_title:he.resource_title,action_type:he.action_type,created_at:he.created_at,user_name:((xe=R.get(he.user_id))==null?void 0:xe.name)||"Unknown",user_email:((pe=R.get(he.user_id))==null?void 0:pe.email)||"Unknown"}});o(te);const X=new Map;A.forEach(he=>{X.set(he.id,{user_id:he.id,user_name:he.name,user_email:he.email,app_launches:0,content_views:0,last_activity:""})}),V.forEach(he=>{const xe=X.get(he.user_id);xe&&(xe.app_launches++,(!xe.last_activity||new Date(he.launched_at)>new Date(xe.last_activity))&&(xe.last_activity=he.launched_at))}),te.forEach(he=>{const xe=X.get(he.user_id);xe&&(xe.content_views++,(!xe.last_activity||new Date(he.created_at)>new Date(xe.last_activity))&&(xe.last_activity=he.created_at))});const ie=Array.from(X.values()).filter(he=>he.app_launches>0||he.content_views>0).sort((he,xe)=>new Date(xe.last_activity).getTime()-new Date(he.last_activity).getTime());a(ie)}catch(A){console.error("Error loading activity:",A),e({title:"Error",description:"Failed to load activity logs",variant:"destructive"})}finally{g(!1)}},C=A=>r.filter(I=>I.user_id===A),P=A=>i.filter(I=>I.user_id===A);return m?s.jsx(at,{children:s.jsx(ct,{className:"flex items-center justify-center py-8",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):s.jsxs(s.Fragment,{children:[s.jsxs(at,{children:[s.jsxs(xr,{children:[s.jsx(wr,{children:"Agent Activity"}),s.jsx(us,{children:"Track app usage and content engagement - click an agent for details"})]}),s.jsx(ct,{children:s.jsx("div",{className:"rounded-md border",children:s.jsxs(ni,{children:[s.jsx(si,{children:s.jsxs(Dr,{children:[s.jsx(Nt,{children:"Agent"}),s.jsx(Nt,{className:"text-center",children:"App Launches"}),s.jsx(Nt,{className:"text-center",children:"Content Views"}),s.jsx(Nt,{children:"Last Active"})]})}),s.jsx(ii,{children:c.length===0?s.jsx(Dr,{children:s.jsx(xt,{colSpan:4,className:"text-center text-muted-foreground",children:"No activity yet"})}):c.map(A=>s.jsxs(Dr,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>j({id:A.user_id,name:A.user_name,email:A.user_email}),children:[s.jsx(xt,{children:s.jsxs("div",{children:[s.jsx("div",{className:"font-medium",children:A.user_name}),s.jsx("div",{className:"text-sm text-muted-foreground",children:A.user_email})]})}),s.jsx(xt,{className:"text-center",children:s.jsxs(ir,{variant:"outline",className:"gap-1",children:[s.jsx(Sf,{className:"h-3 w-3"}),A.app_launches]})}),s.jsx(xt,{className:"text-center",children:s.jsxs(ir,{variant:"secondary",className:"gap-1",children:[s.jsx(Ii,{className:"h-3 w-3"}),A.content_views]})}),s.jsx(xt,{className:"text-sm text-muted-foreground",children:A.last_activity&&Bu(new Date(A.last_activity),{addSuffix:!0})})]},A.user_id))})]})})})]}),s.jsx(mn,{open:!!_,onOpenChange:A=>!A&&j(null),children:s.jsxs(pn,{className:"max-w-3xl max-h-[80vh] overflow-hidden flex flex-col",children:[s.jsxs(xn,{children:[s.jsxs(gn,{children:[_==null?void 0:_.name,"'s Activity"]}),s.jsx(fi,{children:_==null?void 0:_.email})]}),s.jsxs(go,{defaultValue:"content",className:"flex-1 overflow-hidden flex flex-col",children:[s.jsxs(ao,{className:"grid w-full grid-cols-2",children:[s.jsx(Bn,{value:"content",children:"Content Engagement"}),s.jsx(Bn,{value:"apps",children:"App Launches"})]}),s.jsx(xs,{value:"content",className:"flex-1 overflow-auto",children:s.jsx("div",{className:"rounded-md border",children:s.jsxs(ni,{children:[s.jsx(si,{children:s.jsxs(Dr,{children:[s.jsx(Nt,{children:"Resource"}),s.jsx(Nt,{children:"Type"}),s.jsx(Nt,{children:"Action"}),s.jsx(Nt,{children:"Time"})]})}),s.jsx(ii,{children:_&&P(_.id).length===0?s.jsx(Dr,{children:s.jsx(xt,{colSpan:4,className:"text-center text-muted-foreground",children:"No content engagement yet"})}):_&&P(_.id).map(A=>s.jsxs(Dr,{children:[s.jsx(xt,{className:"max-w-[200px] truncate font-medium",children:A.resource_title}),s.jsx(xt,{children:s.jsxs(ir,{variant:"outline",className:"gap-1",children:[w9e(A.resource_type),_9e[A.resource_type]||A.resource_type]})}),s.jsx(xt,{children:s.jsx("span",{className:"text-sm text-muted-foreground",children:b9e[A.action_type]||A.action_type})}),s.jsx(xt,{className:"text-sm text-muted-foreground",children:Bu(new Date(A.created_at),{addSuffix:!0})})]},A.id))})]})})}),s.jsx(xs,{value:"apps",className:"flex-1 overflow-auto",children:s.jsx("div",{className:"rounded-md border",children:s.jsxs(ni,{children:[s.jsx(si,{children:s.jsxs(Dr,{children:[s.jsx(Nt,{children:"App"}),s.jsx(Nt,{children:"Time"})]})}),s.jsx(ii,{children:_&&C(_.id).length===0?s.jsx(Dr,{children:s.jsx(xt,{colSpan:2,className:"text-center text-muted-foreground",children:"No app launches yet"})}):_&&C(_.id).map(A=>s.jsxs(Dr,{children:[s.jsx(xt,{children:s.jsx(ir,{variant:"outline",children:A.app_name})}),s.jsx(xt,{className:"text-sm text-muted-foreground",children:Bu(new Date(A.launched_at),{addSuffix:!0})})]},A.id))})]})})})]})]})})]})},S9e=({brokerageId:t})=>{const{toast:e}=Ri(),[r,n]=D.useState({totalAgents:0,activeAgents:0,pendingAgents:0,totalLaunches:0,launchesThisWeek:0,launchesThisMonth:0}),[i,o]=D.useState(!0);D.useEffect(()=>{c()},[t]);const c=async()=>{try{o(!0);const{data:a,error:m}=await ae.from("profiles").select("id").eq("brokerage_id",t);if(m)throw m;const g=a.map(V=>V.id),_=g.length;if(g.length===0){o(!1);return}const{data:j,error:N}=await ae.from("profiles").select("id, email").in("id",g);if(N)throw N;const{count:C}=await ae.from("profiles").select("*",{count:"exact",head:!0}).eq("brokerage_id",t).not("last_login","is",null),P=C||0,A=_-P,{count:I}=await ae.from("activity_logs").select("*",{count:"exact",head:!0}).in("user_id",g),O=new Date;O.setDate(O.getDate()-7);const{count:R}=await ae.from("activity_logs").select("*",{count:"exact",head:!0}).in("user_id",g).gte("launched_at",O.toISOString()),z=new Date;z.setMonth(z.getMonth()-1);const{count:W}=await ae.from("activity_logs").select("*",{count:"exact",head:!0}).in("user_id",g).gte("launched_at",z.toISOString());n({totalAgents:_,activeAgents:P,pendingAgents:A,totalLaunches:I||0,launchesThisWeek:R||0,launchesThisMonth:W||0})}catch(a){console.error("Error loading analytics:",a),e({title:"Error",description:"Failed to load analytics",variant:"destructive"})}finally{o(!1)}};return i?s.jsx(at,{children:s.jsx(ct,{className:"flex items-center justify-center py-8",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):s.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[s.jsxs(at,{children:[s.jsxs(xr,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[s.jsx(wr,{className:"text-sm font-medium",children:"Total Agents"}),s.jsx(_i,{className:"h-4 w-4 text-muted-foreground"})]}),s.jsxs(ct,{children:[s.jsx("div",{className:"text-2xl font-bold",children:r.totalAgents}),s.jsxs("p",{className:"text-xs text-muted-foreground",children:[r.activeAgents," active, ",r.pendingAgents," pending"]})]})]}),s.jsxs(at,{children:[s.jsxs(xr,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[s.jsx(wr,{className:"text-sm font-medium",children:"Active Agents"}),s.jsx(gc,{className:"h-4 w-4 text-muted-foreground"})]}),s.jsxs(ct,{children:[s.jsx("div",{className:"text-2xl font-bold",children:r.activeAgents}),s.jsx("p",{className:"text-xs text-muted-foreground",children:r.totalAgents>0?`${Math.round(r.activeAgents/r.totalAgents*100)}% of total`:"0% of total"})]})]}),s.jsxs(at,{children:[s.jsxs(xr,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[s.jsx(wr,{className:"text-sm font-medium",children:"Pending Invites"}),s.jsx(No,{className:"h-4 w-4 text-muted-foreground"})]}),s.jsxs(ct,{children:[s.jsx("div",{className:"text-2xl font-bold",children:r.pendingAgents}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Awaiting setup"})]})]}),s.jsxs(at,{children:[s.jsxs(xr,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[s.jsx(wr,{className:"text-sm font-medium",children:"Total App Launches"}),s.jsx(Qw,{className:"h-4 w-4 text-muted-foreground"})]}),s.jsxs(ct,{children:[s.jsx("div",{className:"text-2xl font-bold",children:r.totalLaunches}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"All time"})]})]}),s.jsxs(at,{children:[s.jsxs(xr,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[s.jsx(wr,{className:"text-sm font-medium",children:"This Week"}),s.jsx(Qw,{className:"h-4 w-4 text-muted-foreground"})]}),s.jsxs(ct,{children:[s.jsx("div",{className:"text-2xl font-bold",children:r.launchesThisWeek}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Last 7 days"})]})]}),s.jsxs(at,{children:[s.jsxs(xr,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[s.jsx(wr,{className:"text-sm font-medium",children:"This Month"}),s.jsx(Qw,{className:"h-4 w-4 text-muted-foreground"})]}),s.jsxs(ct,{children:[s.jsx("div",{className:"text-2xl font-bold",children:r.launchesThisMonth}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Last 30 days"})]})]})]})},N9e=({brokerageId:t})=>{const[e,r]=D.useState([]),[n,i]=D.useState(!0),[o,c]=D.useState(!1),[a,m]=D.useState(!1),[g,_]=D.useState({description:"",maxUses:""});D.useEffect(()=>{j()},[t]);const j=async()=>{try{const{data:O,error:R}=await ae.from("invite_codes").select("*").eq("brokerage_id",t).order("created_at",{ascending:!1});if(R)throw R;r(O||[])}catch(O){console.error("Error loading invite codes:",O),Dt.error("Failed to load invite links")}finally{i(!1)}},N=()=>Math.random().toString(36).substring(2,8).toUpperCase(),C=async()=>{c(!0);try{const O=N(),{error:R}=await ae.from("invite_codes").insert({code:O,description:g.description||null,max_uses:g.maxUses?parseInt(g.maxUses):null,brokerage_id:t,is_active:!0});if(R)throw R;Dt.success("Invite link created!"),m(!1),_({description:"",maxUses:""}),j()}catch(O){console.error("Error creating invite code:",O),Dt.error("Failed to create invite link")}finally{c(!1)}},P=async O=>{try{const{error:R}=await ae.from("invite_codes").delete().eq("id",O);if(R)throw R;Dt.success("Invite link deleted"),r(e.filter(z=>z.id!==O))}catch(R){console.error("Error deleting invite code:",R),Dt.error("Failed to delete invite link")}},A=async(O,R)=>{try{const{error:z}=await ae.from("invite_codes").update({is_active:!R}).eq("id",O);if(z)throw z;r(e.map(W=>W.id===O?{...W,is_active:!R}:W)),Dt.success(`Invite link ${R?"deactivated":"activated"}`)}catch(z){console.error("Error toggling invite code:",z),Dt.error("Failed to update invite link")}},I=O=>{const R=`${window.location.origin}/join?code=${O}`;navigator.clipboard.writeText(R),Dt.success("Link copied to clipboard!")};return n?s.jsx(at,{children:s.jsx(ct,{className:"flex items-center justify-center py-8",children:s.jsx(Ps,{className:"h-6 w-6 animate-spin text-muted-foreground"})})}):s.jsxs(at,{children:[s.jsxs(xr,{className:"flex flex-row items-center justify-between",children:[s.jsxs("div",{children:[s.jsxs(wr,{className:"flex items-center gap-2",children:[s.jsx(Go,{className:"h-5 w-5"}),"Agent Invite Links"]}),s.jsx(us,{children:"Create shareable links for agents to join your brokerage"})]}),s.jsxs(mn,{open:a,onOpenChange:m,children:[s.jsx(Do,{asChild:!0,children:s.jsxs(de,{size:"sm",children:[s.jsx(Qn,{className:"mr-2 h-4 w-4"}),"Create Link"]})}),s.jsxs(pn,{children:[s.jsxs(xn,{children:[s.jsx(gn,{children:"Create Invite Link"}),s.jsx(fi,{children:"Create a new invite link for agents to join your brokerage"})]}),s.jsxs("div",{className:"space-y-4 py-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"description",children:"Description (optional)"}),s.jsx(Et,{id:"description",placeholder:"e.g., New agent recruiting campaign",value:g.description,onChange:O=>_({...g,description:O.target.value})})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"maxUses",children:"Max Uses (optional)"}),s.jsx(Et,{id:"maxUses",type:"number",placeholder:"Leave empty for unlimited",value:g.maxUses,onChange:O=>_({...g,maxUses:O.target.value})})]}),s.jsx(de,{onClick:C,disabled:o,className:"w-full",children:o?s.jsxs(s.Fragment,{children:[s.jsx(Ps,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):"Create Invite Link"})]})]})]})]}),s.jsx(ct,{children:e.length===0?s.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[s.jsx(Go,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),s.jsx("p",{children:"No invite links yet"}),s.jsx("p",{className:"text-sm",children:"Create one to start inviting agents"})]}):s.jsx("div",{className:"space-y-3",children:e.map(O=>s.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border bg-card",children:[s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("code",{className:"text-sm font-mono bg-muted px-2 py-0.5 rounded",children:O.code}),s.jsx(ir,{variant:O.is_active?"default":"secondary",children:O.is_active?"Active":"Inactive"})]}),O.description&&s.jsx("p",{className:"text-sm text-muted-foreground mt-1 truncate",children:O.description}),s.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[O.uses_count," uses",O.max_uses&&` / ${O.max_uses} max`]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(de,{variant:"ghost",size:"sm",onClick:()=>I(O.code),title:"Copy link",children:s.jsx(ix,{className:"h-4 w-4"})}),s.jsx(de,{variant:"ghost",size:"sm",onClick:()=>A(O.id,O.is_active),title:O.is_active?"Deactivate":"Activate",children:O.is_active?"Disable":"Enable"}),s.jsx(de,{variant:"ghost",size:"sm",onClick:()=>P(O.id),className:"text-destructive hover:text-destructive",title:"Delete",children:s.jsx(oi,{className:"h-4 w-4"})})]})]},O.id))})})]})},C9e=()=>{const{brokerageId:t}=rn(),[e,r]=D.useState(null),[n,i]=D.useState([]),[o,c]=D.useState(!0);D.useEffect(()=>{t&&a()},[t]);const a=async()=>{try{const{data:N}=await ae.from("referral_codes").select("code").eq("brokerage_id",t).single();if(N)r(N.code);else{const P=`REF${t==null?void 0:t.slice(0,8).toUpperCase()}`;await ae.from("referral_codes").insert({brokerage_id:t,code:P}),r(P)}const{data:C}=await ae.from("referrals").select(` *, referred_user:profiles!referred_user_id(name, email), referred_brokerage:brokerages!referred_brokerage_id(name) `).eq("referrer_brokerage_id",t).order("created_at",{ascending:!1});i(C||[])}catch(N){console.error("Error fetching referral data:",N)}finally{c(!1)}},m=()=>{const N=`https://dashboard.relevelup.com/?ref=${e}`;navigator.clipboard.writeText(N),Dt.success("Referral link copied to clipboard!")},g=n.filter(N=>N.status==="qualified").length,_=n.filter(N=>N.status==="pending").length,j=g*25;return o?null:s.jsxs(at,{children:[s.jsxs(xr,{children:[s.jsxs(wr,{className:"flex items-center gap-2",children:[s.jsx(_i,{className:"h-5 w-5"}),"Referral Program"]}),s.jsx(us,{children:"Refer other brokerage managers and save $25/month per qualified referral"})]}),s.jsxs(ct,{className:"space-y-4",children:[s.jsxs("div",{className:"p-4 bg-muted rounded-lg",children:[s.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:"Your Referral Link"}),s.jsxs("div",{className:"flex gap-2",children:[s.jsxs("code",{className:"flex-1 px-3 py-2 bg-background rounded border text-sm truncate",children:["https://dashboard.relevelup.com/?ref=",e]}),s.jsx(de,{size:"sm",onClick:m,children:s.jsx(ix,{className:"h-4 w-4"})})]})]}),s.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[s.jsxs("div",{className:"text-center p-3 bg-muted/50 rounded-lg",children:[s.jsx(M1,{className:"h-5 w-5 mx-auto text-green-600 mb-1"}),s.jsxs("p",{className:"text-2xl font-bold",children:["$",j]}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Monthly Savings"})]}),s.jsxs("div",{className:"text-center p-3 bg-muted/50 rounded-lg",children:[s.jsx(_i,{className:"h-5 w-5 mx-auto text-primary mb-1"}),s.jsx("p",{className:"text-2xl font-bold",children:g}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Qualified Referrals"})]}),s.jsxs("div",{className:"text-center p-3 bg-muted/50 rounded-lg",children:[s.jsx(No,{className:"h-5 w-5 mx-auto text-amber-600 mb-1"}),s.jsx("p",{className:"text-2xl font-bold",children:_}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Pending (30 days)"})]})]}),n.length>0&&s.jsxs("div",{className:"space-y-2",children:[s.jsx("p",{className:"text-sm font-medium",children:"Your Referrals"}),n.slice(0,5).map(N=>{var C,P;return s.jsxs("div",{className:"flex items-center justify-between p-2 bg-muted/30 rounded",children:[s.jsx("span",{className:"text-sm",children:((C=N.referred_brokerage)==null?void 0:C.name)||((P=N.referred_user)==null?void 0:P.email)||"Pending setup"}),s.jsx(ir,{variant:N.status==="qualified"?"default":N.status==="pending"?"secondary":"destructive",children:N.status})]},N.id)})]})]})]})},k9e=()=>{const{user:t,isBrokerageManager:e,brokerageId:r,isAdmin:n}=rn(),i=Bs(),{toast:o}=Ri(),[c,a]=D.useState(""),[m,g]=D.useState(!0);D.useEffect(()=>{if(!t||!e&&!n){i("/dashboard");return}_()},[t,e,n,r,i]);const _=async()=>{if(!r){o({title:"Error",description:"No brokerage assigned",variant:"destructive"}),i("/dashboard");return}try{const{data:j,error:N}=await ae.from("brokerages").select("name").eq("id",r).single();if(N)throw N;a(j.name)}catch(j){console.error("Error loading brokerage info:",j),o({title:"Error",description:"Failed to load brokerage information",variant:"destructive"})}finally{g(!1)}};return m?s.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):s.jsx("div",{className:"min-h-screen bg-background p-4 md:p-8",children:s.jsxs("div",{className:"mx-auto max-w-7xl",children:[s.jsx("div",{className:"mb-6 flex items-center justify-between",children:s.jsxs("div",{children:[s.jsxs(de,{variant:"ghost",onClick:()=>i("/dashboard"),className:"mb-4",children:[s.jsx(Ka,{className:"mr-2 h-4 w-4"}),"Back to Dashboard"]}),s.jsx("h1",{className:"text-3xl font-bold",children:c}),s.jsx("p",{className:"text-muted-foreground",children:"Brokerage Management Dashboard"})]})}),s.jsxs(go,{defaultValue:"agents",className:"space-y-4",children:[s.jsxs(ao,{className:"grid w-full grid-cols-6",children:[s.jsx(Bn,{value:"agents",children:"Agents"}),s.jsx(Bn,{value:"invite",children:"Invite Links"}),s.jsx(Bn,{value:"referrals",children:"Referrals"}),s.jsx(Bn,{value:"activity",children:"Activity"}),s.jsx(Bn,{value:"analytics",children:"Analytics"}),s.jsx(Bn,{value:"shares",children:"Shares"})]}),s.jsx(xs,{value:"agents",className:"space-y-4",children:s.jsx(v9e,{brokerageId:r})}),s.jsx(xs,{value:"invite",className:"space-y-4",children:s.jsx(N9e,{brokerageId:r})}),s.jsx(xs,{value:"referrals",className:"space-y-4",children:s.jsx(C9e,{})}),s.jsx(xs,{value:"activity",className:"space-y-4",children:s.jsx(j9e,{brokerageId:r})}),s.jsx(xs,{value:"analytics",className:"space-y-4",children:s.jsx(S9e,{brokerageId:r})}),s.jsx(xs,{value:"shares",className:"space-y-4",children:s.jsx(Rye,{brokerageOnly:!0,brokerageId:r})})]})]})})};function T9e(){const t=Bs(),[e,r]=D.useState(""),[n,i]=D.useState("grid"),{data:o,isLoading:c}=Sr({queryKey:["newsletters"],queryFn:async()=>{const{data:C,error:P}=await ae.from("newsletter_content").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(P)throw P;return C}}),{data:a}=Sr({queryKey:["newsletter-likes-all"],queryFn:async()=>{const{data:C}=await ae.from("newsletter_likes").select("newsletter_id");return C||[]}}),{data:m}=Sr({queryKey:["newsletter-comments-all"],queryFn:async()=>{const{data:C}=await ae.from("newsletter_comments").select("newsletter_id");return C||[]}}),g=C=>(a==null?void 0:a.filter(P=>P.newsletter_id===C).length)||0,_=C=>(m==null?void 0:m.filter(P=>P.newsletter_id===C).length)||0,j=o==null?void 0:o.filter(C=>{var P;return C.title.toLowerCase().includes(e.toLowerCase())||((P=C.description)==null?void 0:P.toLowerCase().includes(e.toLowerCase()))}),N=C=>{t(`/newsletters/${C}`)};return s.jsx(Jr,{title:"Newsletter Content",children:s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{children:[s.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Newsletter Content"}),s.jsx("p",{className:"text-muted-foreground mt-1",children:"Monthly newsletter templates and resources"})]}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[s.jsxs("div",{className:"relative flex-1 max-w-sm",children:[s.jsx(ba,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),s.jsx(Et,{placeholder:"Search newsletters...",value:e,onChange:C=>r(C.target.value),className:"pl-9"})]}),s.jsxs("div",{className:"flex gap-2",children:[e&&s.jsx(de,{variant:"outline",size:"sm",onClick:()=>r(""),children:"Clear"}),s.jsxs("div",{className:"flex border rounded-md",children:[s.jsx(de,{variant:n==="grid"?"secondary":"ghost",size:"icon",onClick:()=>i("grid"),className:"rounded-r-none",children:s.jsx(tD,{className:"h-4 w-4"})}),s.jsx(de,{variant:n==="list"?"secondary":"ghost",size:"icon",onClick:()=>i("list"),className:"rounded-l-none",children:s.jsx(Aj,{className:"h-4 w-4"})})]})]})]}),s.jsxs("div",{className:"text-sm text-muted-foreground",children:[(j==null?void 0:j.length)||0," item",(j==null?void 0:j.length)!==1?"s":""," found"]}),c&&s.jsx("div",{className:n==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-4",children:[...Array(8)].map((C,P)=>s.jsx(at,{children:s.jsxs(ct,{className:"p-4",children:[s.jsx(Dn,{className:"aspect-[4/3] w-full rounded-lg mb-4"}),s.jsx(Dn,{className:"h-5 w-3/4 mb-2"}),s.jsx(Dn,{className:"h-4 w-full mb-4"})]})},P))}),!c&&(j==null?void 0:j.length)===0&&s.jsxs("div",{className:"text-center py-12",children:[s.jsx(Ii,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),s.jsx("div",{className:"text-muted-foreground mb-4",children:e?"No newsletters match your search":"No newsletters available yet"}),e&&s.jsx(de,{variant:"outline",onClick:()=>r(""),children:"Clear Search"})]}),!c&&j&&j.length>0&&s.jsx("div",{className:n==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-4",children:j.map(C=>s.jsxs(at,{className:`group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer ${n==="list"?"flex flex-row":""}`,onClick:()=>N(C.id),children:[s.jsx("div",{className:`relative overflow-hidden bg-muted ${n==="list"?"w-48 shrink-0":"aspect-[4/3]"}`,children:C.preview_image_url?s.jsx("img",{src:C.preview_image_url,alt:C.title,className:"w-full h-full object-contain group-hover:scale-105 transition-transform duration-300"}):s.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:s.jsx(Ii,{className:"h-16 w-16"})})}),s.jsxs(ct,{className:`p-4 flex flex-col ${n==="list"?"flex-1":""}`,children:[s.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 mb-1",children:C.title}),C.description&&s.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3 flex-1",children:C.description}),s.jsxs("div",{className:"flex items-center gap-4 text-sm text-muted-foreground mb-3",children:[s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(Ip,{className:"h-3.5 w-3.5"}),g(C.id)]}),s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(lu,{className:"h-3.5 w-3.5"}),_(C.id)]})]}),s.jsxs(de,{size:"sm",className:"w-full gap-2",onClick:P=>{P.stopPropagation(),N(C.id)},children:[s.jsx(oa,{className:"h-4 w-4"}),"View Details"]})]})]},C.id))})]})})}function E9e(){const{id:t}=mu(),e=Bs(),{user:r}=rn(),{toast:n}=Ri(),i=Wn(),{trackEngagement:o}=MT(),[c,a]=D.useState(""),{data:m,isLoading:g}=Sr({queryKey:["newsletter",t],queryFn:async()=>{const{data:V,error:K}=await ae.from("newsletter_content").select("*").eq("id",t).single();if(K)throw K;return V},enabled:!!t});D.useEffect(()=>{m&&o("newsletter",m.id,m.title,"view")},[m==null?void 0:m.id]);const{data:_}=Sr({queryKey:["newsletter-drives",t],queryFn:async()=>{const{data:V}=await ae.from("newsletter_drive_links").select("*").eq("newsletter_id",t).order("sort_order");return V||[]},enabled:!!t}),{data:j}=Sr({queryKey:["newsletter-pdfs",t],queryFn:async()=>{const{data:V}=await ae.from("newsletter_pdfs").select("*").eq("newsletter_id",t).order("sort_order");return V||[]},enabled:!!t}),{data:N}=Sr({queryKey:["newsletter-videos",t],queryFn:async()=>{const{data:V}=await ae.from("newsletter_videos").select("*").eq("newsletter_id",t).order("sort_order");return V||[]},enabled:!!t}),{data:C}=Sr({queryKey:["newsletter-canva-links",t],queryFn:async()=>{const{data:V}=await ae.from("newsletter_canva_links").select("*").eq("newsletter_id",t).order("sort_order");return V||[]},enabled:!!t}),{data:P}=Sr({queryKey:["newsletter-likes",t],queryFn:async()=>{const{data:V}=await ae.from("newsletter_likes").select("*").eq("newsletter_id",t);return V||[]},enabled:!!t}),{data:A}=Sr({queryKey:["newsletter-comments",t],queryFn:async()=>{const{data:V}=await ae.from("newsletter_comments").select("*, profiles:user_id(name)").eq("newsletter_id",t).order("created_at",{ascending:!1});return V||[]},enabled:!!t}),I=P==null?void 0:P.some(V=>V.user_id===(r==null?void 0:r.id)),O=zr({mutationFn:async()=>{I?await ae.from("newsletter_likes").delete().eq("newsletter_id",t).eq("user_id",r==null?void 0:r.id):await ae.from("newsletter_likes").insert({newsletter_id:t,user_id:r==null?void 0:r.id})},onSuccess:()=>{i.invalidateQueries({queryKey:["newsletter-likes",t]})}}),R=zr({mutationFn:async V=>{const{error:K}=await ae.from("newsletter_comments").insert({newsletter_id:t,user_id:r==null?void 0:r.id,content:V});if(K)throw K},onSuccess:()=>{i.invalidateQueries({queryKey:["newsletter-comments",t]}),a(""),n({title:"Comment added"})}}),z=zr({mutationFn:async V=>{const{error:K}=await ae.from("newsletter_comments").delete().eq("id",V);if(K)throw K},onSuccess:()=>{i.invalidateQueries({queryKey:["newsletter-comments",t]}),n({title:"Comment deleted"})}}),W=V=>{if(V.includes("player.mediadelivery.net")||V.includes("iframe.mediadelivery.net")){const K=V.match(/embed\/(\d+)\/([a-f0-9-]+)/);if(K)return s.jsx("div",{className:"relative w-full pt-[56.25%]",children:s.jsx("iframe",{src:`https://iframe.mediadelivery.net/embed/${K[1]}/${K[2]}?autoplay=false`,className:"absolute inset-0 w-full h-full rounded-lg",allow:"accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture",allowFullScreen:!0})})}if(V.includes("youtube.com")||V.includes("youtu.be")){const K=V.match(/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([^&\s]+)/);if(K)return s.jsx("div",{className:"relative w-full pt-[56.25%]",children:s.jsx("iframe",{src:`https://www.youtube.com/embed/${K[1]}`,className:"absolute inset-0 w-full h-full rounded-lg",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})}return s.jsxs("a",{href:V,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 text-primary hover:underline",children:[s.jsx(Sf,{className:"h-4 w-4"})," Watch Video"]})};return g?s.jsx(Jr,{title:"",description:"",children:s.jsxs("div",{className:"space-y-6",children:[s.jsx(Dn,{className:"h-8 w-32"}),s.jsx(Dn,{className:"h-64 w-full"}),s.jsx(Dn,{className:"h-32 w-full"})]})}):m?s.jsx(Jr,{title:"",description:"",children:s.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[s.jsxs(de,{variant:"ghost",onClick:()=>e("/newsletters"),className:"mb-4",children:[s.jsx(Ka,{className:"mr-2 h-4 w-4"})," Back to Newsletters"]}),m.preview_image_url&&s.jsx("img",{src:m.preview_image_url,alt:m.title,className:"w-full h-64 md:h-80 object-cover rounded-lg"}),s.jsxs("div",{children:[s.jsx("h1",{className:"text-3xl font-bold",children:m.title}),s.jsx("p",{className:"text-muted-foreground mt-1",children:Vn(new Date(m.publish_date),"MMMM d, yyyy")})]}),m.description&&s.jsx("p",{className:"text-lg text-muted-foreground",children:m.description}),s.jsxs("div",{className:"flex items-center gap-4",children:[s.jsx(Wj,{resourceType:"newsletter",resourceId:m.id,resourceTitle:m.title}),s.jsxs(de,{variant:I?"default":"outline",size:"sm",onClick:()=>O.mutate(),children:[s.jsx(bp,{className:`h-4 w-4 mr-1 ${I?"fill-current":""}`}),(P==null?void 0:P.length)||0," ",(P==null?void 0:P.length)===1?"Like":"Likes"]})]}),C&&C.length>0&&s.jsxs(at,{children:[s.jsx(xr,{children:s.jsx(wr,{className:"text-lg",children:"Canva Templates"})}),s.jsx(ct,{className:"space-y-2",children:C.map(V=>s.jsxs("a",{href:V.canva_share_link,target:"_blank",rel:"noopener noreferrer",onClick:()=>o("newsletter",m.id,m.title,"click_canva"),className:"flex items-center gap-3 p-3 rounded-lg hover:bg-muted transition-colors",children:[s.jsx(A_,{className:"h-5 w-5 text-purple-500"}),s.jsx("span",{className:"font-medium",children:V.title}),s.jsx(oa,{className:"h-4 w-4 text-muted-foreground ml-auto"})]},V.id))})]}),_&&_.length>0&&s.jsxs(at,{children:[s.jsx(xr,{children:s.jsx(wr,{className:"text-lg",children:"Google Drive Files"})}),s.jsx(ct,{className:"space-y-2",children:_.map(V=>s.jsxs("a",{href:V.drive_url,target:"_blank",rel:"noopener noreferrer",onClick:()=>o("newsletter",m.id,m.title,"click_link"),className:"flex items-center gap-3 p-3 rounded-lg hover:bg-muted transition-colors",children:[s.jsx(oa,{className:"h-5 w-5 text-primary"}),s.jsx("span",{className:"font-medium",children:V.title})]},V.id))})]}),j&&j.length>0&&s.jsxs(at,{children:[s.jsx(xr,{children:s.jsx(wr,{className:"text-lg",children:"PDF Downloads"})}),s.jsx(ct,{className:"space-y-2",children:j.map(V=>s.jsxs("a",{href:V.file_url,target:"_blank",rel:"noopener noreferrer",onClick:()=>o("newsletter",m.id,m.title,"click_pdf"),className:"flex items-center gap-3 p-3 rounded-lg hover:bg-muted transition-colors",children:[s.jsx(Ii,{className:"h-5 w-5 text-red-500"}),s.jsx("span",{className:"font-medium flex-1",children:V.name}),s.jsx(Pp,{className:"h-4 w-4 text-muted-foreground"})]},V.id))})]}),N&&N.length>0&&s.jsxs(at,{children:[s.jsx(xr,{children:s.jsx(wr,{className:"text-lg",children:"Videos"})}),s.jsx(ct,{className:"space-y-6",children:N.map(V=>s.jsxs("div",{className:"space-y-2",children:[s.jsx("h4",{className:"font-medium",children:V.title}),W(V.video_url)]},V.id))})]}),s.jsxs(at,{children:[s.jsx(xr,{children:s.jsxs(wr,{className:"text-lg",children:["Comments (",(A==null?void 0:A.length)||0,")"]})}),s.jsxs(ct,{className:"space-y-4",children:[s.jsxs("div",{className:"flex gap-3",children:[s.jsx(mi,{placeholder:"Write a comment...",value:c,onChange:V=>a(V.target.value),className:"flex-1"}),s.jsx(de,{onClick:()=>c.trim()&&R.mutate(c),disabled:!c.trim()||R.isPending,children:s.jsx(Dc,{className:"h-4 w-4"})})]}),s.jsx("div",{className:"space-y-4",children:A==null?void 0:A.map(V=>{var K,Q,te;return s.jsxs("div",{className:"flex gap-3",children:[s.jsx(ql,{className:"h-8 w-8",children:s.jsx(Hl,{children:((Q=(K=V.profiles)==null?void 0:K.name)==null?void 0:Q[0])||"U"})}),s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"font-medium text-sm",children:((te=V.profiles)==null?void 0:te.name)||"User"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-xs text-muted-foreground",children:Vn(new Date(V.created_at),"MMM d, yyyy")}),V.user_id===(r==null?void 0:r.id)&&s.jsx(de,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>z.mutate(V.id),children:s.jsx(oi,{className:"h-3 w-3"})})]})]}),s.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:V.content})]})]},V.id)})})]})]})]})}):s.jsx(Jr,{title:"Not Found",description:"",children:s.jsxs("div",{className:"text-center py-12",children:[s.jsx("p",{className:"text-muted-foreground",children:"Newsletter not found"}),s.jsx(de,{variant:"link",onClick:()=>e("/newsletters"),children:"Back to Newsletters"})]})})}function A9e(){const{toast:t}=Ri(),e=Wn(),[r,n]=D.useState(!1),[i,o]=D.useState(null),[c,a]=D.useState({title:"",description:"",publish_date:Vn(new Date,"yyyy-MM-dd'T'HH:mm"),is_published:!1}),[m,g]=D.useState(null),[_,j]=D.useState(null),[N,C]=D.useState([]),[P,A]=D.useState([]),[I,O]=D.useState([]),[R,z]=D.useState([]),[W,V]=D.useState([]),[K,Q]=D.useState(!1),{data:te,isLoading:X}=Sr({queryKey:["admin-newsletters"],queryFn:async()=>{const{data:_e,error:Ye}=await ae.from("newsletter_content").select("*").order("publish_date",{ascending:!1});if(Ye)throw Ye;return _e}}),ie=zr({mutationFn:async _e=>{const{data:Ye,error:pt}=await ae.from("newsletter_content").insert({title:_e.title,description:_e.description||null,preview_image_url:_e.preview_image_url,publish_date:_e.publish_date,is_published:_e.is_published}).select().single();if(pt)throw pt;return Ye},onSuccess:async _e=>{await pe(_e.id),e.invalidateQueries({queryKey:["admin-newsletters"]}),t({title:"Newsletter created successfully"}),ge()},onError:_e=>{t({title:"Error creating newsletter",description:_e.message,variant:"destructive"})}}),he=zr({mutationFn:async _e=>{const{error:Ye}=await ae.from("newsletter_content").update({title:_e.title,description:_e.description||null,preview_image_url:_e.preview_image_url,publish_date:_e.publish_date,is_published:_e.is_published}).eq("id",_e.id);if(Ye)throw Ye;return _e.id},onSuccess:async _e=>{await pe(_e),e.invalidateQueries({queryKey:["admin-newsletters"]}),t({title:"Newsletter updated successfully"}),ge()},onError:_e=>{t({title:"Error updating newsletter",description:_e.message,variant:"destructive"})}}),xe=zr({mutationFn:async _e=>{const{error:Ye}=await ae.from("newsletter_content").delete().eq("id",_e);if(Ye)throw Ye},onSuccess:()=>{e.invalidateQueries({queryKey:["admin-newsletters"]}),t({title:"Newsletter deleted successfully"})},onError:_e=>{t({title:"Error deleting newsletter",description:_e.message,variant:"destructive"})}}),pe=async _e=>{await ae.from("newsletter_drive_links").delete().eq("newsletter_id",_e),await ae.from("newsletter_pdfs").delete().eq("newsletter_id",_e),await ae.from("newsletter_videos").delete().eq("newsletter_id",_e),await ae.from("newsletter_canva_links").delete().eq("newsletter_id",_e);for(const Ye of W){const pt=`${_e}/${Date.now()}-${Ye.file.name}`,{error:nt}=await ae.storage.from("newsletter-content").upload(pt,Ye.file);if(!nt){const{data:Qt}=ae.storage.from("newsletter-content").getPublicUrl(pt);P.push({name:Ye.name,file_url:Qt.publicUrl,file_size:Ye.file.size,sort_order:P.length})}}N.length>0&&await ae.from("newsletter_drive_links").insert(N.map((Ye,pt)=>({newsletter_id:_e,title:Ye.title,drive_url:Ye.drive_url,sort_order:pt}))),P.length>0&&await ae.from("newsletter_pdfs").insert(P.map((Ye,pt)=>({newsletter_id:_e,name:Ye.name,file_url:Ye.file_url,file_size:Ye.file_size||null,sort_order:pt}))),I.length>0&&await ae.from("newsletter_videos").insert(I.map((Ye,pt)=>({newsletter_id:_e,title:Ye.title,video_url:Ye.video_url,sort_order:pt}))),R.length>0&&await ae.from("newsletter_canva_links").insert(R.map((Ye,pt)=>({newsletter_id:_e,title:Ye.title,canva_share_link:Ye.canva_share_link,sort_order:pt})))},ve=async _e=>{o(_e),a({title:_e.title,description:_e.description||"",publish_date:Vn(new Date(_e.publish_date),"yyyy-MM-dd'T'HH:mm"),is_published:_e.is_published}),j(_e.preview_image_url);const[Ye,pt,nt,Qt]=await Promise.all([ae.from("newsletter_drive_links").select("*").eq("newsletter_id",_e.id).order("sort_order"),ae.from("newsletter_pdfs").select("*").eq("newsletter_id",_e.id).order("sort_order"),ae.from("newsletter_videos").select("*").eq("newsletter_id",_e.id).order("sort_order"),ae.from("newsletter_canva_links").select("*").eq("newsletter_id",_e.id).order("sort_order")]);C(Ye.data||[]),A(pt.data||[]),O(nt.data||[]),z(Qt.data||[]),V([]),n(!0)},ge=()=>{n(!1),o(null),a({title:"",description:"",publish_date:Vn(new Date,"yyyy-MM-dd'T'HH:mm"),is_published:!1}),g(null),j(null),C([]),A([]),O([]),z([]),V([])},ke=async _e=>{var pt;const Ye=(pt=_e.target.files)==null?void 0:pt[0];Ye&&(g(Ye),j(URL.createObjectURL(Ye)))},Ce=async()=>{if(!c.title){t({title:"Title is required",variant:"destructive"});return}Q(!0);let _e=_;if(m){const Ye=`previews/${Date.now()}-${m.name}`,{error:pt}=await ae.storage.from("newsletter-content").upload(Ye,m);if(!pt){const{data:nt}=ae.storage.from("newsletter-content").getPublicUrl(Ye);_e=nt.publicUrl}}i?he.mutate({id:i.id,...c,preview_image_url:_e}):ie.mutate({...c,preview_image_url:_e}),Q(!1)},Se=()=>{C([...N,{title:"",drive_url:"",sort_order:N.length}])},je=()=>{O([...I,{title:"",video_url:"",sort_order:I.length}])},et=()=>{z([...R,{title:"",canva_share_link:"",sort_order:R.length}])},bt=_e=>{const Ye=_e.target.files;if(!Ye)return;const pt=Array.from(Ye).map(nt=>({file:nt,name:nt.name.replace(/\.[^/.]+$/,"")}));V([...W,...pt])};return s.jsx(Jr,{title:"Newsletter Content",description:"Manage monthly newsletter templates and resources",children:s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsxs(at,{children:[s.jsx(xr,{className:"pb-2",children:s.jsx(wr,{className:"text-sm font-medium text-muted-foreground",children:"Total Newsletters"})}),s.jsx(ct,{children:s.jsx("div",{className:"text-2xl font-bold",children:(te==null?void 0:te.length)||0})})]}),s.jsxs(at,{children:[s.jsx(xr,{className:"pb-2",children:s.jsx(wr,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),s.jsx(ct,{children:s.jsx("div",{className:"text-2xl font-bold",children:(te==null?void 0:te.filter(_e=>_e.is_published).length)||0})})]})]}),s.jsxs(mn,{open:r,onOpenChange:_e=>!_e&&ge(),children:[s.jsx(Do,{asChild:!0,children:s.jsxs(de,{onClick:()=>n(!0),children:[s.jsx(Qn,{className:"mr-2 h-4 w-4"})," Add Newsletter"]})}),s.jsxs(pn,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[s.jsx(xn,{children:s.jsx(gn,{children:i?"Edit Newsletter":"Add Newsletter"})}),s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Title *"}),s.jsx(Et,{value:c.title,onChange:_e=>a({...c,title:_e.target.value}),placeholder:"Newsletter title"})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Publish Date"}),s.jsx(Et,{type:"datetime-local",value:c.publish_date,onChange:_e=>a({...c,publish_date:_e.target.value})})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Description"}),s.jsx(ag,{content:c.description,onChange:_e=>a({...c,description:_e}),placeholder:"Newsletter description",minHeight:"120px"})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Preview Image"}),s.jsxs("div",{className:"flex items-center gap-4",children:[_&&s.jsx("img",{src:_,alt:"Preview",className:"h-20 w-32 object-cover rounded-md"}),s.jsxs("div",{children:[s.jsx(Et,{type:"file",accept:"image/*",onChange:ke,className:"hidden",id:"preview-upload"}),s.jsx(de,{variant:"outline",asChild:!0,children:s.jsxs("label",{htmlFor:"preview-upload",className:"cursor-pointer",children:[s.jsx(Vu,{className:"mr-2 h-4 w-4"})," Upload Image"]})})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(ri,{checked:c.is_published,onCheckedChange:_e=>a({...c,is_published:_e})}),s.jsx(mt,{children:"Published"})]}),s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx(mt,{className:"text-base font-medium",children:"Google Drive Links"}),s.jsxs(de,{type:"button",variant:"outline",size:"sm",onClick:Se,children:[s.jsx(Qn,{className:"mr-1 h-3 w-3"})," Add Link"]})]}),N.map((_e,Ye)=>s.jsxs("div",{className:"flex gap-2 items-center",children:[s.jsx(Et,{placeholder:"Link title",value:_e.title,onChange:pt=>{const nt=[...N];nt[Ye].title=pt.target.value,C(nt)},className:"w-1/3"}),s.jsx(Et,{placeholder:"Google Drive URL",value:_e.drive_url,onChange:pt=>{const nt=[...N];nt[Ye].drive_url=pt.target.value,C(nt)},className:"flex-1"}),s.jsx(de,{type:"button",variant:"ghost",size:"icon",onClick:()=>C(N.filter((pt,nt)=>nt!==Ye)),children:s.jsx(Ni,{className:"h-4 w-4"})})]},Ye))]}),s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx(mt,{className:"text-base font-medium",children:"PDF Files"}),s.jsxs("div",{children:[s.jsx(Et,{type:"file",accept:".pdf",multiple:!0,onChange:bt,className:"hidden",id:"pdf-upload"}),s.jsx(de,{variant:"outline",size:"sm",asChild:!0,children:s.jsxs("label",{htmlFor:"pdf-upload",className:"cursor-pointer",children:[s.jsx(Vu,{className:"mr-1 h-3 w-3"})," Upload PDF"]})})]})]}),P.map((_e,Ye)=>s.jsxs("div",{className:"flex gap-2 items-center bg-muted/50 p-2 rounded",children:[s.jsx(Ii,{className:"h-4 w-4 text-muted-foreground"}),s.jsx("span",{className:"flex-1 text-sm",children:_e.name}),s.jsx(de,{type:"button",variant:"ghost",size:"icon",onClick:()=>A(P.filter((pt,nt)=>nt!==Ye)),children:s.jsx(Ni,{className:"h-4 w-4"})})]},`existing-${Ye}`)),W.map((_e,Ye)=>s.jsxs("div",{className:"flex gap-2 items-center bg-muted/50 p-2 rounded",children:[s.jsx(Ii,{className:"h-4 w-4 text-muted-foreground"}),s.jsx(Et,{value:_e.name,onChange:pt=>{const nt=[...W];nt[Ye].name=pt.target.value,V(nt)},className:"flex-1 h-8",placeholder:"PDF name"}),s.jsx("span",{className:"text-xs text-muted-foreground",children:"(new)"}),s.jsx(de,{type:"button",variant:"ghost",size:"icon",onClick:()=>V(W.filter((pt,nt)=>nt!==Ye)),children:s.jsx(Ni,{className:"h-4 w-4"})})]},`pending-${Ye}`))]}),s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx(mt,{className:"text-base font-medium",children:"Video Links"}),s.jsxs(de,{type:"button",variant:"outline",size:"sm",onClick:je,children:[s.jsx(Qn,{className:"mr-1 h-3 w-3"})," Add Video"]})]}),I.map((_e,Ye)=>s.jsxs("div",{className:"flex gap-2 items-center",children:[s.jsx(Et,{placeholder:"Video title",value:_e.title,onChange:pt=>{const nt=[...I];nt[Ye].title=pt.target.value,O(nt)},className:"w-1/3"}),s.jsx(Et,{placeholder:"Video URL (YouTube, Vimeo, etc.)",value:_e.video_url,onChange:pt=>{const nt=[...I];nt[Ye].video_url=pt.target.value,O(nt)},className:"flex-1"}),s.jsx(de,{type:"button",variant:"ghost",size:"icon",onClick:()=>O(I.filter((pt,nt)=>nt!==Ye)),children:s.jsx(Ni,{className:"h-4 w-4"})})]},Ye))]}),s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx(mt,{className:"text-base font-medium",children:"Canva Links"}),s.jsxs(de,{type:"button",variant:"outline",size:"sm",onClick:et,children:[s.jsx(Qn,{className:"mr-1 h-3 w-3"})," Add Canva Link"]})]}),R.map((_e,Ye)=>s.jsxs("div",{className:"flex gap-2 items-center",children:[s.jsx(Et,{placeholder:"Link title",value:_e.title,onChange:pt=>{const nt=[...R];nt[Ye].title=pt.target.value,z(nt)},className:"w-1/3"}),s.jsx(Et,{placeholder:"Canva share link",value:_e.canva_share_link,onChange:pt=>{const nt=[...R];nt[Ye].canva_share_link=pt.target.value,z(nt)},className:"flex-1"}),s.jsx(de,{type:"button",variant:"ghost",size:"icon",onClick:()=>z(R.filter((pt,nt)=>nt!==Ye)),children:s.jsx(Ni,{className:"h-4 w-4"})})]},Ye))]}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(de,{variant:"outline",onClick:ge,children:"Cancel"}),s.jsx(de,{onClick:Ce,disabled:K||ie.isPending||he.isPending,children:K?"Uploading...":i?"Update":"Create"})]})]})]})]})]}),s.jsx(at,{children:s.jsx(ct,{className:"p-0",children:s.jsxs(ni,{children:[s.jsx(si,{children:s.jsxs(Dr,{children:[s.jsx(Nt,{children:"Name"}),s.jsx(Nt,{children:"Publish Date"}),s.jsx(Nt,{children:"Status"}),s.jsx(Nt,{className:"text-right",children:"Actions"})]})}),s.jsx(ii,{children:X?s.jsx(Dr,{children:s.jsx(xt,{colSpan:4,className:"text-center py-8",children:"Loading..."})}):(te==null?void 0:te.length)===0?s.jsx(Dr,{children:s.jsx(xt,{colSpan:4,className:"text-center py-8 text-muted-foreground",children:"No newsletters yet. Create your first one!"})}):te==null?void 0:te.map(_e=>s.jsxs(Dr,{children:[s.jsx(xt,{children:s.jsxs("div",{className:"flex items-center gap-3",children:[_e.preview_image_url?s.jsx("img",{src:_e.preview_image_url,alt:_e.title,className:"w-10 h-10 rounded object-cover"}):s.jsx("div",{className:"w-10 h-10 rounded bg-muted flex items-center justify-center",children:s.jsx(Ii,{className:"h-5 w-5 text-muted-foreground"})}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium",children:_e.title}),_e.description&&s.jsx("div",{className:"text-sm text-muted-foreground line-clamp-1",children:_e.description})]})]})}),s.jsx(xt,{children:Vn(new Date(_e.publish_date),"MMM d, yyyy")}),s.jsx(xt,{children:s.jsx("span",{className:`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${_e.is_published?"bg-green-100 text-green-800":"bg-yellow-100 text-yellow-800"}`,children:_e.is_published?"Published":"Draft"})}),s.jsx(xt,{className:"text-right",children:s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(de,{variant:"ghost",size:"icon",onClick:()=>ve(_e),children:s.jsx(Rc,{className:"h-4 w-4"})}),s.jsx(de,{variant:"ghost",size:"icon",onClick:()=>ve(_e),children:s.jsx(io,{className:"h-4 w-4"})}),s.jsx(de,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",onClick:()=>{confirm("Are you sure you want to delete this newsletter?")&&xe.mutate(_e.id)},children:s.jsx(oi,{className:"h-4 w-4"})})]})})]},_e.id))})]})})})]})})}const KJ={open:{label:"Open",color:"bg-blue-100 text-blue-800"},under_review:{label:"Under Review",color:"bg-yellow-100 text-yellow-800"},planned:{label:"Planned",color:"bg-purple-100 text-purple-800"},in_progress:{label:"In Progress",color:"bg-orange-100 text-orange-800"},launched:{label:"Launched",color:"bg-green-100 text-green-800"},declined:{label:"Declined",color:"bg-gray-100 text-gray-800"}};function P9e(){const{user:t}=rn(),{toast:e}=Ri(),r=Bs(),n=Wn(),[i,o]=D.useState(""),[c,a]=D.useState("popular"),[m,g]=D.useState(!1),[_,j]=D.useState(""),[N,C]=D.useState(""),[P,A]=D.useState(!1),{data:I=[],isLoading:O}=Sr({queryKey:["wishlist-items",c,P],queryFn:async()=>{let K=ae.from("wishlist_items").select("*");P&&t&&(K=K.eq("user_id",t.id)),c==="latest"?K=K.order("created_at",{ascending:!1}):c==="popular"?K=K.order("vote_count",{ascending:!1}):c==="trending"&&(K=K.order("vote_count",{ascending:!1}));const{data:Q,error:te}=await K;if(te)throw te;const X=[...new Set((Q==null?void 0:Q.map(ke=>ke.user_id))||[])],{data:ie}=await ae.from("profiles").select("id, name").in("id",X),he=new Map((ie==null?void 0:ie.map(ke=>[ke.id,ke]))||[]);let xe=[];if(t){const{data:ke}=await ae.from("wishlist_votes").select("item_id").eq("user_id",t.id);xe=(ke==null?void 0:ke.map(Ce=>Ce.item_id))||[]}const pe=(Q==null?void 0:Q.map(ke=>ke.id))||[],{data:ve}=await ae.from("wishlist_comments").select("item_id").in("item_id",pe),ge=new Map;return ve==null||ve.forEach(ke=>{ge.set(ke.item_id,(ge.get(ke.item_id)||0)+1)}),Q==null?void 0:Q.map(ke=>{const Ce=he.get(ke.user_id),Se=(Ce==null?void 0:Ce.name)||"Unknown";return{...ke,user_name:Se,user_initials:Se.split(" ").map(je=>je[0]).join("").toUpperCase().slice(0,2),has_voted:xe.includes(ke.id),comment_count:ge.get(ke.id)||0}})}}),R=zr({mutationFn:async({title:K,description:Q})=>{const{error:te}=await ae.from("wishlist_items").insert({user_id:t.id,title:K,description:Q});if(te)throw te},onSuccess:()=>{n.invalidateQueries({queryKey:["wishlist-items"]}),g(!1),j(""),C(""),e({title:"Idea submitted!",description:"Your idea has been added to the wishlist."})},onError:K=>{e({title:"Error",description:K.message,variant:"destructive"})}}),z=zr({mutationFn:async({itemId:K,hasVoted:Q})=>{if(Q){const{error:te}=await ae.from("wishlist_votes").delete().eq("item_id",K).eq("user_id",t.id);if(te)throw te;return{itemId:K,wasAdded:!1}}else{const{error:te}=await ae.from("wishlist_votes").insert({item_id:K,user_id:t.id});if(te)throw te;return{itemId:K,wasAdded:!0}}},onSuccess:async K=>{if(n.invalidateQueries({queryKey:["wishlist-items"]}),K!=null&&K.wasAdded){const Q=I.find(X=>X.id===K.itemId),te=((Q==null?void 0:Q.vote_count)||0)+1;ae.functions.invoke("wishlist-notify",{body:{itemId:K.itemId,voteCount:te}}).catch(console.error)}},onError:K=>{e({title:"Error",description:K.message,variant:"destructive"})}}),W=I.filter(K=>K.title.toLowerCase().includes(i.toLowerCase())||K.description.toLowerCase().includes(i.toLowerCase())),V=()=>{if(!_.trim()||!N.trim()){e({title:"Error",description:"Please fill in both title and description.",variant:"destructive"});return}R.mutate({title:_.trim(),description:N.trim()})};return s.jsx(Jr,{title:"Wishlist",children:s.jsxs("div",{className:"max-w-4xl mx-auto",children:[s.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:s.jsx(pM,{className:"h-6 w-6 text-primary"})}),s.jsxs("div",{children:[s.jsx("h1",{className:"text-2xl font-bold",children:"Wishlist"}),s.jsx("p",{className:"text-muted-foreground text-sm",children:"Share ideas and vote on what we build next"})]})]}),s.jsxs(mn,{open:m,onOpenChange:g,children:[s.jsx(Do,{asChild:!0,children:s.jsxs(de,{className:"gap-2",children:[s.jsx(Qn,{className:"h-4 w-4"}),"Add Idea"]})}),s.jsxs(pn,{children:[s.jsx(xn,{children:s.jsx(gn,{children:"Submit a New Idea"})}),s.jsxs("div",{className:"space-y-4 pt-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"title",children:"Title"}),s.jsx(Et,{id:"title",placeholder:"Give your idea a clear title...",value:_,onChange:K=>j(K.target.value)})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"description",children:"Description"}),s.jsx(mi,{id:"description",placeholder:"Describe your idea in detail. What problem does it solve? How would it help agents?",value:N,onChange:K=>C(K.target.value),rows:4})]}),s.jsx(de,{onClick:V,className:"w-full",disabled:R.isPending,children:R.isPending?s.jsxs(s.Fragment,{children:[s.jsx(Ps,{className:"h-4 w-4 mr-2 animate-spin"}),"Submitting..."]}):"Submit Idea"})]})]})]})]}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 mb-6",children:[s.jsxs("div",{className:"relative flex-1",children:[s.jsx(ba,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),s.jsx(Et,{placeholder:"Search ideas...",value:i,onChange:K=>o(K.target.value),className:"pl-10"})]}),s.jsx("div",{className:"flex gap-2",children:s.jsx(go,{value:c,onValueChange:K=>a(K),children:s.jsxs(ao,{children:[s.jsx(Bn,{value:"popular",children:"Most Popular"}),s.jsx(Bn,{value:"latest",children:"Latest"}),s.jsx(Bn,{value:"trending",children:"Trending"})]})})})]}),s.jsx("div",{className:"flex items-center gap-2 mb-4",children:s.jsx(de,{variant:P?"default":"outline",size:"sm",onClick:()=>A(!P),children:P?"Show All Ideas":"My Ideas"})}),O?s.jsx("div",{className:"flex items-center justify-center py-12",children:s.jsx(Ps,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):W.length===0?s.jsxs("div",{className:"text-center py-12 bg-muted/30 rounded-lg",children:[s.jsx(pM,{className:"h-12 w-12 text-muted-foreground mx-auto mb-4"}),s.jsx("h3",{className:"text-lg font-medium mb-2",children:"No ideas yet"}),s.jsx("p",{className:"text-muted-foreground mb-4",children:"Be the first to submit an idea!"}),s.jsxs(de,{onClick:()=>g(!0),children:[s.jsx(Qn,{className:"h-4 w-4 mr-2"}),"Add Idea"]})]}):s.jsx("div",{className:"space-y-3",children:W.map(K=>s.jsx("div",{className:"bg-card border rounded-lg p-4 hover:shadow-md transition-shadow cursor-pointer",onClick:()=>r(`/wishlist/${K.id}`),children:s.jsxs("div",{className:"flex items-start gap-4",children:[s.jsxs("button",{onClick:Q=>{Q.stopPropagation(),z.mutate({itemId:K.id,hasVoted:K.has_voted||!1})},className:ar("flex flex-col items-center justify-center min-w-[50px] py-2 px-3 rounded-lg border transition-colors",K.has_voted?"bg-primary/10 border-primary text-primary":"bg-muted/50 border-border hover:bg-muted"),children:[s.jsx(noe,{className:ar("h-4 w-4",K.has_voted&&"fill-current")}),s.jsx("span",{className:"text-sm font-semibold",children:K.vote_count})]}),s.jsx(ql,{className:"h-10 w-10 bg-primary/20",children:s.jsx(Hl,{className:"bg-primary/20 text-primary text-sm font-medium",children:K.user_initials})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx("h3",{className:"font-semibold text-foreground",children:K.title}),s.jsx(ir,{className:ar("text-xs",KJ[K.status].color),children:KJ[K.status].label})]}),s.jsx("p",{className:"text-muted-foreground text-sm line-clamp-2",children:K.description}),s.jsxs("div",{className:"flex items-center gap-3 mt-2 text-xs text-muted-foreground",children:[s.jsx("span",{children:K.user_name}),s.jsx("span",{children:"•"}),s.jsx("span",{children:new Date(K.created_at).toLocaleDateString()})]})]}),s.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[s.jsx(Tf,{className:"h-4 w-4"}),s.jsx("span",{className:"text-sm",children:K.comment_count})]})]})},K.id))})]})})}const ZJ={open:{label:"Open",color:"bg-blue-100 text-blue-800"},under_review:{label:"Under Review",color:"bg-yellow-100 text-yellow-800"},planned:{label:"Planned",color:"bg-purple-100 text-purple-800"},in_progress:{label:"In Progress",color:"bg-orange-100 text-orange-800"},launched:{label:"Launched",color:"bg-green-100 text-green-800"},declined:{label:"Declined",color:"bg-gray-100 text-gray-800"}};function I9e(){const{itemId:t}=mu(),e=Bs(),{user:r}=rn(),{toast:n}=Ri(),i=Wn(),[o,c]=D.useState(""),{data:a,isLoading:m}=Sr({queryKey:["wishlist-item",t],queryFn:async()=>{const{data:A,error:I}=await ae.from("wishlist_items").select("*").eq("id",t).single();if(I)throw I;const{data:O}=await ae.from("profiles").select("name").eq("id",A.user_id).single();let R=!1;if(r){const{data:z}=await ae.from("wishlist_votes").select("id").eq("item_id",t).eq("user_id",r.id).maybeSingle();R=!!z}return{...A,user_name:(O==null?void 0:O.name)||"Unknown",user_initials:((O==null?void 0:O.name)||"U").split(" ").map(z=>z[0]).join("").toUpperCase().slice(0,2),has_voted:R}}}),{data:g=[],isLoading:_}=Sr({queryKey:["wishlist-comments",t],queryFn:async()=>{const{data:A,error:I}=await ae.from("wishlist_comments").select("*").eq("item_id",t).order("created_at",{ascending:!0});if(I)throw I;const O=[...new Set((A==null?void 0:A.map(W=>W.user_id))||[])],{data:R}=await ae.from("profiles").select("id, name").in("id",O),z=new Map((R==null?void 0:R.map(W=>[W.id,W]))||[]);return A==null?void 0:A.map(W=>{const V=z.get(W.user_id),K=(V==null?void 0:V.name)||"Unknown";return{...W,user_name:K,user_initials:K.split(" ").map(Q=>Q[0]).join("").toUpperCase().slice(0,2)}})}}),j=zr({mutationFn:async A=>{if(A){const{error:I}=await ae.from("wishlist_votes").delete().eq("item_id",t).eq("user_id",r.id);if(I)throw I;return{wasAdded:!1}}else{const{error:I}=await ae.from("wishlist_votes").insert({item_id:t,user_id:r.id});if(I)throw I;return{wasAdded:!0}}},onSuccess:async A=>{if(i.invalidateQueries({queryKey:["wishlist-item",t]}),i.invalidateQueries({queryKey:["wishlist-items"]}),A!=null&&A.wasAdded&&a){const I=(a.vote_count||0)+1;ae.functions.invoke("wishlist-notify",{body:{itemId:t,voteCount:I}}).catch(console.error)}},onError:A=>{n({title:"Error",description:A.message,variant:"destructive"})}}),N=zr({mutationFn:async A=>{const{error:I}=await ae.from("wishlist_comments").insert({item_id:t,user_id:r.id,content:A});if(I)throw I},onSuccess:()=>{i.invalidateQueries({queryKey:["wishlist-comments",t]}),c(""),n({title:"Comment added!"})},onError:A=>{n({title:"Error",description:A.message,variant:"destructive"})}}),C=zr({mutationFn:async A=>{const{error:I}=await ae.from("wishlist_comments").delete().eq("id",A);if(I)throw I},onSuccess:()=>{i.invalidateQueries({queryKey:["wishlist-comments",t]}),n({title:"Comment deleted"})},onError:A=>{n({title:"Error",description:A.message,variant:"destructive"})}}),P=()=>{o.trim()&&N.mutate(o.trim())};return m?s.jsx(Jr,{title:"Wishlist",children:s.jsxs("div",{className:"max-w-3xl mx-auto",children:[s.jsx(Dn,{className:"h-8 w-32 mb-6"}),s.jsx(Dn,{className:"h-48 w-full mb-6"}),s.jsx(Dn,{className:"h-32 w-full"})]})}):a?s.jsx(Jr,{title:"Wishlist",children:s.jsxs("div",{className:"max-w-3xl mx-auto",children:[s.jsxs(de,{variant:"ghost",size:"sm",onClick:()=>e("/wishlist"),className:"mb-4",children:[s.jsx(Ka,{className:"h-4 w-4 mr-2"}),"Back to Wishlist"]}),s.jsx("div",{className:"bg-card border rounded-lg p-6 mb-6",children:s.jsxs("div",{className:"flex items-start gap-4",children:[s.jsxs("button",{onClick:()=>j.mutate(a.has_voted),className:ar("flex flex-col items-center justify-center min-w-[60px] py-3 px-4 rounded-lg border transition-colors",a.has_voted?"bg-primary/10 border-primary text-primary":"bg-muted/50 border-border hover:bg-muted"),children:[s.jsx(noe,{className:ar("h-5 w-5",a.has_voted&&"fill-current")}),s.jsx("span",{className:"text-lg font-bold",children:a.vote_count}),s.jsx("span",{className:"text-xs",children:"votes"})]}),s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[s.jsx("h1",{className:"text-xl font-bold",children:a.title}),s.jsx(ir,{className:ar("text-xs",ZJ[a.status].color),children:ZJ[a.status].label})]}),s.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap mb-4",children:a.description}),s.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[s.jsx(ql,{className:"h-6 w-6",children:s.jsx(Hl,{className:"bg-primary/20 text-primary text-xs",children:a.user_initials})}),s.jsx("span",{children:a.user_name}),s.jsx("span",{children:"•"}),s.jsx("span",{children:new Date(a.created_at).toLocaleDateString()})]})]})]})}),s.jsxs("div",{className:"bg-card border rounded-lg p-6",children:[s.jsxs("h2",{className:"text-lg font-semibold mb-4",children:["Comments (",g.length,")"]}),s.jsxs("div",{className:"flex gap-3 mb-6",children:[s.jsx(mi,{placeholder:"Share your thoughts on this idea...",value:o,onChange:A=>c(A.target.value),rows:2,className:"flex-1"}),s.jsx(de,{onClick:P,disabled:!o.trim()||N.isPending,size:"icon",className:"h-auto",children:N.isPending?s.jsx(Ps,{className:"h-4 w-4 animate-spin"}):s.jsx(Dc,{className:"h-4 w-4"})})]}),_?s.jsx("div",{className:"space-y-4",children:[1,2].map(A=>s.jsx(Dn,{className:"h-20 w-full"},A))}):g.length===0?s.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No comments yet. Be the first to share your thoughts!"}):s.jsx("div",{className:"space-y-4",children:g.map(A=>s.jsxs("div",{className:"flex gap-3 p-3 bg-muted/30 rounded-lg",children:[s.jsx(ql,{className:"h-8 w-8",children:s.jsx(Hl,{className:"bg-primary/20 text-primary text-xs",children:A.user_initials})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx("span",{className:"font-medium text-sm",children:A.user_name}),s.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(A.created_at).toLocaleDateString()})]}),s.jsx("p",{className:"text-sm text-foreground",children:A.content})]}),(r==null?void 0:r.id)===A.user_id&&s.jsx(de,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground hover:text-destructive",onClick:()=>C.mutate(A.id),children:s.jsx(oi,{className:"h-4 w-4"})})]},A.id))})]})]})}):s.jsx(Jr,{title:"Wishlist",children:s.jsxs("div",{className:"max-w-3xl mx-auto text-center py-12",children:[s.jsx("p",{className:"text-muted-foreground",children:"Item not found"}),s.jsx(de,{variant:"link",onClick:()=>e("/wishlist"),children:"Go back to Wishlist"})]})})}const YJ={open:{label:"Open",color:"bg-blue-100 text-blue-800"},under_review:{label:"Under Review",color:"bg-yellow-100 text-yellow-800"},planned:{label:"Planned",color:"bg-purple-100 text-purple-800"},in_progress:{label:"In Progress",color:"bg-orange-100 text-orange-800"},launched:{label:"Launched",color:"bg-green-100 text-green-800"},declined:{label:"Declined",color:"bg-gray-100 text-gray-800"}},XJ=["open","under_review","planned","in_progress","launched","declined"];function M9e(){const{toast:t}=Ri(),e=Bs(),r=Wn(),[n,i]=D.useState(""),[o,c]=D.useState("all"),[a,m]=D.useState(!1),[g,_]=D.useState(null),{data:j=[],isLoading:N}=Sr({queryKey:["admin-wishlist-items"],queryFn:async()=>{const{data:O,error:R}=await ae.from("wishlist_items").select("*").order("vote_count",{ascending:!1});if(R)throw R;const z=[...new Set((O==null?void 0:O.map(X=>X.user_id))||[])],{data:W}=await ae.from("profiles").select("id, name, email").in("id",z),V=new Map((W==null?void 0:W.map(X=>[X.id,X]))||[]),K=(O==null?void 0:O.map(X=>X.id))||[],{data:Q}=await ae.from("wishlist_comments").select("item_id").in("item_id",K),te=new Map;return Q==null||Q.forEach(X=>{te.set(X.item_id,(te.get(X.item_id)||0)+1)}),O==null?void 0:O.map(X=>{const ie=V.get(X.user_id);return{...X,user_name:(ie==null?void 0:ie.name)||"Unknown",user_email:(ie==null?void 0:ie.email)||"",comment_count:te.get(X.id)||0}})}}),C=zr({mutationFn:async({itemId:O,status:R})=>{const{error:z}=await ae.from("wishlist_items").update({status:R}).eq("id",O);if(z)throw z},onSuccess:()=>{r.invalidateQueries({queryKey:["admin-wishlist-items"]}),t({title:"Status updated!"})},onError:O=>{t({title:"Error",description:O.message,variant:"destructive"})}}),P=zr({mutationFn:async O=>{const{error:R}=await ae.from("wishlist_items").delete().eq("id",O);if(R)throw R},onSuccess:()=>{r.invalidateQueries({queryKey:["admin-wishlist-items"]}),m(!1),_(null),t({title:"Item deleted!"})},onError:O=>{t({title:"Error",description:O.message,variant:"destructive"})}}),A=j.filter(O=>{const R=O.title.toLowerCase().includes(n.toLowerCase())||O.description.toLowerCase().includes(n.toLowerCase())||O.user_name.toLowerCase().includes(n.toLowerCase()),z=o==="all"||O.status===o;return R&&z}),I={total:j.length,open:j.filter(O=>O.status==="open").length,inProgress:j.filter(O=>O.status==="in_progress").length,launched:j.filter(O=>O.status==="launched").length,highVotes:j.filter(O=>O.vote_count>=10).length};return s.jsx(Jr,{title:"Admin - Wishlist",children:s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"flex items-center gap-4",children:[s.jsx(de,{variant:"ghost",size:"icon",onClick:()=>e("/admin"),children:s.jsx(Ka,{className:"h-5 w-5"})}),s.jsxs("div",{children:[s.jsx("h1",{className:"text-2xl font-bold",children:"Wishlist Management"}),s.jsx("p",{className:"text-muted-foreground",children:"Review and manage community ideas"})]})]}),s.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-4",children:[s.jsxs("div",{className:"bg-card border rounded-lg p-4",children:[s.jsx("p",{className:"text-sm text-muted-foreground",children:"Total Ideas"}),s.jsx("p",{className:"text-2xl font-bold",children:I.total})]}),s.jsxs("div",{className:"bg-card border rounded-lg p-4",children:[s.jsx("p",{className:"text-sm text-muted-foreground",children:"Open"}),s.jsx("p",{className:"text-2xl font-bold text-blue-600",children:I.open})]}),s.jsxs("div",{className:"bg-card border rounded-lg p-4",children:[s.jsx("p",{className:"text-sm text-muted-foreground",children:"In Progress"}),s.jsx("p",{className:"text-2xl font-bold text-orange-600",children:I.inProgress})]}),s.jsxs("div",{className:"bg-card border rounded-lg p-4",children:[s.jsx("p",{className:"text-sm text-muted-foreground",children:"Launched"}),s.jsx("p",{className:"text-2xl font-bold text-green-600",children:I.launched})]}),s.jsxs("div",{className:"bg-card border rounded-lg p-4",children:[s.jsx("p",{className:"text-sm text-muted-foreground",children:"10+ Votes"}),s.jsx("p",{className:"text-2xl font-bold text-primary",children:I.highVotes})]})]}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[s.jsxs("div",{className:"relative flex-1",children:[s.jsx(ba,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),s.jsx(Et,{placeholder:"Search ideas, users...",value:n,onChange:O=>i(O.target.value),className:"pl-10"})]}),s.jsxs(Kn,{value:o,onValueChange:O=>c(O),children:[s.jsx(qn,{className:"w-[180px]",children:s.jsx(Zn,{placeholder:"Filter by status"})}),s.jsxs(Hn,{children:[s.jsx(_r,{value:"all",children:"All Statuses"}),XJ.map(O=>s.jsx(_r,{value:O,children:YJ[O].label},O))]})]})]}),N?s.jsx("div",{className:"space-y-2",children:[1,2,3,4,5].map(O=>s.jsx(Dn,{className:"h-16 w-full"},O))}):s.jsx("div",{className:"bg-card border rounded-lg overflow-hidden",children:s.jsxs(ni,{children:[s.jsx(si,{children:s.jsxs(Dr,{children:[s.jsx(Nt,{className:"w-[60px]",children:"Votes"}),s.jsx(Nt,{children:"Title"}),s.jsx(Nt,{className:"hidden md:table-cell",children:"Submitted By"}),s.jsx(Nt,{className:"hidden sm:table-cell",children:"Comments"}),s.jsx(Nt,{children:"Status"}),s.jsx(Nt,{className:"w-[100px]",children:"Actions"})]})}),s.jsx(ii,{children:A.length===0?s.jsx(Dr,{children:s.jsx(xt,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No items found"})}):A.map(O=>s.jsxs(Dr,{className:ar(O.vote_count>=10&&"bg-primary/5"),children:[s.jsx(xt,{children:s.jsx(ir,{variant:O.vote_count>=10?"default":"secondary",children:O.vote_count})}),s.jsx(xt,{children:s.jsxs("div",{children:[s.jsx("p",{className:"font-medium line-clamp-1",children:O.title}),s.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:O.description})]})}),s.jsx(xt,{className:"hidden md:table-cell",children:s.jsxs("div",{children:[s.jsx("p",{className:"text-sm",children:O.user_name}),s.jsx("p",{className:"text-xs text-muted-foreground",children:O.user_email})]})}),s.jsx(xt,{className:"hidden sm:table-cell",children:O.comment_count}),s.jsx(xt,{children:s.jsxs(Kn,{value:O.status,onValueChange:R=>C.mutate({itemId:O.id,status:R}),children:[s.jsx(qn,{className:"w-[140px] h-8",children:s.jsx(Zn,{})}),s.jsx(Hn,{children:XJ.map(R=>s.jsx(_r,{value:R,children:YJ[R].label},R))})]})}),s.jsx(xt,{children:s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsx(de,{variant:"ghost",size:"icon",onClick:()=>window.open(`/wishlist/${O.id}`,"_blank"),children:s.jsx(oa,{className:"h-4 w-4"})}),s.jsx(de,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>{_(O.id),m(!0)},children:s.jsx(oi,{className:"h-4 w-4"})})]})})]},O.id))})]})}),s.jsx(mn,{open:a,onOpenChange:m,children:s.jsxs(pn,{children:[s.jsx(xn,{children:s.jsx(gn,{children:"Delete Wishlist Item"})}),s.jsx("p",{className:"text-muted-foreground",children:"Are you sure you want to delete this idea? This will also delete all votes and comments."}),s.jsxs("div",{className:"flex justify-end gap-2 mt-4",children:[s.jsx(de,{variant:"outline",onClick:()=>m(!1),children:"Cancel"}),s.jsx(de,{variant:"destructive",onClick:()=>g&&P.mutate(g),disabled:P.isPending,children:P.isPending?s.jsxs(s.Fragment,{children:[s.jsx(Ps,{className:"h-4 w-4 mr-2 animate-spin"}),"Deleting..."]}):"Delete"})]})]})})]})})}function O9e(){const{user:t}=rn(),[e,r]=D.useState([]),[n,i]=D.useState(!0),[o,c]=D.useState(!1),[a,m]=D.useState(null),[g,_]=D.useState(!1),[j,N]=D.useState(null),[C,P]=D.useState(""),[A,I]=D.useState(""),[O,R]=D.useState(""),[z,W]=D.useState(!1),[V,K]=D.useState(""),[Q,te]=D.useState("once"),[X,ie]=D.useState([]),[he,xe]=D.useState([]),[pe,ve]=D.useState(!1),[ge,ke]=D.useState([]),[Ce,Se]=D.useState({total:0,dismissed:0});D.useEffect(()=>{je()},[]);const je=async()=>{const{data:Lt,error:Kt}=await ae.from("levelup_briefs").select("*").order("created_at",{ascending:!1});Kt?(Dt.error("Failed to fetch briefs"),console.error(Kt)):r(Lt||[]),i(!1)},et=()=>{P(""),I(""),R(""),W(!1),K(new Date().toISOString().slice(0,16)),te("once"),ie([]),xe([]),m(null)},bt=()=>{et(),c(!0)},_e=async Lt=>{m(Lt),P(Lt.title),I(Lt.description||""),R(Lt.video_url||""),W(Lt.is_published),K(Lt.publish_date.slice(0,16)),te(Lt.show_frequency);const{data:Kt}=await ae.from("levelup_brief_links").select("*").eq("brief_id",Lt.id).order("sort_order");ie((Kt==null?void 0:Kt.map(rt=>({title:rt.title,url:rt.url})))||[]);const{data:Ar}=await ae.from("levelup_brief_polls").select("*").eq("brief_id",Lt.id).order("sort_order");if(Ar){const rt=[];for(const We of Ar){const{data:_t}=await ae.from("levelup_brief_poll_options").select("*").eq("poll_id",We.id).order("sort_order");rt.push({question:We.question,poll_type:We.poll_type,options:(_t==null?void 0:_t.map(Gt=>Gt.option_text))||[]})}xe(rt)}c(!0)},Ye=async Lt=>{var Ar;const Kt=(Ar=Lt.target.files)==null?void 0:Ar[0];if(Kt){ve(!0);try{const rt=await ae.functions.invoke("bunny-upload",{body:{action:"create",title:Kt.name.replace(/\.[^/.]+$/,"")}});if(rt.error)throw rt.error;const{videoId:We,libraryId:_t}=rt.data,Gt=await ae.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:We}});if(Gt.error)throw Gt.error;const{uploadUrl:rr,apiKey:pr}=Gt.data,kr=new XMLHttpRequest;await new Promise((Fn,Os)=>{kr.upload.addEventListener("progress",ia=>{if(ia.lengthComputable){const pa=Math.round(ia.loaded/ia.total*100);console.log("Upload progress:",pa)}}),kr.addEventListener("load",()=>{kr.status>=200&&kr.status<300?Fn():Os(new Error(`Upload failed with status ${kr.status}`))}),kr.addEventListener("error",()=>Os(new Error("Upload failed"))),kr.open("PUT",rr),kr.setRequestHeader("AccessKey",pr),kr.send(Kt)});const Hr=`https://player.mediadelivery.net/embed/${_t}/${We}`;R(Hr),Dt.success("Video uploaded successfully! It may take a few minutes to process.")}catch(rt){console.error("Upload error:",rt),Dt.error("Failed to upload video")}finally{ve(!1)}}},pt=async()=>{if(!C.trim()){Dt.error("Title is required");return}try{let Lt;if(a){const{error:Kt}=await ae.from("levelup_briefs").update({title:C,description:A||null,video_url:O||null,is_published:z,publish_date:V,show_frequency:Q}).eq("id",a.id);if(Kt)throw Kt;Lt=a.id,await ae.from("levelup_brief_links").delete().eq("brief_id",Lt);const{data:Ar}=await ae.from("levelup_brief_polls").select("id").eq("brief_id",Lt);if(Ar)for(const rt of Ar)await ae.from("levelup_brief_poll_options").delete().eq("poll_id",rt.id);await ae.from("levelup_brief_polls").delete().eq("brief_id",Lt)}else{const{data:Kt,error:Ar}=await ae.from("levelup_briefs").insert({title:C,description:A||null,video_url:O||null,is_published:z,publish_date:V,show_frequency:Q,created_by:t==null?void 0:t.id}).select().single();if(Ar)throw Ar;Lt=Kt.id}if(X.length>0){const Kt=X.map((Ar,rt)=>({brief_id:Lt,title:Ar.title,url:Ar.url,sort_order:rt}));await ae.from("levelup_brief_links").insert(Kt)}for(let Kt=0;Kt0){const _t=Ar.options.map((Gt,rr)=>({poll_id:rt.id,option_text:Gt,sort_order:rr}));await ae.from("levelup_brief_poll_options").insert(_t)}}Dt.success(a?"Brief updated":"Brief created"),c(!1),et(),je()}catch(Lt){console.error("Error saving brief:",Lt),Dt.error("Failed to save brief")}},nt=async Lt=>{if(confirm("Are you sure you want to delete this brief?"))try{const{error:Kt}=await ae.from("levelup_briefs").delete().eq("id",Lt);if(Kt)throw Kt;Dt.success("Brief deleted"),je()}catch(Kt){console.error("Error deleting brief:",Kt),Dt.error("Failed to delete brief")}},Qt=async Lt=>{N(Lt);const{count:Kt}=await ae.from("levelup_brief_views").select("*",{count:"exact",head:!0}).eq("brief_id",Lt.id),{count:Ar}=await ae.from("levelup_brief_views").select("*",{count:"exact",head:!0}).eq("brief_id",Lt.id).not("dismissed_at","is",null);Se({total:Kt||0,dismissed:Ar||0});const{data:rt}=await ae.from("levelup_brief_polls").select("*").eq("brief_id",Lt.id).order("sort_order");if(rt){const We=[];for(const _t of rt){const{data:Gt}=await ae.from("levelup_brief_poll_options").select("*").eq("poll_id",_t.id).order("sort_order"),{data:rr}=await ae.from("levelup_brief_poll_responses").select("option_id").eq("poll_id",_t.id),pr={};let kr=0;Gt&&Gt.forEach(Hr=>{const Fn=(rr==null?void 0:rr.filter(Os=>Os.option_id===Hr.id).length)||0;pr[Hr.id]=Fn,kr+=Fn}),We.push({..._t,options:Gt||[],results:pr,totalResponses:_t.poll_type==="single"?new Set(rr==null?void 0:rr.map(Hr=>Hr.option_id)).size:kr})}ke(We)}_(!0)},gt=()=>{ie([...X,{title:"",url:""}])},Me=(Lt,Kt,Ar)=>{const rt=[...X];rt[Lt][Kt]=Ar,ie(rt)},Oe=Lt=>{ie(X.filter((Kt,Ar)=>Ar!==Lt))},Ie=()=>{xe([...he,{question:"",poll_type:"single",options:["",""]}])},Be=(Lt,Kt)=>{const Ar=[...he];Ar[Lt].question=Kt,xe(Ar)},Pe=(Lt,Kt)=>{const Ar=[...he];Ar[Lt].poll_type=Kt,xe(Ar)},ut=Lt=>{const Kt=[...he];Kt[Lt].options.push(""),xe(Kt)},jt=(Lt,Kt,Ar)=>{const rt=[...he];rt[Lt].options[Kt]=Ar,xe(rt)},$t=(Lt,Kt)=>{const Ar=[...he];Ar[Lt].options=Ar[Lt].options.filter((rt,We)=>We!==Kt),xe(Ar)},Ht=Lt=>{xe(he.filter((Kt,Ar)=>Ar!==Lt))};return s.jsxs(Jr,{title:"The LevelUp Brief",children:[s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsxs("h1",{className:"text-2xl font-bold text-foreground flex items-center gap-2",children:[s.jsx(mT,{className:"h-6 w-6"}),"The LevelUp Brief"]}),s.jsx("p",{className:"text-muted-foreground",children:"Create engaging popup briefs for your agents"})]}),s.jsxs(de,{onClick:bt,children:[s.jsx(Qn,{className:"h-4 w-4 mr-2"}),"Create Brief"]})]}),s.jsx(at,{children:s.jsx(ct,{className:"p-0",children:s.jsxs(ni,{children:[s.jsx(si,{children:s.jsxs(Dr,{children:[s.jsx(Nt,{children:"Title"}),s.jsx(Nt,{children:"Status"}),s.jsx(Nt,{children:"Frequency"}),s.jsx(Nt,{children:"Publish Date"}),s.jsx(Nt,{className:"text-right",children:"Actions"})]})}),s.jsx(ii,{children:n?s.jsx(Dr,{children:s.jsx(xt,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):e.length===0?s.jsx(Dr,{children:s.jsx(xt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No briefs created yet"})}):e.map(Lt=>s.jsxs(Dr,{children:[s.jsx(xt,{className:"font-medium",children:Lt.title}),s.jsx(xt,{children:s.jsx(ir,{variant:Lt.is_published?"default":"secondary",children:Lt.is_published?"Published":"Draft"})}),s.jsx(xt,{className:"capitalize",children:Lt.show_frequency.replace("_"," ")}),s.jsx(xt,{children:Vn(new Date(Lt.publish_date),"MMM d, yyyy h:mm a")}),s.jsx(xt,{className:"text-right",children:s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(de,{variant:"ghost",size:"icon",onClick:()=>Qt(Lt),children:s.jsx(_p,{className:"h-4 w-4"})}),s.jsx(de,{variant:"ghost",size:"icon",onClick:()=>_e(Lt),children:s.jsx(P_,{className:"h-4 w-4"})}),s.jsx(de,{variant:"ghost",size:"icon",onClick:()=>nt(Lt.id),children:s.jsx(oi,{className:"h-4 w-4 text-destructive"})})]})})]},Lt.id))})]})})})]}),s.jsx(mn,{open:o,onOpenChange:c,children:s.jsxs(pn,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[s.jsx(xn,{children:s.jsx(gn,{children:a?"Edit Brief":"Create New Brief"})}),s.jsxs(go,{defaultValue:"content",className:"w-full",children:[s.jsxs(ao,{className:"grid w-full grid-cols-4",children:[s.jsx(Bn,{value:"content",children:"Content"}),s.jsx(Bn,{value:"video",children:"Video"}),s.jsx(Bn,{value:"links",children:"Links"}),s.jsx(Bn,{value:"polls",children:"Polls"})]}),s.jsxs(xs,{value:"content",className:"space-y-4 mt-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Title *"}),s.jsx(Et,{value:C,onChange:Lt=>P(Lt.target.value),placeholder:"What's happening at LevelUp..."})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Description"}),s.jsx(ag,{content:A,onChange:Lt=>I(Lt),placeholder:"Brief overview for agents...",minHeight:"120px"})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Publish Date"}),s.jsx(Et,{type:"datetime-local",value:V,onChange:Lt=>K(Lt.target.value)})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Show Frequency"}),s.jsxs(Kn,{value:Q,onValueChange:te,children:[s.jsx(qn,{children:s.jsx(Zn,{})}),s.jsxs(Hn,{children:[s.jsx(_r,{value:"once",children:"Once (until dismissed)"}),s.jsx(_r,{value:"every_login",children:"Every login"}),s.jsx(_r,{value:"daily",children:"Daily"})]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(ri,{checked:z,onCheckedChange:W}),s.jsx(mt,{children:"Publish immediately"})]})]}),s.jsxs(xs,{value:"video",className:"space-y-4 mt-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Upload Video to Bunny.net"}),s.jsx("div",{className:"flex gap-2",children:s.jsx(Et,{type:"file",accept:"video/*",onChange:Ye,disabled:pe})}),pe&&s.jsx("p",{className:"text-sm text-muted-foreground",children:"Uploading..."})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Or paste embed URL"}),s.jsx(Et,{value:O,onChange:Lt=>R(Lt.target.value),placeholder:"https://iframe.mediadelivery.net/embed/..."})]}),O&&s.jsx("div",{className:"aspect-video rounded-lg overflow-hidden bg-muted",children:s.jsx("iframe",{src:O,className:"w-full h-full",allow:"autoplay; fullscreen",allowFullScreen:!0})})]}),s.jsxs(xs,{value:"links",className:"space-y-4 mt-4",children:[s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsx(mt,{children:"Quick Links"}),s.jsxs(de,{variant:"outline",size:"sm",onClick:gt,children:[s.jsx(Qn,{className:"h-4 w-4 mr-1"}),"Add Link"]})]}),X.map((Lt,Kt)=>s.jsxs("div",{className:"flex gap-2 items-start",children:[s.jsx(Et,{value:Lt.title,onChange:Ar=>Me(Kt,"title",Ar.target.value),placeholder:"Link title",className:"flex-1"}),s.jsx(Et,{value:Lt.url,onChange:Ar=>Me(Kt,"url",Ar.target.value),placeholder:"https://...",className:"flex-[2]"}),s.jsx(de,{variant:"ghost",size:"icon",onClick:()=>Oe(Kt),children:s.jsx(oi,{className:"h-4 w-4 text-destructive"})})]},Kt)),X.length===0&&s.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No links added yet"})]}),s.jsxs(xs,{value:"polls",className:"space-y-4 mt-4",children:[s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsx(mt,{children:"Polls"}),s.jsxs(de,{variant:"outline",size:"sm",onClick:Ie,children:[s.jsx(Qn,{className:"h-4 w-4 mr-1"}),"Add Poll"]})]}),he.map((Lt,Kt)=>s.jsx(at,{className:"p-4",children:s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsx(Et,{value:Lt.question,onChange:Ar=>Be(Kt,Ar.target.value),placeholder:"Poll question...",className:"flex-1 mr-2"}),s.jsxs(Kn,{value:Lt.poll_type,onValueChange:Ar=>Pe(Kt,Ar),children:[s.jsx(qn,{className:"w-32",children:s.jsx(Zn,{})}),s.jsxs(Hn,{children:[s.jsx(_r,{value:"single",children:"Single"}),s.jsx(_r,{value:"multi",children:"Multi-select"})]})]}),s.jsx(de,{variant:"ghost",size:"icon",onClick:()=>Ht(Kt),children:s.jsx(oi,{className:"h-4 w-4 text-destructive"})})]}),s.jsxs("div",{className:"space-y-2 pl-4",children:[Lt.options.map((Ar,rt)=>s.jsxs("div",{className:"flex gap-2",children:[s.jsx(Et,{value:Ar,onChange:We=>jt(Kt,rt,We.target.value),placeholder:`Option ${rt+1}`}),Lt.options.length>2&&s.jsx(de,{variant:"ghost",size:"icon",onClick:()=>$t(Kt,rt),children:s.jsx(oi,{className:"h-4 w-4 text-muted-foreground"})})]},rt)),s.jsxs(de,{variant:"ghost",size:"sm",onClick:()=>ut(Kt),children:[s.jsx(Qn,{className:"h-4 w-4 mr-1"}),"Add Option"]})]})]})},Kt)),he.length===0&&s.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No polls added yet"})]})]}),s.jsxs("div",{className:"flex justify-end gap-2 mt-4",children:[s.jsx(de,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),s.jsx(de,{onClick:pt,children:a?"Update Brief":"Create Brief"})]})]})}),s.jsx(mn,{open:g,onOpenChange:_,children:s.jsxs(pn,{className:"max-w-2xl",children:[s.jsx(xn,{children:s.jsxs(gn,{children:["Results: ",j==null?void 0:j.title]})}),s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsxs(at,{children:[s.jsx(xr,{className:"pb-2",children:s.jsx(wr,{className:"text-sm font-medium text-muted-foreground",children:"Total Views"})}),s.jsx(ct,{children:s.jsx("p",{className:"text-2xl font-bold",children:Ce.total})})]}),s.jsxs(at,{children:[s.jsx(xr,{className:"pb-2",children:s.jsx(wr,{className:"text-sm font-medium text-muted-foreground",children:"Dismissed"})}),s.jsx(ct,{children:s.jsx("p",{className:"text-2xl font-bold",children:Ce.dismissed})})]})]}),ge.length>0?s.jsxs("div",{className:"space-y-4",children:[s.jsx("h3",{className:"font-semibold",children:"Poll Results"}),ge.map(Lt=>s.jsxs(at,{className:"p-4",children:[s.jsx("h4",{className:"font-medium mb-3",children:Lt.question}),s.jsx("div",{className:"space-y-2",children:Lt.options.map(Kt=>{const Ar=Lt.results[Kt.id]||0,rt=Lt.totalResponses>0?Math.round(Ar/Lt.totalResponses*100):0;return s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"flex justify-between text-sm",children:[s.jsx("span",{children:Kt.option_text}),s.jsxs("span",{className:"text-muted-foreground",children:[Ar," (",rt,"%)"]})]}),s.jsx("div",{className:"h-2 bg-muted rounded-full overflow-hidden",children:s.jsx("div",{className:"h-full bg-primary transition-all",style:{width:`${rt}%`}})})]},Kt.id)})})]},Lt.id))]}):s.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No polls in this brief"})]})]})})]})}const R9e=()=>{const{user:t}=rn(),{toast:e}=Ri(),r=Wn(),[n,i]=D.useState(!1),[o,c]=D.useState(null),[a,m]=D.useState({name:"",description:"",signup_link_url:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),[g,_]=D.useState(null),[j,N]=D.useState(""),{data:C=[],isLoading:P}=Sr({queryKey:["additional-services-admin"],queryFn:async()=>{const{data:V,error:K}=await ae.from("additional_services").select("*").order("publish_date",{ascending:!1});if(K)throw K;return V}}),A=zr({mutationFn:async V=>{let K=V.existingImageUrl;if(V.image){const te=V.image.name.split(".").pop(),X=`${Date.now()}-${Math.random().toString(36).substring(7)}.${te}`,{error:ie}=await ae.storage.from("service-images").upload(X,V.image);if(ie)throw ie;const{data:he}=ae.storage.from("service-images").getPublicUrl(X);K=he.publicUrl}const Q={name:V.item.name,description:V.item.description||null,preview_image_url:K,signup_link_url:V.item.signup_link_url,publish_date:V.item.publish_date?new Date(V.item.publish_date).toISOString():new Date().toISOString(),is_published:V.item.is_published,created_by:t==null?void 0:t.id};if(V.itemId){const{error:te}=await ae.from("additional_services").update(Q).eq("id",V.itemId);if(te)throw te}else{const{error:te}=await ae.from("additional_services").insert(Q);if(te)throw te}},onSuccess:()=>{r.invalidateQueries({queryKey:["additional-services-admin"]}),r.invalidateQueries({queryKey:["additional-services"]}),e({title:o?"Service updated":"Service created"}),i(!1),O()},onError:V=>{e({title:"Error saving service",description:V.message,variant:"destructive"})}}),I=zr({mutationFn:async V=>{const{error:K}=await ae.from("additional_services").delete().eq("id",V);if(K)throw K},onSuccess:()=>{r.invalidateQueries({queryKey:["additional-services-admin"]}),r.invalidateQueries({queryKey:["additional-services"]}),e({title:"Service deleted"})},onError:V=>{e({title:"Error deleting service",description:V.message,variant:"destructive"})}}),O=()=>{m({name:"",description:"",signup_link_url:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),_(null),N(""),c(null)},R=V=>{c(V),m({name:V.name,description:V.description||"",signup_link_url:V.signup_link_url,publish_date:V.publish_date?new Date(V.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],is_published:V.is_published}),N(V.preview_image_url||""),i(!0)},z=V=>{var Q;const K=(Q=V.target.files)==null?void 0:Q[0];K&&(_(K),N(URL.createObjectURL(K)))},W=V=>{if(V.preventDefault(),!a.name.trim()){e({title:"Name is required",variant:"destructive"});return}if(!a.signup_link_url.trim()){e({title:"Signup link URL is required",variant:"destructive"});return}A.mutate({item:a,image:g,existingImageUrl:(o==null?void 0:o.preview_image_url)||null,itemId:o==null?void 0:o.id})};return s.jsx(Jr,{title:"Manage Additional Services",children:s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsxs(at,{children:[s.jsx(xr,{className:"pb-2",children:s.jsx(wr,{className:"text-sm font-medium text-muted-foreground",children:"Total Services"})}),s.jsx(ct,{children:s.jsx("div",{className:"text-2xl font-bold",children:C.length})})]}),s.jsxs(at,{children:[s.jsx(xr,{className:"pb-2",children:s.jsx(wr,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),s.jsx(ct,{children:s.jsx("div",{className:"text-2xl font-bold",children:C.filter(V=>V.is_published).length})})]})]}),s.jsxs(mn,{open:n,onOpenChange:V=>{i(V),V||O()},children:[s.jsx(Do,{asChild:!0,children:s.jsxs(de,{className:"gap-2",children:[s.jsx(Qn,{className:"h-4 w-4"}),"Add Service"]})}),s.jsxs(pn,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[s.jsx(xn,{children:s.jsx(gn,{children:o?"Edit Service":"Add New Service"})}),s.jsxs("form",{onSubmit:W,className:"space-y-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"name",children:"Name *"}),s.jsx(Et,{id:"name",value:a.name,onChange:V=>m({...a,name:V.target.value}),placeholder:"Enter service name"})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Description"}),s.jsx(ag,{content:a.description,onChange:V=>m({...a,description:V}),placeholder:"Enter description",minHeight:"120px"})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"signup_link_url",children:"Signup Link URL *"}),s.jsx(Et,{id:"signup_link_url",type:"url",value:a.signup_link_url,onChange:V=>m({...a,signup_link_url:V.target.value}),placeholder:"https://example.com/signup"})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"publish_date",children:"Publish Date"}),s.jsx(Et,{id:"publish_date",type:"date",value:a.publish_date,onChange:V=>m({...a,publish_date:V.target.value})})]}),s.jsxs("div",{className:"flex items-center space-x-2",children:[s.jsx(ri,{id:"is_published",checked:a.is_published,onCheckedChange:V=>m({...a,is_published:V})}),s.jsx(mt,{htmlFor:"is_published",children:"Published"})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Preview Image"}),j?s.jsxs("div",{className:"relative",children:[s.jsx("img",{src:j,alt:"Preview",className:"w-full max-h-48 object-contain rounded-lg border"}),s.jsx(de,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:()=>{_(null),N("")},children:s.jsx(Ni,{className:"h-3 w-3"})})]}):s.jsxs("div",{className:"border-2 border-dashed rounded-lg p-4 text-center",children:[s.jsx(Wm,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),s.jsx(Et,{type:"file",accept:"image/*",onChange:z,className:"cursor-pointer"})]})]}),s.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[s.jsx(de,{type:"button",variant:"outline",onClick:()=>i(!1),children:"Cancel"}),s.jsx(de,{type:"submit",disabled:A.isPending,children:A.isPending?"Saving...":o?"Update":"Create"})]})]})]})]})]}),s.jsx(at,{children:s.jsx(ct,{className:"p-0",children:P?s.jsx("div",{className:"flex justify-center py-8",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):C.length===0?s.jsx("div",{className:"text-center py-8 text-muted-foreground",children:'No services yet. Click "Add Service" to create your first one.'}):s.jsxs(ni,{children:[s.jsx(si,{children:s.jsxs(Dr,{children:[s.jsx(Nt,{className:"w-16",children:"Preview"}),s.jsx(Nt,{children:"Name"}),s.jsx(Nt,{children:"Signup Link"}),s.jsx(Nt,{children:"Publish Date"}),s.jsx(Nt,{children:"Status"}),s.jsx(Nt,{className:"text-right",children:"Actions"})]})}),s.jsx(ii,{children:C.map(V=>s.jsxs(Dr,{children:[s.jsx(xt,{children:V.preview_image_url?s.jsx("img",{src:V.preview_image_url,alt:"",className:"w-12 h-12 object-cover rounded"}):s.jsx("div",{className:"w-12 h-12 bg-muted rounded flex items-center justify-center",children:s.jsx(Wm,{className:"h-5 w-5 text-muted-foreground"})})}),s.jsx(xt,{className:"font-medium",children:V.name}),s.jsx(xt,{children:s.jsxs("a",{href:V.signup_link_url,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline flex items-center gap-1",children:[s.jsx(oa,{className:"h-3 w-3"}),"Link"]})}),s.jsx(xt,{children:new Date(V.publish_date).toLocaleDateString()}),s.jsx(xt,{children:s.jsx(ir,{variant:V.is_published?"default":"secondary",children:V.is_published?"Published":"Draft"})}),s.jsx(xt,{className:"text-right",children:s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(de,{variant:"ghost",size:"icon",onClick:()=>R(V),children:s.jsx(io,{className:"h-4 w-4"})}),s.jsx(de,{variant:"ghost",size:"icon",onClick:()=>{confirm("Are you sure you want to delete this service?")&&I.mutate(V.id)},children:s.jsx(oi,{className:"h-4 w-4 text-destructive"})})]})})]},V.id))})]})})})]})})};function D9e(){const{toast:t}=Ri(),[e,r]=D.useState([]),[n,i]=D.useState(!0),[o,c]=D.useState(!1),[a,m]=D.useState(!1),[g,_]=D.useState({name:"",promotionCode:"",discountType:"percent",percentOff:"",amountOff:"",duration:"once",durationInMonths:""});D.useEffect(()=>{j()},[]);const j=async()=>{try{const{data:I,error:O}=await ae.functions.invoke("stripe-manage-coupons",{body:{action:"list"}});if(O)throw O;r(I.coupons||[])}catch(I){console.error("Error fetching coupons:",I),t({title:"Error",description:"Failed to load coupons",variant:"destructive"})}finally{i(!1)}},N=async()=>{if(!g.name){t({title:"Error",description:"Please enter a coupon name",variant:"destructive"});return}if(g.discountType==="percent"&&!g.percentOff){t({title:"Error",description:"Please enter a percent off value",variant:"destructive"});return}if(g.discountType==="amount"&&!g.amountOff){t({title:"Error",description:"Please enter an amount off value",variant:"destructive"});return}if(g.duration==="repeating"&&!g.durationInMonths){t({title:"Error",description:"Please enter duration in months",variant:"destructive"});return}c(!0);try{const I={action:"create",name:g.name,duration:g.duration,promotion_code:g.promotionCode.trim()||void 0};g.discountType==="percent"?I.percent_off=parseFloat(g.percentOff):(I.amount_off=Math.round(parseFloat(g.amountOff)*100),I.currency="usd"),g.duration==="repeating"&&(I.duration_in_months=parseInt(g.durationInMonths));const{data:O,error:R}=await ae.functions.invoke("stripe-manage-coupons",{body:I});if(R)throw R;t({title:"Success",description:"Coupon created successfully"}),m(!1),_({name:"",promotionCode:"",discountType:"percent",percentOff:"",amountOff:"",duration:"once",durationInMonths:""}),j()}catch(I){console.error("Error creating coupon:",I),t({title:"Error",description:I.message||"Failed to create coupon",variant:"destructive"})}finally{c(!1)}},C=async I=>{if(confirm("Are you sure you want to delete this coupon?"))try{const{error:O}=await ae.functions.invoke("stripe-manage-coupons",{body:{action:"delete",couponId:I}});if(O)throw O;t({title:"Success",description:"Coupon deleted successfully"}),j()}catch(O){console.error("Error deleting coupon:",O),t({title:"Error",description:O.message||"Failed to delete coupon",variant:"destructive"})}},P=I=>I.percent_off?`${I.percent_off}% off`:I.amount_off?`$${(I.amount_off/100).toFixed(2)} off`:"N/A",A=I=>{switch(I.duration){case"once":return"Once";case"forever":return"Forever";case"repeating":return`${I.duration_in_months} months`;default:return I.duration}};return s.jsx(Jr,{title:"Subscription Discounts",children:s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Subscription Discounts"}),s.jsx("p",{className:"text-muted-foreground",children:"Create and manage discount coupons for subscriptions"})]}),s.jsxs(mn,{open:a,onOpenChange:m,children:[s.jsx(Do,{asChild:!0,children:s.jsxs(de,{children:[s.jsx(Qn,{className:"mr-2 h-4 w-4"}),"Create Coupon"]})}),s.jsxs(pn,{children:[s.jsxs(xn,{children:[s.jsx(gn,{children:"Create New Coupon"}),s.jsx(fi,{children:"Create a discount coupon that can be applied to subscriptions"})]}),s.jsxs("div",{className:"space-y-4 pt-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Promotion Code (what users will type)"}),s.jsx(Et,{placeholder:"e.g., BROKERAGE50",value:g.promotionCode,onChange:I=>_({...g,promotionCode:I.target.value.toUpperCase().replace(/[^A-Z0-9]/g,"")}),className:"font-mono uppercase"}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Letters and numbers only. This is the code users enter at checkout."})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Coupon Name (internal label)"}),s.jsx(Et,{placeholder:"e.g., 50% Off Brokerage Launch",value:g.name,onChange:I=>_({...g,name:I.target.value})})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Discount Type"}),s.jsxs(Kn,{value:g.discountType,onValueChange:I=>{const O=I==="amount"&&g.duration==="forever"?"once":g.duration;_({...g,discountType:I,duration:O})},children:[s.jsx(qn,{children:s.jsx(Zn,{})}),s.jsxs(Hn,{children:[s.jsx(_r,{value:"percent",children:s.jsxs("span",{className:"flex items-center",children:[s.jsx(z2e,{className:"mr-2 h-4 w-4"}),"Percentage Off"]})}),s.jsx(_r,{value:"amount",children:s.jsxs("span",{className:"flex items-center",children:[s.jsx(M1,{className:"mr-2 h-4 w-4"}),"Fixed Amount Off"]})})]})]})]}),g.discountType==="percent"?s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Percent Off"}),s.jsxs("div",{className:"relative",children:[s.jsx(Et,{type:"number",min:"1",max:"100",placeholder:"20",value:g.percentOff,onChange:I=>_({...g,percentOff:I.target.value})}),s.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground",children:"%"})]})]}):s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Amount Off (USD)"}),s.jsxs("div",{className:"relative",children:[s.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground",children:"$"}),s.jsx(Et,{type:"number",min:"1",placeholder:"10.00",className:"pl-7",value:g.amountOff,onChange:I=>_({...g,amountOff:I.target.value})})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Duration"}),s.jsxs(Kn,{value:g.duration,onValueChange:I=>_({...g,duration:I}),children:[s.jsx(qn,{children:s.jsx(Zn,{})}),s.jsxs(Hn,{children:[s.jsx(_r,{value:"once",children:"Once (first payment only)"}),s.jsx(_r,{value:"repeating",children:"Multiple months"}),s.jsxs(_r,{value:"forever",disabled:g.discountType==="amount",children:["Forever ",g.discountType==="amount"&&"(% discounts only)"]})]})]}),g.discountType==="amount"&&s.jsx("p",{className:"text-xs text-muted-foreground",children:'Note: "Forever" duration is only available for percentage-based discounts.'})]}),g.duration==="repeating"&&s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Number of Months"}),s.jsx(Et,{type:"number",min:"1",placeholder:"3",value:g.durationInMonths,onChange:I=>_({...g,durationInMonths:I.target.value})})]}),s.jsx(de,{onClick:N,disabled:o,className:"w-full",children:o?s.jsxs(s.Fragment,{children:[s.jsx(Ps,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):"Create Coupon"})]})]})]})]}),s.jsxs(at,{children:[s.jsxs(xr,{children:[s.jsx(wr,{children:"Active Coupons"}),s.jsx(us,{children:"Share coupon codes with users to give them discounts on subscriptions"})]}),s.jsx(ct,{children:n?s.jsx("div",{className:"flex items-center justify-center py-8",children:s.jsx(Ps,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.length===0?s.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No coupons created yet. Create your first coupon to get started."}):s.jsxs(ni,{children:[s.jsx(si,{children:s.jsxs(Dr,{children:[s.jsx(Nt,{children:"Promo Code"}),s.jsx(Nt,{children:"Name"}),s.jsx(Nt,{children:"Discount"}),s.jsx(Nt,{children:"Duration"}),s.jsx(Nt,{children:"Redemptions"}),s.jsx(Nt,{children:"Status"}),s.jsx(Nt,{className:"text-right",children:"Actions"})]})}),s.jsx(ii,{children:e.map(I=>{var O;return s.jsxs(Dr,{children:[s.jsx(xt,{className:"font-mono font-medium",children:((O=I.promotion_codes)==null?void 0:O.length)>0?I.promotion_codes.join(", "):s.jsx("span",{className:"text-muted-foreground text-xs",children:"No promo code"})}),s.jsx(xt,{children:I.name||"-"}),s.jsx(xt,{children:P(I)}),s.jsx(xt,{children:A(I)}),s.jsx(xt,{children:I.times_redeemed}),s.jsx(xt,{children:s.jsx(ir,{variant:I.valid?"default":"secondary",children:I.valid?"Active":"Inactive"})}),s.jsx(xt,{className:"text-right",children:s.jsx(de,{variant:"ghost",size:"sm",onClick:()=>C(I.id),children:s.jsx(oi,{className:"h-4 w-4 text-destructive"})})})]},I.id)})})]})})]}),s.jsxs(at,{children:[s.jsx(xr,{children:s.jsx(wr,{children:"How to Use Coupons"})}),s.jsxs(ct,{className:"text-sm text-muted-foreground space-y-2",children:[s.jsx("p",{children:"1. Create a coupon above with your desired discount."}),s.jsx("p",{children:'2. Share the coupon code (shown in the "Code" column) with users.'}),s.jsx("p",{children:"3. Users can enter the code during checkout to receive the discount."}),s.jsx("p",{children:"4. Alternatively, you can create a promotion code in Stripe dashboard for public-facing promotions."})]})]})]})})}const Zz={prod_Tc07cYplXUGNkm:{name:"Individual Agent",price:"$39/mo",type:"individual"},prod_Tc08MupgoVySDG:{name:"Brokerage (Under 25)",price:"$299/mo",type:"brokerage"},prod_Tc09N1tJ4RrAFn:{name:"Brokerage (Over 25)",price:"$499/mo",type:"brokerage"}};function L9e(){const[t,e]=D.useState(""),[r,n]=D.useState("all"),[i,o]=D.useState(null),{data:c,isLoading:a,refetch:m}=Sr({queryKey:["admin-subscriptions"],queryFn:async()=>{const{data:P,error:A}=await ae.from("profiles").select(` *, brokerages:brokerage_id (id, name) `).order("created_at",{ascending:!1});if(A)throw A;return P}}),{data:g}=Sr({queryKey:["admin-brokerages-subscriptions"],queryFn:async()=>{const{data:P,error:A}=await ae.from("brokerages").select("*").order("name");if(A)throw A;return await Promise.all((P||[]).map(async O=>{const{data:R}=await ae.from("profiles").select("id, name, email, subscription_status, subscription_product_id").eq("brokerage_id",O.id),{data:z}=await ae.from("user_roles").select("user_id").eq("role","brokerage_manager"),W=(z==null?void 0:z.map(Q=>Q.user_id))||[],V=(R==null?void 0:R.filter(Q=>W.includes(Q.id)))||[],K=(R==null?void 0:R.length)||0;return{...O,managers:V,agentCount:K}}))}}),_=P=>{if(P.is_grandfathered)return{status:"Grandfathered",badge:"Legacy",variant:"secondary"};if(P.brokerage_id&&!P.subscription_product_id)return{status:"Brokerage",badge:"Team Member",variant:"outline"};if(P.is_trial&&P.trial_expires_at)return new Date(P.trial_expires_at)>new Date?{status:"Trial",badge:"Active Trial",variant:"default"}:{status:"Trial Expired",badge:"Expired",variant:"destructive"};if(P.subscription_status==="active"||P.subscription_status==="trialing"){const A=Zz[P.subscription_product_id];return{status:(A==null?void 0:A.name)||"Active",badge:P.subscription_status==="trialing"?"Trial":"Active",variant:"default"}}return P.subscription_status==="canceled"||P.subscription_status==="past_due"?{status:"Canceled",badge:"Inactive",variant:"destructive"}:{status:"None",badge:"No Subscription",variant:"outline"}},j=c==null?void 0:c.filter(P=>{var I,O;if(!(((I=P.name)==null?void 0:I.toLowerCase().includes(t.toLowerCase()))||((O=P.email)==null?void 0:O.toLowerCase().includes(t.toLowerCase()))))return!1;switch(_(P),r){case"active":return P.subscription_status==="active";case"trialing":return P.subscription_status==="trialing"||P.is_trial&&new Date(P.trial_expires_at)>new Date;case"grandfathered":return P.is_grandfathered;case"brokerage":return P.brokerage_id&&!P.subscription_product_id&&!P.is_grandfathered;case"expired":return P.subscription_status==="canceled"||P.subscription_status==="past_due"||P.is_trial&&new Date(P.trial_expires_at)<=new Date;case"none":return!P.subscription_status||P.subscription_status==="none";default:return!0}}),N={totalUsers:(c==null?void 0:c.length)||0,activeSubscriptions:(c==null?void 0:c.filter(P=>P.subscription_status==="active").length)||0,trials:(c==null?void 0:c.filter(P=>P.subscription_status==="trialing"||P.is_trial&&new Date(P.trial_expires_at)>new Date).length)||0,grandfathered:(c==null?void 0:c.filter(P=>P.is_grandfathered).length)||0,brokerageMembers:(c==null?void 0:c.filter(P=>P.brokerage_id&&!P.subscription_product_id&&!P.is_grandfathered).length)||0,individualSubscribers:(c==null?void 0:c.filter(P=>P.subscription_status==="active"&&P.subscription_product_id==="prod_Tc07cYplXUGNkm").length)||0,brokerageSubscribers:(c==null?void 0:c.filter(P=>P.subscription_status==="active"&&(P.subscription_product_id==="prod_Tc08MupgoVySDG"||P.subscription_product_id==="prod_Tc09N1tJ4RrAFn")).length)||0},C=P=>{window.open(`https://dashboard.stripe.com/customers/${P}`,"_blank")};return s.jsx(Jr,{title:"Subscription Management",children:s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("h1",{className:"text-2xl font-bold",children:"Subscription Management"}),s.jsx("p",{className:"text-muted-foreground",children:"Track and manage all subscriptions"})]}),s.jsxs(de,{onClick:()=>m(),variant:"outline",size:"sm",children:[s.jsx(R1,{className:"h-4 w-4 mr-2"}),"Refresh"]})]}),s.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-7 gap-4",children:[s.jsx(at,{children:s.jsxs(ct,{className:"pt-4",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(_i,{className:"h-4 w-4 text-muted-foreground"}),s.jsx("span",{className:"text-sm text-muted-foreground",children:"Total Users"})]}),s.jsx("p",{className:"text-2xl font-bold mt-1",children:N.totalUsers})]})}),s.jsx(at,{className:"border-green-500/50",children:s.jsxs(ct,{className:"pt-4",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(fM,{className:"h-4 w-4 text-green-500"}),s.jsx("span",{className:"text-sm text-muted-foreground",children:"Active Paid"})]}),s.jsx("p",{className:"text-2xl font-bold mt-1 text-green-600",children:N.activeSubscriptions})]})}),s.jsx(at,{className:"border-blue-500/50",children:s.jsxs(ct,{className:"pt-4",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(No,{className:"h-4 w-4 text-blue-500"}),s.jsx("span",{className:"text-sm text-muted-foreground",children:"Trials"})]}),s.jsx("p",{className:"text-2xl font-bold mt-1 text-blue-600",children:N.trials})]})}),s.jsx(at,{className:"border-purple-500/50",children:s.jsxs(ct,{className:"pt-4",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(G6,{className:"h-4 w-4 text-purple-500"}),s.jsx("span",{className:"text-sm text-muted-foreground",children:"Grandfathered"})]}),s.jsx("p",{className:"text-2xl font-bold mt-1 text-purple-600",children:N.grandfathered})]})}),s.jsx(at,{className:"border-orange-500/50",children:s.jsxs(ct,{className:"pt-4",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(yc,{className:"h-4 w-4 text-orange-500"}),s.jsx("span",{className:"text-sm text-muted-foreground",children:"Brokerage Members"})]}),s.jsx("p",{className:"text-2xl font-bold mt-1 text-orange-600",children:N.brokerageMembers})]})}),s.jsx(at,{children:s.jsxs(ct,{className:"pt-4",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Coe,{className:"h-4 w-4 text-muted-foreground"}),s.jsx("span",{className:"text-sm text-muted-foreground",children:"Individual"})]}),s.jsx("p",{className:"text-2xl font-bold mt-1",children:N.individualSubscribers})]})}),s.jsx(at,{children:s.jsxs(ct,{className:"pt-4",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(yc,{className:"h-4 w-4 text-muted-foreground"}),s.jsx("span",{className:"text-sm text-muted-foreground",children:"Brokerage Subs"})]}),s.jsx("p",{className:"text-2xl font-bold mt-1",children:N.brokerageSubscribers})]})})]}),s.jsxs(go,{defaultValue:"users",className:"space-y-4",children:[s.jsxs(ao,{children:[s.jsx(Bn,{value:"users",children:"All Users"}),s.jsx(Bn,{value:"brokerages",children:"Brokerages"})]}),s.jsxs(xs,{value:"users",className:"space-y-4",children:[s.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[s.jsxs("div",{className:"relative flex-1",children:[s.jsx(ba,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),s.jsx(Et,{placeholder:"Search by name or email...",value:t,onChange:P=>e(P.target.value),className:"pl-9"})]}),s.jsxs(Kn,{value:r,onValueChange:P=>n(P),children:[s.jsx(qn,{className:"w-[200px]",children:s.jsx(Zn,{placeholder:"Filter by status"})}),s.jsxs(Hn,{children:[s.jsx(_r,{value:"all",children:"All Users"}),s.jsx(_r,{value:"active",children:"Active Subscriptions"}),s.jsx(_r,{value:"trialing",children:"Trials"}),s.jsx(_r,{value:"grandfathered",children:"Grandfathered"}),s.jsx(_r,{value:"brokerage",children:"Brokerage Members"}),s.jsx(_r,{value:"expired",children:"Expired/Canceled"}),s.jsx(_r,{value:"none",children:"No Subscription"})]})]})]}),s.jsx(at,{children:s.jsx(ct,{className:"p-0",children:s.jsxs(ni,{children:[s.jsx(si,{children:s.jsxs(Dr,{children:[s.jsx(Nt,{children:"User"}),s.jsx(Nt,{children:"Status"}),s.jsx(Nt,{children:"Plan"}),s.jsx(Nt,{children:"Brokerage"}),s.jsx(Nt,{children:"End Date"}),s.jsx(Nt,{className:"text-right",children:"Actions"})]})}),s.jsx(ii,{children:a?s.jsx(Dr,{children:s.jsx(xt,{colSpan:6,className:"text-center py-8",children:"Loading subscriptions..."})}):(j==null?void 0:j.length)===0?s.jsx(Dr,{children:s.jsx(xt,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No users found"})}):j==null?void 0:j.map(P=>{var O,R;const A=_(P),I=Zz[P.subscription_product_id];return s.jsxs(Dr,{children:[s.jsx(xt,{children:s.jsxs("div",{children:[s.jsx("p",{className:"font-medium",children:P.name}),s.jsx("p",{className:"text-sm text-muted-foreground",children:P.email})]})}),s.jsx(xt,{children:s.jsx(ir,{variant:A.variant,children:A.badge})}),s.jsx(xt,{children:s.jsx("span",{className:"text-sm",children:P.is_grandfathered?"Legacy Access":P.brokerage_id&&!P.subscription_product_id?"Brokerage Subscription":(I==null?void 0:I.name)||A.status})}),s.jsx(xt,{children:(O=P.brokerages)!=null&&O.name?s.jsx("span",{className:"text-sm",children:P.brokerages.name}):s.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})}),s.jsx(xt,{children:P.subscription_end_date?s.jsx("span",{className:"text-sm",children:Vn(new Date(P.subscription_end_date),"MMM d, yyyy")}):P.trial_expires_at?s.jsxs("span",{className:"text-sm text-blue-600",children:["Trial: ",Vn(new Date(P.trial_expires_at),"MMM d, yyyy")]}):s.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})}),s.jsx(xt,{className:"text-right",children:s.jsxs("div",{className:"flex items-center justify-end gap-2",children:[P.stripe_customer_id&&s.jsx(de,{variant:"ghost",size:"sm",onClick:()=>C(P.stripe_customer_id),children:s.jsx(oa,{className:"h-4 w-4"})}),s.jsxs(mn,{children:[s.jsx(Do,{asChild:!0,children:s.jsx(de,{variant:"outline",size:"sm",onClick:()=>o(P),children:"Details"})}),s.jsxs(pn,{children:[s.jsxs(xn,{children:[s.jsx(gn,{children:"Subscription Details"}),s.jsxs(fi,{children:[P.name," (",P.email,")"]})]}),s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-muted-foreground",children:"Status"}),s.jsx(ir,{variant:A.variant,className:"mt-1",children:A.badge})]}),s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-muted-foreground",children:"Plan"}),s.jsx("p",{className:"font-medium",children:P.is_grandfathered?"Grandfathered (Legacy)":P.brokerage_id&&!P.subscription_product_id?"Brokerage Subscription":(I==null?void 0:I.name)||"None"})]}),P.brokerage_id&&s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-muted-foreground",children:"Brokerage"}),s.jsx("p",{className:"font-medium",children:((R=P.brokerages)==null?void 0:R.name)||"Unknown"})]}),P.subscription_end_date&&s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-muted-foreground",children:"Current Period End"}),s.jsx("p",{className:"font-medium",children:Vn(new Date(P.subscription_end_date),"MMMM d, yyyy")})]}),P.trial_expires_at&&s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-muted-foreground",children:"Trial Expires"}),s.jsx("p",{className:"font-medium",children:Vn(new Date(P.trial_expires_at),"MMMM d, yyyy")})]}),P.stripe_customer_id&&s.jsxs("div",{className:"col-span-2",children:[s.jsx("p",{className:"text-sm text-muted-foreground",children:"Stripe Customer ID"}),s.jsx("p",{className:"font-mono text-sm",children:P.stripe_customer_id})]})]}),P.stripe_customer_id&&s.jsxs(de,{className:"w-full",onClick:()=>C(P.stripe_customer_id),children:[s.jsx(oa,{className:"h-4 w-4 mr-2"}),"View in Stripe Dashboard"]})]})]})]})]})})]},P.id)})})]})})})]}),s.jsx(xs,{value:"brokerages",className:"space-y-4",children:s.jsx("div",{className:"grid gap-4",children:g==null?void 0:g.map(P=>{var I,O;const A=(I=P.managers)==null?void 0:I.some(R=>R.subscription_status==="active"&&(R.subscription_product_id==="prod_Tc08MupgoVySDG"||R.subscription_product_id==="prod_Tc09N1tJ4RrAFn"));return s.jsxs(at,{children:[s.jsx(xr,{className:"pb-3",children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"w-10 h-10 rounded-lg bg-primary/10 flex items-center justify-center",children:s.jsx(yc,{className:"h-5 w-5 text-primary"})}),s.jsxs("div",{children:[s.jsx(wr,{className:"text-lg",children:P.name}),s.jsxs(us,{children:[P.agentCount," agents"]})]})]}),s.jsx(ir,{variant:A?"default":"outline",children:A?"Active Subscription":"No Active Subscription"})]})}),s.jsx(ct,{children:((O=P.managers)==null?void 0:O.length)>0?s.jsxs("div",{className:"space-y-2",children:[s.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:"Managers:"}),P.managers.map(R=>{const z=Zz[R.subscription_product_id];return s.jsxs("div",{className:"flex items-center justify-between p-2 rounded-lg bg-muted/50",children:[s.jsxs("div",{children:[s.jsx("p",{className:"font-medium",children:R.name}),s.jsx("p",{className:"text-sm text-muted-foreground",children:R.email})]}),s.jsx("div",{className:"text-right",children:z?s.jsxs("div",{children:[s.jsx(ir,{variant:"default",children:z.name}),s.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:z.price})]}):s.jsx(ir,{variant:"outline",children:"No Subscription"})})]},R.id)})]}):s.jsx("p",{className:"text-sm text-muted-foreground",children:"No managers assigned"})})]},P.id)})})})]})]})})}function F9e(){const[t,e]=D.useState([]),[r,n]=D.useState(!0),[i,o]=D.useState(""),[c,a]=D.useState("all"),[m,g]=D.useState({total:0,qualified:0,pending:0,cancelled:0,totalDiscounts:0});D.useEffect(()=>{_()},[]);const _=async()=>{try{const{data:P,error:A}=await ae.from("referrals").select(` *, referrer_brokerage:brokerages!referrer_brokerage_id(name), referred_brokerage:brokerages!referred_brokerage_id(name), referred_user:profiles!referred_user_id(name, email) `).order("created_at",{ascending:!1});if(A)throw A;e(P||[]);const I=(P==null?void 0:P.filter(z=>z.status==="qualified").length)||0,O=(P==null?void 0:P.filter(z=>z.status==="pending").length)||0,R=(P==null?void 0:P.filter(z=>z.status==="cancelled").length)||0;g({total:(P==null?void 0:P.length)||0,qualified:I,pending:O,cancelled:R,totalDiscounts:I*25})}catch(P){console.error("Error fetching referrals:",P),Dt.error("Failed to load referrals")}finally{n(!1)}},j=async()=>{try{Dt.loading("Processing qualifications...");const{error:P}=await ae.functions.invoke("process-referral-qualifications");if(P)throw P;Dt.dismiss(),Dt.success("Qualifications processed successfully"),_()}catch(P){Dt.dismiss(),console.error("Error processing qualifications:",P),Dt.error("Failed to process qualifications")}},N=t.filter(P=>{var O,R,z,W,V,K;const A=((R=(O=P.referrer_brokerage)==null?void 0:O.name)==null?void 0:R.toLowerCase().includes(i.toLowerCase()))||((W=(z=P.referred_brokerage)==null?void 0:z.name)==null?void 0:W.toLowerCase().includes(i.toLowerCase()))||((K=(V=P.referred_user)==null?void 0:V.email)==null?void 0:K.toLowerCase().includes(i.toLowerCase())),I=c==="all"||P.status===c;return A&&I}),C=P=>{switch(P){case"qualified":return s.jsxs(ir,{className:"bg-green-100 text-green-800",children:[s.jsx(gc,{className:"h-3 w-3 mr-1"}),"Qualified"]});case"pending":return s.jsxs(ir,{variant:"secondary",children:[s.jsx(No,{className:"h-3 w-3 mr-1"}),"Pending"]});case"cancelled":return s.jsxs(ir,{variant:"destructive",children:[s.jsx(W2,{className:"h-3 w-3 mr-1"}),"Cancelled"]});default:return s.jsx(ir,{children:P})}};return s.jsx(Jr,{title:"Referral Program",children:s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Referral Program"}),s.jsx("p",{className:"text-muted-foreground",children:"Track and manage brokerage referrals"})]}),s.jsxs(de,{onClick:j,variant:"outline",children:[s.jsx(R1,{className:"h-4 w-4 mr-2"}),"Process Qualifications"]})]}),s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-5 gap-4",children:[s.jsx(at,{children:s.jsx(ct,{className:"pt-6",children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(_i,{className:"h-5 w-5 text-muted-foreground"}),s.jsxs("div",{children:[s.jsx("p",{className:"text-2xl font-bold",children:m.total}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Total Referrals"})]})]})})}),s.jsx(at,{children:s.jsx(ct,{className:"pt-6",children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(gc,{className:"h-5 w-5 text-green-600"}),s.jsxs("div",{children:[s.jsx("p",{className:"text-2xl font-bold",children:m.qualified}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Qualified"})]})]})})}),s.jsx(at,{children:s.jsx(ct,{className:"pt-6",children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(No,{className:"h-5 w-5 text-amber-600"}),s.jsxs("div",{children:[s.jsx("p",{className:"text-2xl font-bold",children:m.pending}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Pending"})]})]})})}),s.jsx(at,{children:s.jsx(ct,{className:"pt-6",children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(W2,{className:"h-5 w-5 text-red-600"}),s.jsxs("div",{children:[s.jsx("p",{className:"text-2xl font-bold",children:m.cancelled}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Cancelled"})]})]})})}),s.jsx(at,{children:s.jsx(ct,{className:"pt-6",children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(M1,{className:"h-5 w-5 text-green-600"}),s.jsxs("div",{children:[s.jsxs("p",{className:"text-2xl font-bold",children:["$",m.totalDiscounts]}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Monthly Discounts"})]})]})})})]}),s.jsxs(at,{children:[s.jsxs(xr,{children:[s.jsx(wr,{children:"All Referrals"}),s.jsx(us,{children:"View and manage all referral relationships"})]}),s.jsxs(ct,{children:[s.jsxs("div",{className:"flex gap-4 mb-4",children:[s.jsxs("div",{className:"relative flex-1",children:[s.jsx(ba,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),s.jsx(Et,{placeholder:"Search by brokerage or email...",value:i,onChange:P=>o(P.target.value),className:"pl-10"})]}),s.jsxs(Kn,{value:c,onValueChange:a,children:[s.jsx(qn,{className:"w-[180px]",children:s.jsx(Zn,{placeholder:"Filter by status"})}),s.jsxs(Hn,{children:[s.jsx(_r,{value:"all",children:"All Statuses"}),s.jsx(_r,{value:"pending",children:"Pending"}),s.jsx(_r,{value:"qualified",children:"Qualified"}),s.jsx(_r,{value:"cancelled",children:"Cancelled"})]})]})]}),r?s.jsx("div",{className:"flex justify-center py-8",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):s.jsxs(ni,{children:[s.jsx(si,{children:s.jsxs(Dr,{children:[s.jsx(Nt,{children:"Referrer"}),s.jsx(Nt,{children:"Referred"}),s.jsx(Nt,{children:"Signup Date"}),s.jsx(Nt,{children:"Status"}),s.jsx(Nt,{children:"Qualified Date"}),s.jsx(Nt,{children:"Discount"})]})}),s.jsx(ii,{children:N.length===0?s.jsx(Dr,{children:s.jsx(xt,{colSpan:6,className:"text-center text-muted-foreground py-8",children:"No referrals found"})}):N.map(P=>{var A,I,O,R;return s.jsxs(Dr,{children:[s.jsx(xt,{className:"font-medium",children:((A=P.referrer_brokerage)==null?void 0:A.name)||"Unknown"}),s.jsx(xt,{children:s.jsxs("div",{children:[s.jsx("p",{children:((I=P.referred_brokerage)==null?void 0:I.name)||((O=P.referred_user)==null?void 0:O.name)||"Pending setup"}),s.jsx("p",{className:"text-xs text-muted-foreground",children:(R=P.referred_user)==null?void 0:R.email})]})}),s.jsx(xt,{children:Vn(new Date(P.signup_date),"MMM d, yyyy")}),s.jsx(xt,{children:C(P.status)}),s.jsx(xt,{children:P.qualified_date?Vn(new Date(P.qualified_date),"MMM d, yyyy"):"-"}),s.jsx(xt,{children:P.discount_applied?s.jsx(ir,{variant:"outline",className:"text-green-600",children:"$25/mo applied"}):s.jsx("span",{className:"text-muted-foreground",children:"-"})})]},P.id)})})]})]})]})]})})}const Yz=[{value:"add_agent",label:"Add Agent"},{value:"share_resource",label:"Share Resource"},{value:"post_community",label:"Post in Community"},{value:"register_event",label:"Register for Event"},{value:"view_template",label:"View Template"},{value:"watch_academy",label:"Watch Academy Video"},{value:"use_toolbox",label:"Use Toolbox"},{value:"launch_app",label:"Launch App"}],z9e=[{value:"brokerage_manager",label:"Brokerage Manager"},{value:"agent",label:"Agent"}];function B9e(){const[t,e]=D.useState([]),[r,n]=D.useState(!0),[i,o]=D.useState(!1),[c,a]=D.useState(null),[m,g]=D.useState({title:"",description:"",action_type:"view_template",target_role:"agent",is_active:!0});D.useEffect(()=>{_()},[]);const _=async()=>{try{const{data:R,error:z}=await ae.from("onboarding_checklist_items").select("*").order("target_role").order("sort_order");if(z)throw z;e(R||[])}catch(R){console.error("Error fetching checklist items:",R),Dt.error("Failed to load checklist items")}finally{n(!1)}},j=()=>{a(null),g({title:"",description:"",action_type:"view_template",target_role:"agent",is_active:!0}),o(!0)},N=R=>{a(R),g({title:R.title,description:R.description||"",action_type:R.action_type,target_role:R.target_role,is_active:R.is_active}),o(!0)},C=async()=>{if(!m.title.trim()){Dt.error("Title is required");return}try{if(c){const{error:R}=await ae.from("onboarding_checklist_items").update({title:m.title,description:m.description||null,action_type:m.action_type,target_role:m.target_role,is_active:m.is_active}).eq("id",c.id);if(R)throw R;Dt.success("Checklist item updated")}else{const R=t.filter(W=>W.target_role===m.target_role).reduce((W,V)=>Math.max(W,V.sort_order),-1),{error:z}=await ae.from("onboarding_checklist_items").insert({title:m.title,description:m.description||null,action_type:m.action_type,target_role:m.target_role,is_active:m.is_active,sort_order:R+1});if(z)throw z;Dt.success("Checklist item created")}o(!1),_()}catch(R){console.error("Error saving checklist item:",R),Dt.error("Failed to save checklist item")}},P=async R=>{if(confirm("Are you sure you want to delete this checklist item?"))try{const{error:z}=await ae.from("onboarding_checklist_items").delete().eq("id",R);if(z)throw z;Dt.success("Checklist item deleted"),_()}catch(z){console.error("Error deleting checklist item:",z),Dt.error("Failed to delete checklist item")}},A=async R=>{try{const{error:z}=await ae.from("onboarding_checklist_items").update({is_active:!R.is_active}).eq("id",R.id);if(z)throw z;Dt.success(R.is_active?"Item deactivated":"Item activated"),_()}catch(z){console.error("Error toggling item:",z),Dt.error("Failed to update item")}},I=t.filter(R=>R.target_role==="brokerage_manager"),O=t.filter(R=>R.target_role==="agent");return s.jsxs(Jr,{title:"Onboarding Checklist",children:[s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("h2",{className:"text-2xl font-bold",children:"Onboarding Checklist"}),s.jsx("p",{className:"text-muted-foreground",children:"Manage checklist items shown to new users on their dashboard"})]}),s.jsxs(de,{onClick:j,className:"gap-2",children:[s.jsx(Qn,{className:"h-4 w-4"}),"Add Item"]})]}),s.jsxs(at,{children:[s.jsx(xr,{children:s.jsxs(wr,{className:"flex items-center gap-2",children:[s.jsx(ir,{variant:"secondary",children:"Brokerage Manager"}),"Checklist Items"]})}),s.jsx(ct,{children:I.length===0?s.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No checklist items for brokerage managers"}):s.jsxs(ni,{children:[s.jsx(si,{children:s.jsxs(Dr,{children:[s.jsx(Nt,{className:"w-12",children:"#"}),s.jsx(Nt,{children:"Title"}),s.jsx(Nt,{children:"Action Type"}),s.jsx(Nt,{children:"Status"}),s.jsx(Nt,{className:"text-right",children:"Actions"})]})}),s.jsx(ii,{children:I.map((R,z)=>{var W;return s.jsxs(Dr,{children:[s.jsx(xt,{className:"text-muted-foreground",children:z+1}),s.jsx(xt,{children:s.jsxs("div",{children:[s.jsx("p",{className:"font-medium",children:R.title}),R.description&&s.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:R.description})]})}),s.jsx(xt,{children:s.jsx(ir,{variant:"outline",children:((W=Yz.find(V=>V.value===R.action_type))==null?void 0:W.label)||R.action_type})}),s.jsx(xt,{children:s.jsx(ri,{checked:R.is_active,onCheckedChange:()=>A(R)})}),s.jsx(xt,{className:"text-right",children:s.jsxs("div",{className:"flex items-center justify-end gap-2",children:[s.jsx(de,{variant:"ghost",size:"icon",onClick:()=>N(R),children:s.jsx(io,{className:"h-4 w-4"})}),s.jsx(de,{variant:"ghost",size:"icon",onClick:()=>P(R.id),children:s.jsx(oi,{className:"h-4 w-4 text-destructive"})})]})})]},R.id)})})]})})]}),s.jsxs(at,{children:[s.jsx(xr,{children:s.jsxs(wr,{className:"flex items-center gap-2",children:[s.jsx(ir,{variant:"secondary",children:"Agent"}),"Checklist Items"]})}),s.jsx(ct,{children:O.length===0?s.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No checklist items for agents"}):s.jsxs(ni,{children:[s.jsx(si,{children:s.jsxs(Dr,{children:[s.jsx(Nt,{className:"w-12",children:"#"}),s.jsx(Nt,{children:"Title"}),s.jsx(Nt,{children:"Action Type"}),s.jsx(Nt,{children:"Status"}),s.jsx(Nt,{className:"text-right",children:"Actions"})]})}),s.jsx(ii,{children:O.map((R,z)=>{var W;return s.jsxs(Dr,{children:[s.jsx(xt,{className:"text-muted-foreground",children:z+1}),s.jsx(xt,{children:s.jsxs("div",{children:[s.jsx("p",{className:"font-medium",children:R.title}),R.description&&s.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:R.description})]})}),s.jsx(xt,{children:s.jsx(ir,{variant:"outline",children:((W=Yz.find(V=>V.value===R.action_type))==null?void 0:W.label)||R.action_type})}),s.jsx(xt,{children:s.jsx(ri,{checked:R.is_active,onCheckedChange:()=>A(R)})}),s.jsx(xt,{className:"text-right",children:s.jsxs("div",{className:"flex items-center justify-end gap-2",children:[s.jsx(de,{variant:"ghost",size:"icon",onClick:()=>N(R),children:s.jsx(io,{className:"h-4 w-4"})}),s.jsx(de,{variant:"ghost",size:"icon",onClick:()=>P(R.id),children:s.jsx(oi,{className:"h-4 w-4 text-destructive"})})]})})]},R.id)})})]})})]})]}),s.jsx(mn,{open:i,onOpenChange:o,children:s.jsxs(pn,{children:[s.jsx(xn,{children:s.jsx(gn,{children:c?"Edit Checklist Item":"Add Checklist Item"})}),s.jsxs("div",{className:"space-y-4 py-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"title",children:"Title *"}),s.jsx(Et,{id:"title",value:m.title,onChange:R=>g({...m,title:R.target.value}),placeholder:"e.g., Watch your first academy video"})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"description",children:"Description"}),s.jsx(mi,{id:"description",value:m.description,onChange:R=>g({...m,description:R.target.value}),placeholder:"Optional description for the checklist item",rows:2})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Target Role"}),s.jsxs(Kn,{value:m.target_role,onValueChange:R=>g({...m,target_role:R}),children:[s.jsx(qn,{children:s.jsx(Zn,{})}),s.jsx(Hn,{children:z9e.map(R=>s.jsx(_r,{value:R.value,children:R.label},R.value))})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Action Type"}),s.jsxs(Kn,{value:m.action_type,onValueChange:R=>g({...m,action_type:R}),children:[s.jsx(qn,{children:s.jsx(Zn,{})}),s.jsx(Hn,{children:Yz.map(R=>s.jsx(_r,{value:R.value,children:R.label},R.value))})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(ri,{id:"is_active",checked:m.is_active,onCheckedChange:R=>g({...m,is_active:R})}),s.jsx(mt,{htmlFor:"is_active",children:"Active"})]})]}),s.jsxs(zi,{children:[s.jsx(de,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),s.jsx(de,{onClick:C,children:c?"Save Changes":"Create Item"})]})]})})]})}function $9e(){Ri(),Wn();const[t,e]=D.useState("relationship-types"),{data:r}=Sr({queryKey:["admin-feature-flags"],queryFn:async()=>{const{data:C,error:P}=await ae.from("feature_flags").select("*").order("key");if(P)throw P;return C}}),{data:n,isLoading:i}=Sr({queryKey:["admin-relationship-types"],queryFn:async()=>{const{data:C,error:P}=await ae.from("relationship_types").select("*").order("sort_order");if(P)throw P;return C}}),{data:o,isLoading:c}=Sr({queryKey:["admin-action-types"],queryFn:async()=>{const{data:C,error:P}=await ae.from("action_types").select("*").order("sort_order");if(P)throw P;return C}}),{data:a,isLoading:m}=Sr({queryKey:["admin-action-scripts"],queryFn:async()=>{const{data:C,error:P}=await ae.from("action_scripts").select("*, action_type:action_types(*)");if(P)throw P;return C}}),{data:g,isLoading:_}=Sr({queryKey:["admin-touchpoint-plans"],queryFn:async()=>{const{data:C,error:P}=await ae.from("touchpoint_plans").select("*").order("name");if(P)throw P;return C}}),{data:j,isLoading:N}=Sr({queryKey:["admin-popby-items"],queryFn:async()=>{const{data:C,error:P}=await ae.from("popby_items").select("*").is("owner_user_id",null).order("name");if(P)throw P;return C}});return s.jsx(Jr,{title:"Agent OS Control Center",children:s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{children:[s.jsx("h1",{className:"text-2xl font-bold",children:"Agent OS Control Center"}),s.jsx("p",{className:"text-muted-foreground",children:"Manage InnerCircle settings, scripts, and touchpoint plans"})]}),s.jsxs(go,{value:t,onValueChange:e,children:[s.jsxs(ao,{className:"grid w-full grid-cols-8",children:[s.jsxs(Bn,{value:"relationship-types",className:"gap-2",children:[s.jsx(_i,{className:"h-4 w-4"}),s.jsx("span",{className:"hidden sm:inline",children:"Relationships"})]}),s.jsxs(Bn,{value:"action-types",className:"gap-2",children:[s.jsx(Yl,{className:"h-4 w-4"}),s.jsx("span",{className:"hidden sm:inline",children:"Actions"})]}),s.jsxs(Bn,{value:"scripts",className:"gap-2",children:[s.jsx(Ii,{className:"h-4 w-4"}),s.jsx("span",{className:"hidden sm:inline",children:"Scripts"})]}),s.jsxs(Bn,{value:"video-scripts",className:"gap-2",children:[s.jsx(uoe,{className:"h-4 w-4"}),s.jsx("span",{className:"hidden sm:inline",children:"Video Scripts"})]}),s.jsxs(Bn,{value:"plans",className:"gap-2",children:[s.jsx(ko,{className:"h-4 w-4"}),s.jsx("span",{className:"hidden sm:inline",children:"Plans"})]}),s.jsxs(Bn,{value:"popbys",className:"gap-2",children:[s.jsx(yd,{className:"h-4 w-4"}),s.jsx("span",{className:"hidden sm:inline",children:"Popbys"})]}),s.jsxs(Bn,{value:"settings",className:"gap-2",children:[s.jsx(eg,{className:"h-4 w-4"}),s.jsx("span",{className:"hidden sm:inline",children:"Settings"})]}),s.jsxs(Bn,{value:"feature-flags",className:"gap-2",children:[s.jsx(T2e,{className:"h-4 w-4"}),s.jsx("span",{className:"hidden sm:inline",children:"Flags"})]})]}),s.jsx(xs,{value:"relationship-types",className:"mt-6",children:s.jsx(U9e,{types:n||[],isLoading:i})}),s.jsx(xs,{value:"action-types",className:"mt-6",children:s.jsx(V9e,{types:o||[],isLoading:c})}),s.jsx(xs,{value:"scripts",className:"mt-6",children:s.jsx(q9e,{scripts:a||[],actionTypes:o||[],isLoading:m})}),s.jsx(xs,{value:"video-scripts",className:"mt-6",children:s.jsx(K9e,{})}),s.jsx(xs,{value:"plans",className:"mt-6",children:s.jsx(H9e,{plans:g||[],actionTypes:o||[],scripts:a||[],isLoading:_})}),s.jsx(xs,{value:"popbys",className:"mt-6",children:s.jsx(G9e,{items:j||[],isLoading:N})}),s.jsx(xs,{value:"settings",className:"mt-6",children:s.jsx(Z9e,{})}),s.jsx(xs,{value:"feature-flags",className:"mt-6",children:s.jsx(W9e,{flags:r||[]})})]})]})})}function U9e({types:t,isLoading:e}){const{toast:r}=Ri(),n=Wn(),[i,o]=D.useState(null),[c,a]=D.useState(!1),m=zr({mutationFn:async _=>{if(_.id){const{error:j}=await ae.from("relationship_types").update({name:_.name,description:_.description,icon:_.icon}).eq("id",_.id);if(j)throw j}else{const{error:j}=await ae.from("relationship_types").insert([{name:_.name,description:_.description,icon:_.icon,sort_order:t.length}]);if(j)throw j}},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-relationship-types"]}),a(!1),o(null),r({title:"Saved successfully"})},onError:_=>{r({title:"Error",description:_.message,variant:"destructive"})}}),g=async _=>{await ae.from("relationship_types").update({active:!_.active}).eq("id",_.id),n.invalidateQueries({queryKey:["admin-relationship-types"]})};return s.jsxs(at,{children:[s.jsxs(xr,{className:"flex flex-row items-center justify-between",children:[s.jsxs("div",{children:[s.jsx(wr,{children:"Relationship Types"}),s.jsx(us,{children:"Define the relationship categories for InnerCircle contacts"})]}),s.jsxs(de,{onClick:()=>{o(null),a(!0)},children:[s.jsx(Qn,{className:"h-4 w-4 mr-2"}),"Add Type"]})]}),s.jsx(ct,{children:e?s.jsx("div",{className:"flex justify-center py-8",children:s.jsx(Ps,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):s.jsxs(ni,{children:[s.jsx(si,{children:s.jsxs(Dr,{children:[s.jsx(Nt,{className:"w-12"}),s.jsx(Nt,{children:"Name"}),s.jsx(Nt,{children:"Description"}),s.jsx(Nt,{children:"Status"}),s.jsx(Nt,{className:"w-24",children:"Actions"})]})}),s.jsx(ii,{children:t.map(_=>s.jsxs(Dr,{children:[s.jsx(xt,{children:s.jsx(foe,{className:"h-4 w-4 text-muted-foreground cursor-grab"})}),s.jsx(xt,{className:"font-medium",children:_.name}),s.jsx(xt,{className:"text-muted-foreground",children:_.description}),s.jsx(xt,{children:s.jsx(ri,{checked:_.active,onCheckedChange:()=>g(_)})}),s.jsx(xt,{children:s.jsx(de,{variant:"ghost",size:"icon",onClick:()=>{o(_),a(!0)},children:s.jsx(io,{className:"h-4 w-4"})})})]},_.id))})]})}),s.jsx(mn,{open:c,onOpenChange:a,children:s.jsxs(pn,{children:[s.jsx(xn,{children:s.jsxs(gn,{children:[i?"Edit":"Add"," Relationship Type"]})}),s.jsxs("form",{onSubmit:_=>{_.preventDefault();const j=new FormData(_.currentTarget);m.mutate({id:i==null?void 0:i.id,name:j.get("name"),description:j.get("description"),icon:j.get("icon")})},children:[s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"name",children:"Name"}),s.jsx(Et,{id:"name",name:"name",defaultValue:i==null?void 0:i.name,required:!0})]}),s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"description",children:"Description"}),s.jsx(mi,{id:"description",name:"description",defaultValue:(i==null?void 0:i.description)||""})]}),s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"icon",children:"Icon"}),s.jsx(Et,{id:"icon",name:"icon",defaultValue:(i==null?void 0:i.icon)||"",placeholder:"e.g., star, heart, user"})]})]}),s.jsxs(zi,{className:"mt-4",children:[s.jsx(de,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),s.jsxs(de,{type:"submit",disabled:m.isPending,children:[m.isPending&&s.jsx(Ps,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function V9e({types:t,isLoading:e}){const{toast:r}=Ri(),n=Wn(),[i,o]=D.useState(null),[c,a]=D.useState(!1),m=zr({mutationFn:async _=>{if(_.id){const{error:j}=await ae.from("action_types").update({name:_.name,description:_.description,icon:_.icon,color:_.color}).eq("id",_.id);if(j)throw j}else{const{error:j}=await ae.from("action_types").insert([{name:_.name,description:_.description,icon:_.icon,color:_.color,sort_order:t.length}]);if(j)throw j}},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-action-types"]}),a(!1),o(null),r({title:"Saved successfully"})},onError:_=>{r({title:"Error",description:_.message,variant:"destructive"})}}),g=async _=>{await ae.from("action_types").update({active:!_.active}).eq("id",_.id),n.invalidateQueries({queryKey:["admin-action-types"]})};return s.jsxs(at,{children:[s.jsxs(xr,{className:"flex flex-row items-center justify-between",children:[s.jsxs("div",{children:[s.jsx(wr,{children:"Action Types"}),s.jsx(us,{children:"Define the types of touchpoint actions agents can take"})]}),s.jsxs(de,{onClick:()=>{o(null),a(!0)},children:[s.jsx(Qn,{className:"h-4 w-4 mr-2"}),"Add Action"]})]}),s.jsx(ct,{children:e?s.jsx("div",{className:"flex justify-center py-8",children:s.jsx(Ps,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):s.jsxs(ni,{children:[s.jsx(si,{children:s.jsxs(Dr,{children:[s.jsx(Nt,{children:"Name"}),s.jsx(Nt,{children:"Description"}),s.jsx(Nt,{children:"Color"}),s.jsx(Nt,{children:"Status"}),s.jsx(Nt,{className:"w-24",children:"Actions"})]})}),s.jsx(ii,{children:t.map(_=>s.jsxs(Dr,{children:[s.jsx(xt,{className:"font-medium",children:_.name}),s.jsx(xt,{className:"text-muted-foreground",children:_.description}),s.jsx(xt,{children:_.color&&s.jsx("div",{className:"w-6 h-6 rounded",style:{backgroundColor:_.color}})}),s.jsx(xt,{children:s.jsx(ri,{checked:_.active,onCheckedChange:()=>g(_)})}),s.jsx(xt,{children:s.jsx(de,{variant:"ghost",size:"icon",onClick:()=>{o(_),a(!0)},children:s.jsx(io,{className:"h-4 w-4"})})})]},_.id))})]})}),s.jsx(mn,{open:c,onOpenChange:a,children:s.jsxs(pn,{children:[s.jsx(xn,{children:s.jsxs(gn,{children:[i?"Edit":"Add"," Action Type"]})}),s.jsxs("form",{onSubmit:_=>{_.preventDefault();const j=new FormData(_.currentTarget);m.mutate({id:i==null?void 0:i.id,name:j.get("name"),description:j.get("description"),icon:j.get("icon"),color:j.get("color")})},children:[s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"name",children:"Name"}),s.jsx(Et,{id:"name",name:"name",defaultValue:i==null?void 0:i.name,required:!0})]}),s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"description",children:"Description"}),s.jsx(mi,{id:"description",name:"description",defaultValue:(i==null?void 0:i.description)||""})]}),s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"icon",children:"Icon"}),s.jsx(Et,{id:"icon",name:"icon",defaultValue:(i==null?void 0:i.icon)||"",placeholder:"e.g., phone, message"})]}),s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"color",children:"Color"}),s.jsx(Et,{id:"color",name:"color",type:"color",defaultValue:(i==null?void 0:i.color)||"#6366f1"})]})]}),s.jsxs(zi,{className:"mt-4",children:[s.jsx(de,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),s.jsxs(de,{type:"submit",disabled:m.isPending,children:[m.isPending&&s.jsx(Ps,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function q9e({scripts:t,actionTypes:e,isLoading:r}){const{toast:n}=Ri(),i=Wn(),[o,c]=D.useState(null),[a,m]=D.useState(!1),g=zr({mutationFn:async j=>{if(j.id){const{error:N}=await ae.from("action_scripts").update({title:j.title,action_type_id:j.action_type_id,tone:j.tone,script_body:j.script_body,active:j.active}).eq("id",j.id);if(N)throw N}else{const{error:N}=await ae.from("action_scripts").insert([{title:j.title,action_type_id:j.action_type_id,tone:j.tone,script_body:j.script_body,active:!0}]);if(N)throw N}},onSuccess:()=>{i.invalidateQueries({queryKey:["admin-action-scripts"]}),m(!1),c(null),n({title:"Saved successfully"})},onError:j=>{n({title:"Error",description:j.message,variant:"destructive"})}}),_=zr({mutationFn:async j=>{const{error:N}=await ae.from("action_scripts").delete().eq("id",j);if(N)throw N},onSuccess:()=>{i.invalidateQueries({queryKey:["admin-action-scripts"]}),n({title:"Deleted successfully"})}});return s.jsxs(at,{children:[s.jsxs(xr,{className:"flex flex-row items-center justify-between",children:[s.jsxs("div",{children:[s.jsx(wr,{children:"Script Library"}),s.jsx(us,{children:"Create and manage scripts for each action type"})]}),s.jsxs(de,{onClick:()=>{c(null),m(!0)},children:[s.jsx(Qn,{className:"h-4 w-4 mr-2"}),"Add Script"]})]}),s.jsx(ct,{children:r?s.jsx("div",{className:"flex justify-center py-8",children:s.jsx(Ps,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):s.jsxs(ni,{children:[s.jsx(si,{children:s.jsxs(Dr,{children:[s.jsx(Nt,{children:"Title"}),s.jsx(Nt,{children:"Action Type"}),s.jsx(Nt,{children:"Tone"}),s.jsx(Nt,{children:"Status"}),s.jsx(Nt,{className:"w-24",children:"Actions"})]})}),s.jsx(ii,{children:t.map(j=>{var N;return s.jsxs(Dr,{children:[s.jsx(xt,{className:"font-medium",children:j.title}),s.jsx(xt,{children:s.jsx(ir,{variant:"outline",children:((N=j.action_type)==null?void 0:N.name)||"Unknown"})}),s.jsx(xt,{className:"text-muted-foreground",children:j.tone}),s.jsx(xt,{children:s.jsx(ir,{variant:j.active?"default":"secondary",children:j.active?"Active":"Inactive"})}),s.jsxs(xt,{className:"flex gap-1",children:[s.jsx(de,{variant:"ghost",size:"icon",onClick:()=>{c(j),m(!0)},children:s.jsx(io,{className:"h-4 w-4"})}),s.jsx(de,{variant:"ghost",size:"icon",onClick:()=>_.mutate(j.id),children:s.jsx(oi,{className:"h-4 w-4 text-destructive"})})]})]},j.id)})})]})}),s.jsx(mn,{open:a,onOpenChange:m,children:s.jsxs(pn,{className:"max-w-2xl",children:[s.jsx(xn,{children:s.jsxs(gn,{children:[o?"Edit":"Add"," Script"]})}),s.jsxs("form",{onSubmit:j=>{j.preventDefault();const N=new FormData(j.currentTarget);g.mutate({id:o==null?void 0:o.id,title:N.get("title"),action_type_id:N.get("action_type_id"),tone:N.get("tone"),script_body:N.get("script_body"),active:!0})},children:[s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"title",children:"Title"}),s.jsx(Et,{id:"title",name:"title",defaultValue:o==null?void 0:o.title,required:!0})]}),s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"action_type_id",children:"Action Type"}),s.jsxs(Kn,{name:"action_type_id",defaultValue:o==null?void 0:o.action_type_id,children:[s.jsx(qn,{children:s.jsx(Zn,{placeholder:"Select action type"})}),s.jsx(Hn,{children:e.map(j=>s.jsx(_r,{value:j.id,children:j.name},j.id))})]})]})]}),s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"tone",children:"Tone (optional)"}),s.jsx(Et,{id:"tone",name:"tone",defaultValue:(o==null?void 0:o.tone)||"",placeholder:"e.g., Friendly, Professional, Casual"})]}),s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"script_body",children:"Script Body"}),s.jsx(mi,{id:"script_body",name:"script_body",defaultValue:o==null?void 0:o.script_body,rows:8,required:!0,placeholder:`Use {{FirstName}}, {{LastName}}, and {{AgentName}} as placeholders. Example: Hey {{FirstName}}, it's {{AgentName}}. I was thinking about you and wanted to check in...`})]})]}),s.jsxs(zi,{className:"mt-4",children:[s.jsx(de,{type:"button",variant:"outline",onClick:()=>m(!1),children:"Cancel"}),s.jsxs(de,{type:"submit",disabled:g.isPending,children:[g.isPending&&s.jsx(Ps,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function H9e({plans:t,actionTypes:e,scripts:r,isLoading:n}){const{toast:i}=Ri(),o=Wn(),[c,a]=D.useState(null),[m,g]=D.useState(!1),[_,j]=D.useState(null),[N,C]=D.useState(!1),[P,A]=D.useState(null),[I,O]=D.useState(null),{data:R}=Sr({queryKey:["plan-items",_],queryFn:async()=>{if(!_)return[];const{data:X,error:ie}=await ae.from("touchpoint_plan_items").select("*").eq("plan_id",_).order("month_number");if(ie)throw ie;return X},enabled:!!_}),z=zr({mutationFn:async X=>{if(X.id){const{error:ie}=await ae.from("touchpoint_plans").update({name:X.name,description:X.description,active:X.active}).eq("id",X.id);if(ie)throw ie}else{const{error:ie}=await ae.from("touchpoint_plans").insert([{name:X.name,description:X.description,active:!0}]);if(ie)throw ie}},onSuccess:()=>{o.invalidateQueries({queryKey:["admin-touchpoint-plans"]}),g(!1),a(null),i({title:"Saved successfully"})},onError:X=>{i({title:"Error",description:X.message,variant:"destructive"})}}),W=zr({mutationFn:async X=>{if(X.id){const{error:ie}=await ae.from("touchpoint_plan_items").update({action_type_id:X.action_type_id,default_script_id:X.default_script_id,notes:X.notes}).eq("id",X.id);if(ie)throw ie}else{const{error:ie}=await ae.from("touchpoint_plan_items").insert([{plan_id:X.plan_id,month_number:X.month_number,action_type_id:X.action_type_id,default_script_id:X.default_script_id,notes:X.notes}]);if(ie)throw ie}},onSuccess:()=>{o.invalidateQueries({queryKey:["plan-items",_]}),i({title:"Item saved"})}}),V=zr({mutationFn:async X=>{const{error:ie}=await ae.from("touchpoint_plan_items").delete().eq("id",X);if(ie)throw ie},onSuccess:()=>{o.invalidateQueries({queryKey:["plan-items",_]})}}),K=zr({mutationFn:async X=>{const{data:ie,error:he}=await ae.from("action_scripts").insert([{...X,active:!0}]).select().single();if(he)throw he;return ie},onSuccess:async X=>{o.invalidateQueries({queryKey:["admin-action-scripts"]}),P&&await W.mutateAsync({id:P.itemId,plan_id:_,month_number:P.month,action_type_id:P.actionTypeId,default_script_id:X.id}),C(!1),A(null),i({title:"Script created and assigned"})},onError:X=>{i({title:"Error",description:X.message,variant:"destructive"})}}),Q=(X,ie,he)=>{A({month:X,actionTypeId:ie,itemId:he}),C(!0)},te=X=>r.find(ie=>ie.id===X);return s.jsxs("div",{className:"space-y-6",children:[s.jsxs(at,{children:[s.jsxs(xr,{className:"flex flex-row items-center justify-between",children:[s.jsxs("div",{children:[s.jsx(wr,{children:"Touchpoint Plans"}),s.jsx(us,{children:"Create annual touchpoint plans that agents can apply to their contacts"})]}),s.jsxs(de,{onClick:()=>{a(null),g(!0)},children:[s.jsx(Qn,{className:"h-4 w-4 mr-2"}),"Add Plan"]})]}),s.jsx(ct,{children:n?s.jsx("div",{className:"flex justify-center py-8",children:s.jsx(Ps,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):s.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:t.map(X=>s.jsxs(at,{className:`cursor-pointer transition-colors ${_===X.id?"border-primary":""}`,onClick:()=>j(X.id),children:[s.jsx(xr,{className:"pb-2",children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx(wr,{className:"text-base",children:X.name}),s.jsx(de,{variant:"ghost",size:"icon",onClick:ie=>{ie.stopPropagation(),a(X),g(!0)},children:s.jsx(io,{className:"h-4 w-4"})})]})}),s.jsxs(ct,{children:[s.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2",children:X.description}),s.jsx(ir,{variant:X.active?"default":"secondary",className:"mt-2",children:X.active?"Active":"Inactive"})]})]},X.id))})})]}),_&&s.jsxs(at,{children:[s.jsxs(xr,{children:[s.jsx(wr,{children:"Plan Schedule"}),s.jsx(us,{children:"Configure the monthly touchpoint schedule. Select an action type for each month, then assign or create a script."})]}),s.jsx(ct,{children:s.jsx("div",{className:"grid gap-3",children:Array.from({length:12},(X,ie)=>ie+1).map(X=>{const ie=R==null?void 0:R.find(pe=>pe.month_number===X),he=ie!=null&&ie.default_script_id?te(ie.default_script_id):null,xe=r.filter(pe=>pe.action_type_id===(ie==null?void 0:ie.action_type_id)&&pe.active);return s.jsxs("div",{className:"p-4 border rounded-lg space-y-3",children:[s.jsxs("div",{className:"flex items-center gap-4",children:[s.jsxs("div",{className:"w-20 font-medium text-sm",children:["Month ",X]}),s.jsxs(Kn,{value:(ie==null?void 0:ie.action_type_id)||"none",onValueChange:pe=>{pe==="none"&&ie?V.mutate(ie.id):pe!=="none"&&W.mutate({id:ie==null?void 0:ie.id,plan_id:_,month_number:X,action_type_id:pe,default_script_id:null})},children:[s.jsx(qn,{className:"w-40",children:s.jsx(Zn,{placeholder:"No action"})}),s.jsxs(Hn,{children:[s.jsx(_r,{value:"none",children:"No action"}),e.filter(pe=>pe.active).map(pe=>s.jsx(_r,{value:pe.id,children:s.jsxs("span",{className:"flex items-center gap-2",children:[pe.color&&s.jsx("span",{className:"w-3 h-3 rounded-full",style:{backgroundColor:pe.color}}),pe.name]})},pe.id))]})]}),ie&&s.jsxs(s.Fragment,{children:[s.jsxs(Kn,{value:ie.default_script_id||"none",onValueChange:pe=>{O(null),W.mutate({id:ie.id,default_script_id:pe==="none"?null:pe})},children:[s.jsx(qn,{className:"w-56",children:s.jsx(Zn,{placeholder:"Select script"})}),s.jsxs(Hn,{children:[s.jsx(_r,{value:"none",children:"No default script"}),xe.map(pe=>s.jsxs(_r,{value:pe.id,children:[pe.title," ",pe.tone&&`(${pe.tone})`]},pe.id))]})]}),s.jsxs(de,{variant:"outline",size:"sm",onClick:()=>Q(X,ie.action_type_id,ie.id),children:[s.jsx(Qn,{className:"h-3 w-3 mr-1"}),"New Script"]}),he&&s.jsx(de,{variant:"ghost",size:"sm",onClick:()=>O((I==null?void 0:I.id)===he.id?null:he),children:(I==null?void 0:I.id)===he.id?"Hide":"Preview"})]})]}),I&&(ie==null?void 0:ie.default_script_id)===I.id&&s.jsxs("div",{className:"ml-24 p-3 bg-muted rounded-lg text-sm",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[s.jsx(ir,{variant:"outline",children:I.title}),I.tone&&s.jsx(ir,{variant:"secondary",children:I.tone})]}),s.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:I.script_body})]})]},X)})})})]}),s.jsx(mn,{open:m,onOpenChange:g,children:s.jsxs(pn,{children:[s.jsx(xn,{children:s.jsxs(gn,{children:[c?"Edit":"Add"," Touchpoint Plan"]})}),s.jsxs("form",{onSubmit:X=>{X.preventDefault();const ie=new FormData(X.currentTarget);z.mutate({id:c==null?void 0:c.id,name:ie.get("name"),description:ie.get("description"),active:!0})},children:[s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"name",children:"Name"}),s.jsx(Et,{id:"name",name:"name",defaultValue:c==null?void 0:c.name,required:!0})]}),s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"description",children:"Description"}),s.jsx(mi,{id:"description",name:"description",defaultValue:(c==null?void 0:c.description)||"",rows:3})]})]}),s.jsxs(zi,{className:"mt-4",children:[s.jsx(de,{type:"button",variant:"outline",onClick:()=>g(!1),children:"Cancel"}),s.jsxs(de,{type:"submit",disabled:z.isPending,children:[z.isPending&&s.jsx(Ps,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})}),s.jsx(mn,{open:N,onOpenChange:C,children:s.jsxs(pn,{className:"max-w-2xl",children:[s.jsxs(xn,{children:[s.jsx(gn,{children:"Create New Script"}),s.jsxs(fi,{children:["Create a script for Month ",P==null?void 0:P.month,". Use ","{{FirstName}}",", ","{{LastName}}",", and ","{{AgentName}}"," as placeholders."]})]}),s.jsxs("form",{onSubmit:X=>{X.preventDefault();const ie=new FormData(X.currentTarget);K.mutate({title:ie.get("title"),action_type_id:P.actionTypeId,tone:ie.get("tone"),script_body:ie.get("script_body")})},children:[s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"script_title",children:"Title"}),s.jsx(Et,{id:"script_title",name:"title",placeholder:"e.g., Warm Check-In",required:!0})]}),s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"script_tone",children:"Tone"}),s.jsx(Et,{id:"script_tone",name:"tone",placeholder:"e.g., Friendly, Professional"})]})]}),s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"script_body",children:"Script Body"}),s.jsx(mi,{id:"script_body",name:"script_body",rows:6,required:!0,placeholder:"Hey {{FirstName}}, it's {{AgentName}}. I was thinking about you and wanted to check in..."})]})]}),s.jsxs(zi,{className:"mt-4",children:[s.jsx(de,{type:"button",variant:"outline",onClick:()=>C(!1),children:"Cancel"}),s.jsxs(de,{type:"submit",disabled:K.isPending,children:[K.isPending&&s.jsx(Ps,{className:"h-4 w-4 mr-2 animate-spin"}),"Create & Assign"]})]})]})]})})]})}function W9e({flags:t}){const{toast:e}=Ri(),r=Wn(),n=async(i,o)=>{const{error:c}=await ae.from("feature_flags").update({...o,updated_at:new Date().toISOString()}).eq("id",i.id);c?e({title:"Error",description:c.message,variant:"destructive"}):(r.invalidateQueries({queryKey:["admin-feature-flags"]}),e({title:"Flag updated"}))};return s.jsxs(at,{children:[s.jsxs(xr,{children:[s.jsx(wr,{children:"Feature Flags"}),s.jsx(us,{children:"Control which features are enabled for members"})]}),s.jsx(ct,{children:s.jsxs(ni,{children:[s.jsx(si,{children:s.jsxs(Dr,{children:[s.jsx(Nt,{children:"Flag"}),s.jsx(Nt,{children:"Status"}),s.jsx(Nt,{children:"Notes"}),s.jsx(Nt,{children:"Last Updated"})]})}),s.jsx(ii,{children:t.map(i=>s.jsxs(Dr,{children:[s.jsx(xt,{className:"font-mono text-sm",children:i.key}),s.jsx(xt,{children:s.jsx(ri,{checked:i.enabled,onCheckedChange:o=>n(i,{enabled:o})})}),s.jsx(xt,{children:s.jsx(Et,{defaultValue:i.notes||"",placeholder:"Add notes...",className:"max-w-xs",onBlur:o=>{o.target.value!==i.notes&&n(i,{notes:o.target.value})}})}),s.jsx(xt,{className:"text-muted-foreground text-sm",children:new Date(i.updated_at).toLocaleDateString()})]},i.id))})]})})]})}function G9e({items:t,isLoading:e}){const{toast:r}=Ri(),n=Wn(),[i,o]=D.useState(null),[c,a]=D.useState(!1),m=zr({mutationFn:async j=>{if(j.id){const{error:N}=await ae.from("popby_items").update({name:j.name,description:j.description}).eq("id",j.id);if(N)throw N}else{const{error:N}=await ae.from("popby_items").insert([{name:j.name,description:j.description,owner_user_id:null}]);if(N)throw N}},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-popby-items"]}),n.invalidateQueries({queryKey:["popby-items"]}),a(!1),o(null),r({title:"Saved successfully"})},onError:j=>{r({title:"Error",description:j.message,variant:"destructive"})}}),g=async j=>{await ae.from("popby_items").update({is_active:!j.is_active}).eq("id",j.id),n.invalidateQueries({queryKey:["admin-popby-items"]}),n.invalidateQueries({queryKey:["popby-items"]})},_=async j=>{await ae.from("popby_items").delete().eq("id",j),n.invalidateQueries({queryKey:["admin-popby-items"]}),n.invalidateQueries({queryKey:["popby-items"]}),r({title:"Deleted successfully"})};return s.jsxs(at,{children:[s.jsxs(xr,{className:"flex flex-row items-center justify-between",children:[s.jsxs("div",{children:[s.jsx(wr,{children:"Popby Ideas"}),s.jsx(us,{children:"Manage global popby ideas that all agents can see"})]}),s.jsxs(de,{onClick:()=>{o(null),a(!0)},children:[s.jsx(Qn,{className:"h-4 w-4 mr-2"}),"Add Popby Idea"]})]}),s.jsx(ct,{children:e?s.jsx("div",{className:"flex justify-center py-8",children:s.jsx(Ps,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):t.length===0?s.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[s.jsx(yd,{className:"h-12 w-12 mx-auto mb-2 opacity-50"}),s.jsx("p",{children:"No popby ideas yet. Add your first one!"})]}):s.jsxs(ni,{children:[s.jsx(si,{children:s.jsxs(Dr,{children:[s.jsx(Nt,{children:"Name"}),s.jsx(Nt,{children:"Description"}),s.jsx(Nt,{children:"Status"}),s.jsx(Nt,{className:"w-24",children:"Actions"})]})}),s.jsx(ii,{children:t.map(j=>s.jsxs(Dr,{children:[s.jsx(xt,{className:"font-medium",children:j.name}),s.jsx(xt,{className:"text-muted-foreground",children:j.description}),s.jsx(xt,{children:s.jsx(ri,{checked:j.is_active,onCheckedChange:()=>g(j)})}),s.jsx(xt,{children:s.jsxs("div",{className:"flex gap-1",children:[s.jsx(de,{variant:"ghost",size:"icon",onClick:()=>{o(j),a(!0)},children:s.jsx(io,{className:"h-4 w-4"})}),s.jsx(de,{variant:"ghost",size:"icon",onClick:()=>_(j.id),children:s.jsx(oi,{className:"h-4 w-4 text-destructive"})})]})})]},j.id))})]})}),s.jsx(mn,{open:c,onOpenChange:a,children:s.jsxs(pn,{children:[s.jsx(xn,{children:s.jsxs(gn,{children:[i?"Edit":"Add"," Popby Idea"]})}),s.jsxs("form",{onSubmit:j=>{j.preventDefault();const N=new FormData(j.currentTarget);m.mutate({id:i==null?void 0:i.id,name:N.get("name"),description:N.get("description")})},children:[s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"name",children:"Name"}),s.jsx(Et,{id:"name",name:"name",defaultValue:i==null?void 0:i.name,required:!0,placeholder:"e.g., Homemade Cookies"})]}),s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"description",children:"Description"}),s.jsx(mi,{id:"description",name:"description",defaultValue:(i==null?void 0:i.description)||"",placeholder:"Brief description of the popby idea..."})]})]}),s.jsxs(zi,{className:"mt-4",children:[s.jsx(de,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),s.jsxs(de,{type:"submit",disabled:m.isPending,children:[m.isPending&&s.jsx(Ps,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function K9e(){var C;const{toast:t}=Ri(),e=Wn(),[r,n]=D.useState(null),[i,o]=D.useState(!1),{data:c,isLoading:a}=Sr({queryKey:["admin-video-script-categories"],queryFn:async()=>{const{data:P,error:A}=await ae.from("video_script_categories").select("*").order("sort_order");if(A)throw A;return P}}),{data:m,isLoading:g}=Sr({queryKey:["admin-video-scripts"],queryFn:async()=>{const{data:P,error:A}=await ae.from("video_scripts").select("*, category:video_script_categories(*)").order("title");if(A)throw A;return P}}),_=zr({mutationFn:async P=>{var A,I;if(P.id){const{error:O}=await ae.from("video_scripts").update({title:P.title,script_text:P.script_text,category_id:P.category_id,tags:((A=P.tags)==null?void 0:A.split(",").map(R=>R.trim()).filter(Boolean))||[]}).eq("id",P.id);if(O)throw O}else{const{error:O}=await ae.from("video_scripts").insert([{title:P.title,script_text:P.script_text,category_id:P.category_id||null,tags:((I=P.tags)==null?void 0:I.split(",").map(R=>R.trim()).filter(Boolean))||[]}]);if(O)throw O}},onSuccess:()=>{e.invalidateQueries({queryKey:["admin-video-scripts"]}),o(!1),n(null),t({title:"Video script saved!"})},onError:P=>t({title:"Error",description:P.message,variant:"destructive"})}),j=async P=>{await ae.from("video_scripts").update({is_active:!P.is_active}).eq("id",P.id),e.invalidateQueries({queryKey:["admin-video-scripts"]})},N=async P=>{confirm("Delete this video script?")&&(await ae.from("video_scripts").delete().eq("id",P),e.invalidateQueries({queryKey:["admin-video-scripts"]}),t({title:"Script deleted"}))};return s.jsxs(at,{children:[s.jsxs(xr,{className:"flex flex-row items-center justify-between",children:[s.jsxs("div",{children:[s.jsx(wr,{children:"Video Scripts"}),s.jsx(us,{children:"Manage teleprompter scripts for Quick Video Touch"})]}),s.jsxs(de,{onClick:()=>{n(null),o(!0)},children:[s.jsx(Qn,{className:"h-4 w-4 mr-2"}),"Add Script"]})]}),s.jsx(ct,{children:g?s.jsx("div",{className:"flex justify-center py-8",children:s.jsx(Ps,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):s.jsxs(ni,{children:[s.jsx(si,{children:s.jsxs(Dr,{children:[s.jsx(Nt,{children:"Title"}),s.jsx(Nt,{children:"Category"}),s.jsx(Nt,{children:"Status"}),s.jsx(Nt,{className:"w-24",children:"Actions"})]})}),s.jsx(ii,{children:m==null?void 0:m.map(P=>{var A;return s.jsxs(Dr,{children:[s.jsx(xt,{className:"font-medium",children:P.title}),s.jsx(xt,{className:"text-muted-foreground",children:((A=P.category)==null?void 0:A.name)||"Uncategorized"}),s.jsx(xt,{children:s.jsx(ri,{checked:P.is_active,onCheckedChange:()=>j(P)})}),s.jsxs(xt,{className:"flex gap-1",children:[s.jsx(de,{variant:"ghost",size:"icon",onClick:()=>{n(P),o(!0)},children:s.jsx(io,{className:"h-4 w-4"})}),s.jsx(de,{variant:"ghost",size:"icon",onClick:()=>N(P.id),children:s.jsx(oi,{className:"h-4 w-4"})})]})]},P.id)})})]})}),s.jsx(mn,{open:i,onOpenChange:o,children:s.jsxs(pn,{className:"max-w-2xl",children:[s.jsx(xn,{children:s.jsxs(gn,{children:[r?"Edit":"Add"," Video Script"]})}),s.jsxs("form",{onSubmit:P=>{P.preventDefault();const A=new FormData(P.currentTarget);_.mutate({id:r==null?void 0:r.id,title:A.get("title"),script_text:A.get("script_text"),category_id:A.get("category_id")||null,tags:A.get("tags")})},children:[s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"title",children:"Title"}),s.jsx(Et,{id:"title",name:"title",defaultValue:r==null?void 0:r.title,required:!0})]}),s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"category_id",children:"Category"}),s.jsxs(Kn,{name:"category_id",defaultValue:(r==null?void 0:r.category_id)||"",children:[s.jsx(qn,{children:s.jsx(Zn,{placeholder:"Select category"})}),s.jsx(Hn,{children:c==null?void 0:c.map(P=>s.jsx(_r,{value:P.id,children:P.name},P.id))})]})]}),s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"script_text",children:"Script Text"}),s.jsx(mi,{id:"script_text",name:"script_text",defaultValue:r==null?void 0:r.script_text,rows:6,required:!0,placeholder:"Enter the teleprompter script..."})]}),s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"tags",children:"Tags (comma-separated)"}),s.jsx(Et,{id:"tags",name:"tags",defaultValue:((C=r==null?void 0:r.tags)==null?void 0:C.join(", "))||"",placeholder:"birthday, follow-up, thank-you"})]})]}),s.jsxs(zi,{className:"mt-4",children:[s.jsx(de,{type:"button",variant:"outline",onClick:()=>o(!1),children:"Cancel"}),s.jsxs(de,{type:"submit",disabled:_.isPending,children:[_.isPending&&s.jsx(Ps,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function Z9e(){const{toast:t}=Ri(),[e,r]=D.useState(""),[n,i]=D.useState(!0),[o,c]=D.useState(!1);D.useEffect(()=>{(async()=>{i(!0);try{const{data:g}=await ae.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();g!=null&&g.value&&r(g.value)}catch(g){console.error("Error fetching settings:",g)}i(!1)})()},[]);const a=async()=>{c(!0);try{await ae.from("settings").upsert({key:"mapbox_public_token",value:e.trim()}),t({title:"Mapbox token saved!"})}catch{t({title:"Error saving token",variant:"destructive"})}c(!1)};return n?s.jsx(at,{children:s.jsx(ct,{className:"flex justify-center py-8",children:s.jsx(Ps,{className:"h-8 w-8 animate-spin text-muted-foreground"})})}):s.jsx("div",{className:"space-y-6",children:s.jsxs(at,{children:[s.jsxs(xr,{children:[s.jsxs(wr,{className:"flex items-center gap-2",children:[s.jsx(wp,{className:"h-5 w-5"}),"Popby Map Settings"]}),s.jsx(us,{children:"Configure the map feature for popbys"})]}),s.jsxs(ct,{className:"space-y-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"mapbox-token",children:"Mapbox Public Token"}),s.jsx(Et,{id:"mapbox-token",placeholder:"pk.eyJ1I...",value:e,onChange:m=>r(m.target.value)}),s.jsxs("p",{className:"text-xs text-muted-foreground",children:["Get your token at"," ",s.jsx("a",{href:"https://mapbox.com/",target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline",children:"mapbox.com"}),". This token will be used by all agents for the popby map feature."]})]}),s.jsxs(de,{onClick:a,disabled:o,children:[o&&s.jsx(Ps,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Token"]}),e&&s.jsx(ir,{variant:"secondary",className:"ml-2",children:"Token configured"})]})]})})}const Y9e=()=>{const[t,e]=D.useState(""),[r,n]=D.useState("grid"),i=Bs(),{data:o=[],isLoading:c}=Sr({queryKey:["additional-services"],queryFn:async()=>{const{data:m,error:g}=await ae.from("additional_services").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(g)throw g;return m}}),a=o.filter(m=>{var _;return m.name.toLowerCase().includes(t.toLowerCase())||((_=m.description)==null?void 0:_.toLowerCase().includes(t.toLowerCase()))});return s.jsx(Jr,{title:"Additional Services",children:s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{children:[s.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Additional Services"}),s.jsx("p",{className:"text-muted-foreground mt-1",children:"Explore our additional services and offerings"})]}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[s.jsxs("div",{className:"relative flex-1 max-w-sm",children:[s.jsx(ba,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),s.jsx(Et,{placeholder:"Search services...",value:t,onChange:m=>e(m.target.value),className:"pl-9"})]}),s.jsxs("div",{className:"flex gap-2",children:[t&&s.jsx(de,{variant:"outline",size:"sm",onClick:()=>e(""),children:"Clear"}),s.jsxs("div",{className:"flex border rounded-md",children:[s.jsx(de,{variant:r==="grid"?"secondary":"ghost",size:"icon",onClick:()=>n("grid"),className:"rounded-r-none",children:s.jsx(tD,{className:"h-4 w-4"})}),s.jsx(de,{variant:r==="list"?"secondary":"ghost",size:"icon",onClick:()=>n("list"),className:"rounded-l-none",children:s.jsx(Aj,{className:"h-4 w-4"})})]})]})]}),s.jsxs("div",{className:"text-sm text-muted-foreground",children:[a.length," service",a.length!==1?"s":""," found"]}),c&&s.jsx("div",{className:r==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-4",children:[...Array(4)].map((m,g)=>s.jsx(at,{children:s.jsxs(ct,{className:"p-4",children:[s.jsx(Dn,{className:"aspect-[3/2] w-full rounded-lg mb-4"}),s.jsx(Dn,{className:"h-5 w-3/4 mb-2"}),s.jsx(Dn,{className:"h-4 w-full mb-4"})]})},g))}),!c&&a.length===0&&s.jsxs("div",{className:"text-center py-12",children:[s.jsx("div",{className:"text-muted-foreground mb-4",children:t?"No services match your search":"No additional services available yet"}),t&&s.jsx(de,{variant:"outline",onClick:()=>e(""),children:"Clear Search"})]}),!c&&a.length>0&&s.jsx("div",{className:r==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-4",children:a.map(m=>s.jsxs(at,{className:`group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer ${r==="list"?"flex flex-row":""}`,onClick:()=>i(`/additional-services/${m.id}`),children:[s.jsx("div",{className:`relative overflow-hidden bg-muted ${r==="list"?"w-48 shrink-0":"aspect-[3/2]"}`,children:m.preview_image_url?s.jsx("img",{src:m.preview_image_url,alt:m.name,className:"w-full h-full object-contain group-hover:scale-105 transition-transform duration-300"}):s.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:s.jsx(cu,{className:"h-8 w-8"})})}),s.jsxs(ct,{className:`p-4 flex flex-col ${r==="list"?"flex-1":""}`,children:[s.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 mb-1",children:m.name}),m.description&&s.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 flex-1",children:m.description})]})]},m.id))})]})})},X9e=()=>{const{serviceId:t}=mu(),e=Bs(),{data:r,isLoading:n}=Sr({queryKey:["additional-service",t],queryFn:async()=>{const{data:i,error:o}=await ae.from("additional_services").select("*").eq("id",t).eq("is_published",!0).single();if(o)throw o;return i},enabled:!!t});return n?s.jsx(Jr,{title:"Loading...",children:s.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[s.jsx(Dn,{className:"h-8 w-48"}),s.jsx(Dn,{className:"h-64 w-full rounded-lg"}),s.jsx(Dn,{className:"h-24 w-full"})]})}):r?s.jsx(Jr,{title:r.name,children:s.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[s.jsxs(de,{variant:"ghost",onClick:()=>e("/additional-services"),className:"gap-2",children:[s.jsx(Ka,{className:"h-4 w-4"}),"Back to Services"]}),s.jsx(at,{className:"overflow-hidden",children:s.jsx("div",{className:"relative bg-muted",children:r.preview_image_url?s.jsx("img",{src:r.preview_image_url,alt:r.name,className:"w-full h-auto max-h-[500px] object-contain mx-auto"}):s.jsx("div",{className:"w-full h-64 flex items-center justify-center text-muted-foreground",children:s.jsx(cu,{className:"h-16 w-16"})})})}),s.jsx(at,{children:s.jsxs(ct,{className:"p-6 space-y-6",children:[s.jsxs("div",{children:[s.jsx("h1",{className:"text-2xl font-bold text-foreground mb-2",children:r.name}),s.jsxs("div",{className:"flex items-center text-sm text-muted-foreground",children:[s.jsx(ko,{className:"h-4 w-4 mr-1"}),"Published ",Vn(new Date(r.publish_date),"MMMM d, yyyy")]})]}),r.description&&s.jsx("div",{className:"prose prose-sm max-w-none text-muted-foreground [&_a]:text-primary [&_a]:underline",dangerouslySetInnerHTML:{__html:r.description}}),s.jsx("div",{className:"pt-4 border-t",children:s.jsxs(de,{size:"lg",className:"gap-2",onClick:()=>window.open(r.signup_link_url,"_blank"),children:[s.jsx(oa,{className:"h-5 w-5"}),"Sign Up Now"]})})]})})]})}):s.jsx(Jr,{title:"Not Found",children:s.jsxs("div",{className:"max-w-4xl mx-auto text-center py-12",children:[s.jsx("h2",{className:"text-2xl font-bold text-foreground mb-4",children:"Service Not Found"}),s.jsx("p",{className:"text-muted-foreground mb-6",children:"The service you're looking for doesn't exist or has been removed."}),s.jsxs(de,{onClick:()=>e("/additional-services"),children:[s.jsx(Ka,{className:"h-4 w-4 mr-2"}),"Back to Services"]})]})})},bC=[{id:"content-calendar",name:"Social Media Content Calendar Generator",iframe:``},{id:"property-promotion",name:"Property Promotion AI Tool",iframe:''},{id:"bio-boost",name:"Realtor Bio-Boost",iframe:''},{id:"market-report",name:"Market Report & Video Script Generator",iframe:''},{id:"property-description",name:"Property Description Writer",iframe:''},{id:"newsletter-generator",name:"Local Real Estate Newsletter Generator",iframe:''}];function Q9e(){const[t,e]=D.useState(bC[0].id),r=bC.find(n=>n.id===t)||bC[0];return s.jsx(Jr,{title:"AI Toolkit",children:s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:s.jsx(N5,{className:"h-6 w-6 text-primary"})}),s.jsxs("div",{children:[s.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"AI Toolkit"}),s.jsx("p",{className:"text-muted-foreground",children:"Powerful AI tools to boost your real estate business"})]})]}),s.jsx("div",{className:"md:hidden",children:s.jsxs(Kn,{value:t,onValueChange:e,children:[s.jsx(qn,{className:"w-full",children:s.jsx(Zn,{placeholder:"Select a tool"})}),s.jsx(Hn,{children:bC.map(n=>s.jsx(_r,{value:n.id,children:n.name},n.id))})]})}),s.jsx("div",{className:"hidden md:block",children:s.jsx(go,{value:t,onValueChange:e,className:"w-full",children:s.jsx(ao,{className:"w-full flex-wrap h-auto gap-1 bg-muted p-1",children:bC.map(n=>s.jsx(Bn,{value:n.id,className:"flex-1 min-w-[150px] text-xs lg:text-sm whitespace-normal h-auto py-2",children:n.name},n.id))})})}),s.jsx("div",{className:"flex justify-center",children:s.jsx("div",{className:"w-full max-w-[700px]",dangerouslySetInnerHTML:{__html:r.iframe}})})]})})}const QJ="agent-os-onboarding-completed",WP=[{icon:G2,iconColor:"text-white",bgGradient:"from-primary via-primary/80 to-purple-600",title:"Welcome to Agent OS",description:"You've unlocked a powerful new tool designed to help you build stronger relationships and close more deals. Agent OS is currently in beta, and we're excited for you to try it!",highlights:["Manage your most important relationships","Stay in touch with automated reminders","Track your transactions and goals","Maximize referrals from your sphere"]},{icon:koe,iconColor:"text-white",bgGradient:"from-pink-500 via-rose-500 to-red-500",title:"InnerCircle Home",description:"Your daily command center. See today's action items, track your momentum streak, and get a snapshot of your relationship health—all at a glance.",highlights:["Today's touchpoints and special dates","Momentum stats and streak tracking","Relationship health overview","Quick access to all features"]},{icon:_i,iconColor:"text-white",bgGradient:"from-blue-500 via-indigo-500 to-purple-500",title:"Contacts",description:"Import and organize your sphere of influence. Tag contacts by relationship type (Top 25, Past Clients, Referral Partners, etc.) to prioritize your outreach.",highlights:["Import contacts via CSV","Tag by relationship type","Track birthdays and home anniversaries","See relationship health scores"]},{icon:H2,iconColor:"text-white",bgGradient:"from-emerald-500 via-teal-500 to-cyan-500",title:"Touchpoint Plans",description:"Assign automated touchpoint schedules to your contact groups. Each plan tells you exactly who to reach out to and when—with pre-written scripts to make it easy.",highlights:["Pre-built 12-month plans","Create your own custom plans","Scripts for calls, texts, and emails","Automatic daily action items"]},{icon:yd,iconColor:"text-white",bgGradient:"from-orange-500 via-amber-500 to-yellow-500",title:"Popbys",description:"Pop-by visits are one of the most powerful ways to stay top-of-mind. Track your gift drop-offs and see who's due for a visit on the map.",highlights:["Track pop-by gift ideas","Set visit frequency by contact type","Log completed pop-bys","Map view for route planning"]},{icon:_p,iconColor:"text-white",bgGradient:"from-purple-500 via-violet-500 to-indigo-500",title:"Scorecard",description:"Track your transactions, set goals, and see your progress over time. Know exactly where your business stands and where your deals are coming from.",highlights:["Log buyer and seller transactions","Set and track annual goals","See your top lead sources","Export data for your records"]}],J9e=()=>{const[t,e]=D.useState(!1),[r,n]=D.useState(0),[i,o]=D.useState(!1);D.useEffect(()=>{if(!localStorage.getItem(QJ)){const P=setTimeout(()=>e(!0),500);return()=>clearTimeout(P)}},[]);const c=()=>{r{n(r+1),o(!1)},150)):m()},a=()=>{m()},m=()=>{localStorage.setItem(QJ,"true"),e(!1)},g=WP[r],_=g.icon,j=r===WP.length-1,N=C=>{C||m(),e(C)};return s.jsx(mn,{open:t,onOpenChange:N,children:s.jsxs(pn,{className:"sm:max-w-lg overflow-hidden p-0 gap-0",children:[s.jsxs("div",{className:`relative bg-gradient-to-br ${g.bgGradient} p-8 pb-12 transition-all duration-500`,children:[s.jsxs("div",{className:"absolute inset-0 overflow-hidden",children:[s.jsx("div",{className:"absolute -top-4 -right-4 w-32 h-32 bg-white/10 rounded-full blur-2xl animate-pulse"}),s.jsx("div",{className:"absolute -bottom-8 -left-8 w-40 h-40 bg-white/10 rounded-full blur-3xl animate-pulse",style:{animationDelay:"1s"}}),s.jsx("div",{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-64 h-64 bg-white/5 rounded-full blur-3xl"})]}),s.jsxs("div",{className:`relative mx-auto flex h-20 w-20 items-center justify-center transition-all duration-300 ${i?"scale-75 opacity-0":"scale-100 opacity-100"}`,children:[s.jsx("div",{className:"absolute inset-0 bg-white/20 rounded-2xl blur-xl"}),s.jsx("div",{className:"relative flex h-20 w-20 items-center justify-center rounded-2xl bg-white/20 backdrop-blur-sm border border-white/30 shadow-2xl",children:s.jsx(_,{className:`h-10 w-10 ${g.iconColor} drop-shadow-lg`})})]}),r===0&&s.jsxs("div",{className:"absolute top-4 right-4 px-3 py-1 rounded-full bg-white/20 backdrop-blur-sm border border-white/30 text-white text-xs font-medium flex items-center gap-1.5",children:[s.jsx(cu,{className:"h-3 w-3"}),"Beta"]})]}),s.jsxs("div",{className:"p-6 pt-4",children:[s.jsxs(xn,{className:"text-center sm:text-center pb-2",children:[s.jsx(gn,{className:`text-2xl font-bold transition-all duration-300 ${i?"translate-y-2 opacity-0":"translate-y-0 opacity-100"}`,children:g.title}),s.jsx(fi,{className:`text-base pt-2 transition-all duration-300 delay-75 ${i?"translate-y-2 opacity-0":"translate-y-0 opacity-100"}`,children:g.description})]}),g.highlights&&s.jsx("div",{className:`space-y-2.5 py-4 transition-all duration-300 delay-100 ${i?"translate-y-2 opacity-0":"translate-y-0 opacity-100"}`,children:g.highlights.map((C,P)=>s.jsxs("div",{className:"flex items-center gap-3 group",style:{transitionDelay:`${150+P*50}ms`},children:[s.jsx("div",{className:`flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-gradient-to-br ${g.bgGradient} shadow-sm`,children:s.jsx(ru,{className:"h-3.5 w-3.5 text-white"})}),s.jsx("span",{className:"text-sm text-muted-foreground group-hover:text-foreground transition-colors",children:C})]},P))}),s.jsx("div",{className:"flex justify-center gap-2 py-4",children:WP.map((C,P)=>s.jsx("button",{onClick:()=>{P!==r&&(o(!0),setTimeout(()=>{n(P),o(!1)},150))},className:`h-2 rounded-full transition-all duration-300 ${P===r?"w-8 bg-gradient-to-r "+g.bgGradient:P{const Me=parseInt(V,10);if(isNaN(Me)||Me<1){na({title:"Invalid goal",description:"Please enter a number greater than 0",variant:"destructive"});return}te(Me),cpe(Me),W(!1),na({title:"Goal updated",description:`Weekly touch goal set to ${Me}`})},ie=()=>{K(Q.toString()),W(!0)};D.useEffect(()=>{(async()=>{if(!(e!=null&&e.id))return;const{data:Oe}=await ae.from("profiles").select("name").eq("id",e.id).single();Oe!=null&&Oe.name&&R(Oe.name.split(" ")[0])})()},[e==null?void 0:e.id]),D.useEffect(()=>{a.mutate()},[]);const he=Cp(new Date),xe=hc(he,7),pe=Me=>{if(!Me)return null;const Oe=new Date(Me);return new Date(he.getFullYear(),Oe.getMonth(),Oe.getDate())},ve=(i==null?void 0:i.filter(Me=>{const Oe=pe(Me.birthday),Ie=pe(Me.home_anniversary);return Oe&&Wo(Oe,he)||Ie&&Wo(Ie,he)}))||[],ge=(i==null?void 0:i.filter(Me=>{if(!Me.birthday&&!Me.home_anniversary)return!1;const Oe=Ie=>{if(!Ie)return!1;const Be=pe(Ie);return Be?UM(Be,he)&&lq(Be,xe):!1};return Oe(Me.birthday)||Oe(Me.home_anniversary)}).slice(0,5))||[],ke=ve.map(Me=>{var Pe,ut,jt;const Oe=pe(Me.birthday),Ie=Oe&&Wo(Oe,he),Be=(o==null?void 0:o.find($t=>$t.name==="Call"))||(o==null?void 0:o[0]);return{contact:Me,actionType:Be||{id:"special-date",name:Ie?"Birthday Call":"Anniversary Call",icon:Ie?"Cake":"Home",color:Ie?"#EC4899":"#8B5CF6",description:Ie?"Wish them happy birthday!":"Celebrate their home anniversary!",active:!0,sort_order:0,created_at:"",updated_at:""},planName:Ie?"🎂 Birthday Today!":"🏠 Home Anniversary!",relationshipTypeName:((jt=(ut=(Pe=Me.tags)==null?void 0:Pe[0])==null?void 0:ut.relationship_type)==null?void 0:jt.name)||"",monthNumber:0,isSpecialDate:!0,specialDateType:Ie?"birthday":"anniversary"}}),Se=c!==void 0?c||[]:(i==null?void 0:i.slice(0,5).map((Me,Oe)=>{var Be,Pe,ut;const Ie=o==null?void 0:o[Oe%((o==null?void 0:o.length)||1)];return Ie?{contact:Me,actionType:Ie,planName:"Quick Touch",relationshipTypeName:((ut=(Pe=(Be=Me.tags)==null?void 0:Be[0])==null?void 0:Pe.relationship_type)==null?void 0:ut.name)||"",monthNumber:0}:null}).filter(Boolean))||[],je=[...ke,...Se],et=async(Me,Oe,Ie)=>{await _.mutateAsync({contactId:Me,actionTypeId:Oe,scriptUsedId:Ie}),I(!1),P(null)},bt=Me=>{Me.script?(P(Me),I(!0)):et(Me.contact.id,Me.actionType.id)},_e=Me=>JJ[Me||"Phone"]||Yl,Ye=Me=>JJ[Me||"Users"]||_i,pt=(Me,Oe)=>Me.replace(/\{\{FirstName\}\}/g,Oe.first_name).replace(/\{\{LastName\}\}/g,Oe.last_name||"").replace(/\{\{AgentName\}\}/g,O||"there"),nt=(Me,Oe)=>({Call:`Thinking of you, ${Oe}!`,Text:`Quick hello, ${Oe}`,Email:`Checking in, ${Oe}`,"Handwritten Note":`A note for ${Oe}`,Video:`Video message for ${Oe}`,Gift:`Something special for you, ${Oe}`})[Me]||`Hello ${Oe}!`,Qt=(Me,Oe,Ie)=>{const Be=`sms:${Me}`;if(Oe&&Ie){const Pe=pt(Oe,Ie);return`${Be}?body=${encodeURIComponent(Pe)}`}return Be},gt=(Me,Oe,Ie,Be,Pe)=>{const ut=`mailto:${Me}`,jt=[];if(Pe){const $t=Ie||nt(Be||"Email",Pe.first_name);if(jt.push(`subject=${encodeURIComponent($t)}`),Oe){const Ht=pt(Oe,Pe);jt.push(`body=${encodeURIComponent(Ht)}`)}}return jt.length>0?`${ut}?${jt.join("&")}`:ut};return s.jsxs(Jr,{title:"InnerCircle",description:"Your relationship-first contact system",children:[s.jsxs("div",{className:"space-y-6 overflow-x-hidden",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("h1",{className:"text-2xl font-bold",children:"InnerCircle"}),s.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-amber-500 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),s.jsxs("section",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[s.jsx("h2",{className:"text-xl font-semibold",children:"Today in Your InnerCircle"}),c!==void 0&&s.jsxs(ir,{variant:"outline",className:"gap-1",children:[s.jsx(cu,{className:"h-3 w-3"}),"Plan-based"]})]}),s.jsx(at,{children:s.jsx(ct,{className:"p-4",children:je.length===0?s.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[s.jsx("p",{children:"No actions scheduled for today."}),s.jsx("p",{className:"text-sm mt-1",children:"Add contacts and enable touchpoint plans to get started."}),s.jsx(de,{variant:"outline",className:"mt-4",onClick:()=>t("/innercircle/plans"),children:"Manage Plans"})]}):s.jsxs("div",{className:"flex gap-3 overflow-x-auto pb-2",children:[je.map((Me,Oe)=>{var Lt,Kt,Ar,rt,We,_t,Gt;const Ie=Me.isSpecialDate,Be=Me.specialDateType,Pe=Ie?Be==="birthday"?uM:ou:_e(((Lt=Me.actionType)==null?void 0:Lt.icon)||null),ut=Me.contact.phone,jt=Me.contact.email,$t=Ie?Be==="birthday"?"#EC4899":"#8B5CF6":((Kt=Me.actionType)==null?void 0:Kt.color)||"#3B82F6",Ht=Ie?Be==="birthday"?"🎂 Birthday Today!":"🏠 Home Anniversary!":(Ar=Me.actionType)==null?void 0:Ar.name;return s.jsxs("div",{className:`flex-shrink-0 w-[260px] border rounded-lg overflow-hidden ${Ie?"ring-2 ring-offset-2":""}`,style:Ie?{"--tw-ring-color":$t}:void 0,children:[s.jsxs("div",{className:"p-3 text-white flex items-center gap-2",style:{backgroundColor:$t},children:[s.jsx(Pe,{className:"h-4 w-4"}),s.jsx("span",{className:"font-medium text-sm",children:Ht})]}),s.jsxs("div",{className:"p-3 space-y-2",children:[s.jsxs("p",{className:"font-medium text-sm",children:[Me.contact.first_name," ",Me.contact.last_name]}),s.jsxs("div",{className:"flex gap-1.5",children:[ut&&s.jsxs(s.Fragment,{children:[s.jsxs("a",{href:`tel:${Me.contact.phone}`,className:"flex-1 flex items-center justify-center gap-1 px-2 py-1.5 bg-primary/10 hover:bg-primary/20 text-primary rounded text-xs font-medium transition-colors",title:"Call",children:[s.jsx(Yl,{className:"h-3 w-3"}),"Call"]}),s.jsxs("a",{href:Qt(Me.contact.phone,(rt=Me.script)==null?void 0:rt.script_body,Me.contact),className:"flex-1 flex items-center justify-center gap-1 px-2 py-1.5 bg-emerald-500/10 hover:bg-emerald-500/20 text-emerald-600 dark:text-emerald-400 rounded text-xs font-medium transition-colors",title:"Text",children:[s.jsx(Tf,{className:"h-3 w-3"}),"Text"]})]}),jt&&s.jsxs("a",{href:gt(Me.contact.email,(We=Me.script)==null?void 0:We.script_body,(_t=Me.script)==null?void 0:_t.email_subject,(Gt=Me.actionType)==null?void 0:Gt.name,Me.contact),className:"flex-1 flex items-center justify-center gap-1 px-2 py-1.5 bg-sky-500/10 hover:bg-sky-500/20 text-sky-600 dark:text-sky-400 rounded text-xs font-medium transition-colors",title:"Email",children:[s.jsx(Fo,{className:"h-3 w-3"}),"Email"]})]}),!ut&&!jt&&s.jsx("p",{className:"text-xs text-muted-foreground italic",children:"No contact info"}),s.jsxs("div",{className:"flex gap-1 flex-wrap",children:[Me.relationshipTypeName&&s.jsx(ir,{variant:"secondary",className:"text-xs",children:Me.relationshipTypeName}),Me.monthNumber>0&&s.jsxs(ir,{variant:"outline",className:"text-xs",children:["Month ",Me.monthNumber]})]}),Me.script&&s.jsx(de,{size:"sm",variant:"outline",className:"w-full",onClick:()=>bt(Me),children:"View Script"}),s.jsx(de,{size:"sm",className:"w-full",onClick:()=>{var rr;return et(Me.contact.id,Me.actionType.id,(rr=Me.script)==null?void 0:rr.id)},disabled:_.isPending,children:"Mark Complete"})]})]},Me.contact.id+Oe)}),s.jsx("div",{className:"flex-shrink-0 w-[100px] border rounded-lg flex items-center justify-center",children:s.jsxs(rg,{children:[s.jsx(ng,{asChild:!0,children:s.jsxs(de,{variant:"ghost",className:"h-full w-full",children:[s.jsx(K6,{className:"h-5 w-5 mr-2"}),"More"]})}),s.jsx(Op,{children:s.jsx(Ro,{onClick:()=>t("/innercircle/contacts"),children:"View all contacts"})})]})})]})})})]}),s.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[s.jsxs(at,{className:"md:col-span-2",children:[s.jsx(xr,{className:"pb-2",children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(wr,{className:"text-lg",children:"Momentum"}),s.jsxs(mn,{open:z,onOpenChange:W,children:[s.jsx(Do,{asChild:!0,children:s.jsx("button",{onClick:ie,className:"p-0.5 rounded hover:bg-muted transition-colors","aria-label":"Edit weekly goal",children:s.jsx(eg,{className:"h-4 w-4 text-muted-foreground hover:text-primary"})})}),s.jsxs(pn,{className:"sm:max-w-[360px]",children:[s.jsxs(xn,{children:[s.jsx(gn,{children:"Set Weekly Goal"}),s.jsx(fi,{children:"How many touches do you want to complete each week?"})]}),s.jsxs("div",{className:"space-y-4 pt-2",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"weekly-goal-ic",children:"Weekly touch goal"}),s.jsx(Et,{id:"weekly-goal-ic",type:"number",min:"1",value:V,onChange:Me=>K(Me.target.value),placeholder:"20",onKeyDown:Me=>{Me.key==="Enter"&&X()}})]}),s.jsx(de,{onClick:X,className:"w-full",children:"Save Goal"})]})]})]})]})}),s.jsxs(ct,{className:"space-y-4",children:[s.jsx(vc,{value:Math.min(m.actionsThisWeek/Q*100,100),className:"h-3 w-full max-w-full"}),s.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[s.jsx(doe,{className:"h-5 w-5 text-orange-500"}),s.jsxs("span",{className:"font-medium",children:[m.actionsThisWeek," / ",Q]}),s.jsx("span",{className:"text-muted-foreground",children:"Actions Completed This Week"})]}),m.streak>0&&s.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[s.jsx("span",{className:"text-lg",children:"🔥"}),s.jsx("span",{className:"font-medium",children:"Great Job!"}),s.jsxs("span",{className:"text-muted-foreground",children:["Keep Your Streak Going! (",m.streak," days)"]})]})]})]}),s.jsxs(at,{children:[s.jsx(xr,{className:"pb-2",children:s.jsx(wr,{className:"text-lg",children:"Upcoming Reminders"})}),s.jsxs(ct,{className:"space-y-3",children:[ge.length>0?ge.map(Me=>{const Oe=Me.birthday,Ie=Me.home_anniversary;return s.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[Oe?s.jsx("span",{className:"text-lg",children:"🎂"}):s.jsx("span",{className:"text-lg",children:"🏠"}),s.jsxs("div",{children:[s.jsxs("span",{className:"font-medium",children:[Me.first_name,"'s"]}),s.jsxs("span",{className:"text-muted-foreground",children:[" ",Oe?"Birthday":"Home Anniversary"]}),s.jsxs("div",{className:"text-xs text-muted-foreground",children:[Oe&&Me.birthday&&Vn(new Date(Me.birthday),"MMM d"),Ie&&Me.home_anniversary&&Vn(new Date(Me.home_anniversary),"MMM d")]})]})]},Me.id)}):s.jsx("p",{className:"text-sm text-muted-foreground",children:"No upcoming reminders"}),g.count>0&&s.jsxs("button",{onClick:()=>t("/innercircle/contacts?filter=not-touched-90"),className:"flex items-start gap-2 text-sm pt-2 border-t w-full text-left hover:bg-accent/50 -mx-4 px-4 py-2 rounded-md transition-colors",children:[s.jsx(No,{className:"h-4 w-4 text-orange-500 mt-0.5"}),s.jsxs("div",{children:[s.jsxs("span",{className:"font-medium text-orange-600 dark:text-orange-400",children:[g.count," Contact",g.count!==1?"s":""]}),s.jsx("span",{className:"text-muted-foreground",children:" Not Reached in 90+ Days"})]}),s.jsx(wd,{className:"h-4 w-4 text-muted-foreground ml-auto mt-0.5"})]})]})]}),s.jsx(wpe,{})]}),s.jsxs("section",{children:[s.jsx("h2",{className:"text-xl font-semibold mb-4",children:"Your InnerCircle"}),s.jsx("div",{className:"flex flex-wrap gap-3",children:r==null?void 0:r.filter(Me=>Me.active).map(Me=>{const Oe=Ye(Me.icon),Ie=(n==null?void 0:n[Me.id])||0,Be=j===Me.id,Pe=e7e[Me.name]||"bg-secondary text-secondary-foreground";return s.jsxs("button",{onClick:()=>{Be?(N(null),t("/innercircle/contacts")):(N(Me.id),t(`/innercircle/contacts?type=${Me.id}`))},className:` flex items-center gap-2 px-4 py-3 rounded-lg border transition-all ${Be?Pe:"bg-card hover:bg-accent"} `,children:[s.jsx(Oe,{className:"h-5 w-5"}),s.jsxs("div",{className:"text-left",children:[s.jsx("div",{className:"font-medium",children:Me.name}),s.jsxs("div",{className:`text-sm ${Be?"opacity-90":"text-muted-foreground"}`,children:[Ie," Contacts"]})]})]},Me.id)})})]}),s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:[s.jsxs(de,{onClick:()=>t("/innercircle/video/record"),className:"w-full bg-gradient-to-r from-primary to-primary/80",children:[s.jsx(uoe,{className:"h-4 w-4 mr-1"}),"Quick Video"]}),s.jsxs(de,{onClick:()=>t("/innercircle/contacts"),className:"w-full",variant:"outline",children:["View Contacts",s.jsx(wd,{className:"h-4 w-4 ml-1"})]}),s.jsx(de,{variant:"outline",onClick:()=>t("/innercircle/video-library"),className:"w-full",children:"Video Library"}),s.jsx(de,{variant:"outline",onClick:()=>t("/innercircle/plans"),className:"w-full",children:"Manage Plans"})]})]}),s.jsx(mn,{open:A,onOpenChange:I,children:s.jsxs(pn,{className:"max-w-md",children:[s.jsx(xn,{children:s.jsx(gn,{className:"flex items-center gap-2",children:C&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:C.actionType.color||"#3B82F6"}}),C.actionType.name," Script"]})})}),C&&C.script&&s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"text-sm text-muted-foreground",children:["For: ",s.jsxs("span",{className:"font-medium text-foreground",children:[C.contact.first_name," ",C.contact.last_name]})]}),s.jsx("div",{className:"bg-muted p-4 rounded-lg",children:s.jsx("p",{className:"whitespace-pre-wrap",children:pt(C.script.script_body,C.contact)})}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(de,{variant:"outline",className:"flex-1",onClick:()=>I(!1),children:"Close"}),s.jsx(de,{className:"flex-1",onClick:()=>{var Me;return et(C.contact.id,C.actionType.id,(Me=C.script)==null?void 0:Me.id)},disabled:_.isPending,children:"Mark Complete"})]})]})]})}),s.jsx(J9e,{})]})}const Xz=768;function jH(){const[t,e]=D.useState(void 0);return D.useEffect(()=>{const r=window.matchMedia(`(max-width: ${Xz-1}px)`),n=()=>{e(window.innerWidthr.removeEventListener("change",n)},[]),!!t}const r7e={warm:{label:"Warm",emoji:"🟢",bgClass:"bg-emerald-500",textClass:"text-emerald-600 dark:text-emerald-400",borderClass:"border-emerald-500",bgLightClass:"bg-emerald-500/10"},cooling:{label:"Cooling Off",emoji:"🟡",bgClass:"bg-amber-500",textClass:"text-amber-600 dark:text-amber-400",borderClass:"border-amber-500",bgLightClass:"bg-amber-500/10"},"at-risk":{label:"At Risk",emoji:"🔴",bgClass:"bg-red-500",textClass:"text-red-600 dark:text-red-400",borderClass:"border-red-500",bgLightClass:"bg-red-500/10"}},n7e={sm:{dot:"h-2 w-2",text:"text-xs",badge:"px-1.5 py-0.5 gap-1"},md:{dot:"h-2.5 w-2.5",text:"text-sm",badge:"px-2 py-1 gap-1.5"},lg:{dot:"h-3 w-3",text:"text-base",badge:"px-3 py-1.5 gap-2"}};function eee({score:t,showScore:e=!1,showTooltip:r=!0,size:n="sm",className:i}){const o=r7e[t.status],c=n7e[n],a=s.jsxs("div",{className:ar("inline-flex items-center rounded-full font-medium",o.bgLightClass,o.textClass,c.badge,c.text,i),children:[s.jsx("span",{className:ar("rounded-full",o.bgClass,c.dot)}),e?s.jsx("span",{children:t.score}):s.jsx("span",{children:o.label})]});return r?s.jsx(fle,{children:s.jsxs(ple,{children:[s.jsx(mle,{asChild:!0,children:a}),s.jsx(l8,{side:"top",className:"w-64 p-3",children:s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"font-semibold",children:"Relationship Score"}),s.jsxs("span",{className:ar("font-bold",o.textClass),children:[t.score,"/100"]})]}),s.jsx(vc,{value:t.score,className:"h-2"}),s.jsxs("div",{className:"space-y-1.5 text-xs",children:[s.jsxs("div",{className:"flex justify-between",children:[s.jsx("span",{className:"text-muted-foreground",children:"Recency"}),s.jsxs("span",{children:[t.breakdown.recency,"/40"]})]}),s.jsxs("div",{className:"flex justify-between",children:[s.jsx("span",{className:"text-muted-foreground",children:"Touchpoints (12mo)"}),s.jsxs("span",{children:[t.breakdown.touchpoints,"/30"]})]}),s.jsxs("div",{className:"flex justify-between",children:[s.jsx("span",{className:"text-muted-foreground",children:"Transactions"}),s.jsxs("span",{children:[t.breakdown.transactions,"/20"]})]}),s.jsxs("div",{className:"flex justify-between",children:[s.jsx("span",{className:"text-muted-foreground",children:"Referrals"}),s.jsxs("span",{children:[t.breakdown.referrals,"/10"]})]})]}),t.daysSinceTouch!==null&&s.jsxs("p",{className:"text-xs text-muted-foreground pt-1 border-t",children:["Last contact: ",t.daysSinceTouch===0?"Today":`${t.daysSinceTouch} days ago`]}),t.daysSinceTouch===null&&s.jsx("p",{className:"text-xs text-muted-foreground pt-1 border-t italic",children:"Never contacted"})]})})]})}):a}const s7e=[{key:"first_name",label:"First Name",required:!0},{key:"last_name",label:"Last Name",required:!1},{key:"email",label:"Email",required:!1},{key:"phone",label:"Phone",required:!1},{key:"address",label:"Street Address",required:!1},{key:"city",label:"City",required:!1},{key:"state",label:"State",required:!1},{key:"zip",label:"Zip Code",required:!1},{key:"spouse_name",label:"Spouse Name",required:!1},{key:"company_name",label:"Company",required:!1},{key:"job_title",label:"Job Title",required:!1},{key:"birthday",label:"Birthday",required:!1},{key:"home_anniversary",label:"Home Anniversary",required:!1},{key:"notes",label:"Notes",required:!1}],i7e=({open:t,onOpenChange:e,relationshipTypes:r,onSuccess:n})=>{const{user:i}=rn(),{toast:o}=Ri(),c=D.useRef(null),[a,m]=D.useState("upload"),[g,_]=D.useState([]),[j,N]=D.useState([]),[C,P]=D.useState({}),[A,I]=D.useState([]),[O,R]=D.useState([]),[z,W]=D.useState(!1),[V,K]=D.useState(null),Q=()=>{m("upload"),_([]),N([]),P({}),I([]),R([]),K(null),c.current&&(c.current.value="")},te=()=>{Q(),e(!1)},X=Ce=>{const Se=Ce.split(` `).map(_e=>_e.trim()).filter(_e=>_e);if(Se.length===0)return{headers:[],data:[]};const je=_e=>{const Ye=[];let pt="",nt=!1;for(let Qt=0;Qt<_e.length;Qt++){const gt=_e[Qt];gt==='"'?nt=!nt:(gt===","||gt===" ")&&!nt?(Ye.push(pt.trim()),pt=""):pt+=gt}return Ye.push(pt.trim()),Ye},et=je(Se[0]),bt=Se.slice(1).map(je);return{headers:et,data:bt}},ie=Ce=>{var et;const Se=(et=Ce.target.files)==null?void 0:et[0];if(!Se)return;const je=new FileReader;je.onload=bt=>{var Qt;const _e=(Qt=bt.target)==null?void 0:Qt.result,{headers:Ye,data:pt}=X(_e);if(Ye.length===0){o({title:"No data found",description:"The CSV file appears to be empty.",variant:"destructive"});return}_(Ye),N(pt);const nt={};Ye.forEach(gt=>{const Me=gt.toLowerCase().replace(/[_\s-]/g,"");Me.includes("firstname")||Me==="first"?nt.first_name=gt:Me.includes("lastname")||Me==="last"?nt.last_name=gt:Me.includes("email")?nt.email=gt:Me.includes("phone")||Me.includes("mobile")||Me.includes("cell")?nt.phone=gt:Me.includes("address")||Me.includes("street")?nt.address=gt:Me==="city"?nt.city=gt:Me==="state"||Me==="province"?nt.state=gt:Me==="zip"||Me==="zipcode"||Me==="postalcode"?nt.zip=gt:Me.includes("spouse")||Me.includes("partner")?nt.spouse_name=gt:Me.includes("company")||Me.includes("organization")||Me.includes("business")?nt.company_name=gt:Me.includes("jobtitle")||Me.includes("title")||Me.includes("position")?nt.job_title=gt:Me.includes("birthday")||Me.includes("dob")||Me.includes("birthdate")?nt.birthday=gt:Me.includes("anniversary")||Me.includes("homeanniversary")?nt.home_anniversary=gt:(Me.includes("notes")||Me.includes("comment"))&&(nt.notes=gt)}),P(nt),m("mapping")},je.readAsText(Se)},he=(Ce,Se)=>{P(je=>{if(Se==="none"){const{[Ce]:et,...bt}=je;return bt}return{...je,[Ce]:Se}})},xe=Ce=>{I(Se=>Se.includes(Ce)?Se.filter(je=>je!==Ce):[...Se,Ce])},pe=()=>{const Ce=j.map(Se=>{const je=_e=>{const Ye=C[_e];if(!Ye)return"";const pt=g.indexOf(Ye);return pt>=0?(Se[pt]||"").trim():""},et=je("first_name"),bt=et.length>0;return{first_name:et,last_name:je("last_name"),email:je("email"),phone:je("phone"),address:je("address"),city:je("city"),state:je("state"),zip:je("zip"),spouse_name:je("spouse_name"),company_name:je("company_name"),job_title:je("job_title"),birthday:je("birthday"),home_anniversary:je("home_anniversary"),notes:je("notes"),isValid:bt,error:bt?void 0:"First name is required"}});R(Ce),m("preview")},ve=async()=>{if(!(i!=null&&i.id))return;const Ce=O.filter(bt=>bt.isValid);if(Ce.length===0){o({title:"No valid contacts",description:"There are no valid contacts to import.",variant:"destructive"});return}W(!0);let Se=0,je=0,et=0;try{for(const bt of Ce)try{let _e=null;if(bt.email){const{data:pt}=await ae.from("innercircle_contacts").select("id").eq("owner_user_id",i.id).eq("email",bt.email).maybeSingle();_e=pt}if(!_e&&bt.phone){const{data:pt}=await ae.from("innercircle_contacts").select("id").eq("owner_user_id",i.id).eq("phone",bt.phone).maybeSingle();_e=pt}const Ye={owner_user_id:i.id,first_name:bt.first_name,last_name:bt.last_name||null,email:bt.email||null,phone:bt.phone||null,address:bt.address||null,city:bt.city||null,state:bt.state||null,zip:bt.zip||null,spouse_name:bt.spouse_name||null,company_name:bt.company_name||null,job_title:bt.job_title||null,birthday:bt.birthday||null,home_anniversary:bt.home_anniversary||null,notes:bt.notes||null};if(_e)await ae.from("innercircle_contacts").update(Ye).eq("id",_e.id),je++;else{const{data:pt}=await ae.from("innercircle_contacts").insert(Ye).select("id").single();pt&&A.length>0&&await ae.from("innercircle_contact_tags").insert(A.map(nt=>({contact_id:pt.id,relationship_type_id:nt}))),Se++}}catch(_e){console.error("Error importing contact:",_e),et++}K({created:Se,updated:je,failed:et}),m("result"),(Se>0||je>0)&&n(),o({title:"Import Complete",description:`${Se} created, ${je} updated${et>0?`, ${et} failed`:""}.`})}catch(bt){console.error("Import error:",bt),o({title:"Import Failed",description:bt.message||"Failed to import contacts",variant:"destructive"})}finally{W(!1)}},ge=O.filter(Ce=>Ce.isValid).length,ke=O.filter(Ce=>!Ce.isValid).length;return s.jsx(mn,{open:t,onOpenChange:te,children:s.jsxs(pn,{className:"max-w-3xl max-h-[85vh] overflow-hidden flex flex-col",children:[s.jsxs(xn,{children:[s.jsxs(gn,{className:"flex items-center gap-2",children:[s.jsx(JR,{className:"h-5 w-5"}),"Import Contacts from CSV"]}),s.jsx(fi,{children:"Upload a CSV file with your contacts. You can map columns and select relationship types."})]}),a==="upload"&&s.jsxs("div",{className:"space-y-4 py-4",children:[s.jsxs("div",{className:"border-2 border-dashed rounded-lg p-8 text-center",children:[s.jsx("input",{type:"file",accept:".csv,.txt",ref:c,onChange:ie,className:"hidden"}),s.jsx(Vu,{className:"h-10 w-10 mx-auto text-muted-foreground mb-4"}),s.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Click to upload or drag and drop a CSV file"}),s.jsx(de,{onClick:()=>{var Ce;return(Ce=c.current)==null?void 0:Ce.click()},children:"Select CSV File"})]}),s.jsxs("div",{className:"bg-muted/50 rounded-lg p-4 text-sm",children:[s.jsx("p",{className:"font-medium mb-2",children:"Supported Fields:"}),s.jsx("p",{className:"text-muted-foreground text-xs mb-3",children:"First Name, Last Name, Email, Phone, Street Address, City, State, Zip, Spouse Name, Company, Job Title, Birthday, Home Anniversary, Notes"}),s.jsxs(de,{variant:"outline",size:"sm",onClick:()=>{const Ce=`First Name,Last Name,Email,Phone,Street Address,City,State,Zip,Spouse Name,Company,Job Title,Birthday,Home Anniversary,Notes John,Doe,john@example.com,555-123-4567,123 Main St,Austin,TX,78701,Jane Doe,ABC Realty,Real Estate Agent,1985-06-15,2020-03-22,Met at open house`,Se=new Blob([Ce],{type:"text/csv"}),je=URL.createObjectURL(Se),et=document.createElement("a");et.href=je,et.download="contact_import_template.csv",et.click(),URL.revokeObjectURL(je)},children:[s.jsx(Pp,{className:"h-4 w-4 mr-2"}),"Download Template"]})]})]}),a==="mapping"&&s.jsxs("div",{className:"flex-1 overflow-auto space-y-4 py-4",children:[s.jsxs("div",{className:"space-y-3",children:[s.jsx(mt,{className:"text-base font-medium",children:"Map CSV Columns to Contact Fields"}),s.jsx("div",{className:"grid gap-3",children:s7e.map(Ce=>s.jsxs("div",{className:"flex items-center gap-4",children:[s.jsxs(mt,{className:"w-40 text-sm",children:[Ce.label,Ce.required&&s.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),s.jsxs(Kn,{value:C[Ce.key]||"none",onValueChange:Se=>he(Ce.key,Se),children:[s.jsx(qn,{className:"w-48",children:s.jsx(Zn,{placeholder:"Select column..."})}),s.jsxs(Hn,{children:[s.jsx(_r,{value:"none",children:"-- Not mapped --"}),g.map(Se=>s.jsx(_r,{value:Se,children:Se},Se))]})]})]},Ce.key))})]}),s.jsxs("div",{className:"space-y-3",children:[s.jsx(mt,{className:"text-base font-medium",children:"Apply Relationship Types (optional)"}),s.jsx("div",{className:"flex flex-wrap gap-2",children:r.map(Ce=>s.jsx(ir,{variant:A.includes(Ce.id)?"default":"outline",className:"cursor-pointer",onClick:()=>xe(Ce.id),children:Ce.name},Ce.id))})]}),s.jsx("div",{className:"bg-muted/50 rounded-lg p-3 text-sm",children:s.jsxs("p",{className:"text-muted-foreground",children:["Preview: ",j.length," row(s) found in CSV"]})})]}),a==="preview"&&s.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col space-y-4",children:[s.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(E_,{className:"h-4 w-4 text-green-500"}),s.jsxs("span",{children:[ge," valid"]})]}),ke>0&&s.jsxs("div",{className:"flex items-center gap-2 text-destructive",children:[s.jsx(sx,{className:"h-4 w-4"}),s.jsxs("span",{children:[ke," invalid"]})]})]}),s.jsxs("div",{className:"flex-1 overflow-auto border rounded-lg",children:[s.jsxs(ni,{children:[s.jsx(si,{children:s.jsxs(Dr,{className:"bg-muted/30",children:[s.jsx(Nt,{children:"First Name"}),s.jsx(Nt,{children:"Last Name"}),s.jsx(Nt,{children:"Email"}),s.jsx(Nt,{children:"Phone"}),s.jsx(Nt,{children:"Status"})]})}),s.jsx(ii,{children:O.slice(0,100).map((Ce,Se)=>s.jsxs(Dr,{children:[s.jsx(xt,{children:Ce.first_name}),s.jsx(xt,{children:Ce.last_name}),s.jsx(xt,{children:Ce.email}),s.jsx(xt,{children:Ce.phone}),s.jsx(xt,{children:Ce.isValid?s.jsx(ir,{variant:"default",className:"bg-green-500/10 text-green-600",children:"Valid"}):s.jsx(ir,{variant:"destructive",children:Ce.error||"Invalid"})})]},Se))})]}),O.length>100&&s.jsxs("p",{className:"text-sm text-muted-foreground text-center py-2",children:["Showing first 100 of ",O.length," contacts"]})]})]}),a==="result"&&V&&s.jsxs("div",{className:"space-y-4 py-4 text-center",children:[s.jsx(E_,{className:"h-12 w-12 mx-auto text-green-500"}),s.jsx("h3",{className:"text-lg font-semibold",children:"Import Complete"}),s.jsxs("p",{className:"text-muted-foreground",children:[V.created," contact(s) created, ",V.updated," updated"]}),V.failed>0&&s.jsxs("p",{className:"text-destructive",children:[V.failed," failed to import"]})]}),s.jsxs(zi,{children:[a==="upload"&&s.jsx(de,{variant:"outline",onClick:te,children:"Cancel"}),a==="mapping"&&s.jsxs(s.Fragment,{children:[s.jsx(de,{variant:"outline",onClick:Q,children:"Back"}),s.jsx(de,{onClick:pe,disabled:!C.first_name,children:"Continue"})]}),a==="preview"&&s.jsxs(s.Fragment,{children:[s.jsx(de,{variant:"outline",onClick:()=>m("mapping"),children:"Back"}),s.jsx(de,{onClick:ve,disabled:z||ge===0,children:z?s.jsxs(s.Fragment,{children:[s.jsx(Ps,{className:"mr-2 h-4 w-4 animate-spin"}),"Importing..."]}):`Import ${ge} Contact${ge!==1?"s":""}`})]}),a==="result"&&s.jsx(de,{onClick:te,children:"Done"})]})]})})};function a7e(){const t=Bs(),[e]=n0(),{user:r}=rn(),n=jH(),i=e.get("type"),o=e.get("filter"),c=e.get("new")==="true",{contactsWithScores:a,isLoading:m}=bpe(),{data:g}=sg(),_=npe(),j=spe(),N=ipe(),[C,P]=D.useState(""),[A,I]=D.useState(i||"all"),[O,R]=D.useState(o||"all"),[z,W]=D.useState(c),[V,K]=D.useState(null),[Q,te]=D.useState(!1);D.useEffect(()=>{o&&R(o)},[o]);const[X,ie]=D.useState({first_name:"",last_name:"",email:"",phone:"",address:"",city:"",state:"",zip:"",birthday:"",home_anniversary:"",notes:"",tagIds:[]});D.useEffect(()=>{c&&W(!0)},[c]),D.useEffect(()=>{var ge;V&&ie({first_name:V.first_name||"",last_name:V.last_name||"",email:V.email||"",phone:V.phone||"",address:V.address||"",city:V.city||"",state:V.state||"",zip:V.zip||"",birthday:V.birthday||"",home_anniversary:V.home_anniversary||"",notes:V.notes||"",tagIds:((ge=V.tags)==null?void 0:ge.map(ke=>ke.relationship_type_id))||[]})},[V]);const he=D.useMemo(()=>{if(!a)return[];let ge=a.filter(ke=>{var je,et,bt;const Ce=C===""||`${ke.first_name} ${ke.last_name}`.toLowerCase().includes(C.toLowerCase())||((je=ke.email)==null?void 0:je.toLowerCase().includes(C.toLowerCase()))||((et=ke.phone)==null?void 0:et.includes(C)),Se=A==="all"||((bt=ke.tags)==null?void 0:bt.some(_e=>_e.relationship_type_id===A));return Ce&&Se});return O==="not-touched-90"?ge=ge.filter(ke=>{const Ce=ke.relationshipScore.daysSinceTouch;return Ce===null||Ce>90}):O==="at-risk"?ge=ge.filter(ke=>ke.relationshipScore.status==="at-risk"):O==="cooling"?ge=ge.filter(ke=>ke.relationshipScore.status==="cooling"):O==="warm"&&(ge=ge.filter(ke=>ke.relationshipScore.status==="warm")),ge},[a,C,A,O]),xe=()=>{ie({first_name:"",last_name:"",email:"",phone:"",address:"",city:"",state:"",zip:"",birthday:"",home_anniversary:"",notes:"",tagIds:[]})},pe=async ge=>{ge.preventDefault(),V?(await j.mutateAsync({id:V.id,...X}),K(null)):(await _.mutateAsync(X),W(!1)),xe()},ve=async ge=>{confirm("Are you sure you want to delete this contact?")&&await N.mutateAsync(ge)};return s.jsx(Jr,{title:"Contacts",description:"Manage your InnerCircle contacts",children:s.jsxs("div",{className:"space-y-6 overflow-x-hidden",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("h1",{className:"text-2xl font-bold",children:"Contacts"}),s.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-amber-500 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),s.jsx("div",{className:"flex items-center gap-4",children:s.jsxs(de,{variant:"ghost",size:"sm",onClick:()=>t("/innercircle"),children:[s.jsx(I1,{className:"h-4 w-4 mr-1"}),"Back"]})}),s.jsx(at,{children:s.jsx(ct,{className:"p-4",children:s.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[s.jsxs("div",{className:"relative flex-1",children:[s.jsx(ba,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),s.jsx(Et,{placeholder:"Search by name, email, or phone...",value:C,onChange:ge=>P(ge.target.value),className:"pl-9"})]}),s.jsxs(Kn,{value:A,onValueChange:I,children:[s.jsx(qn,{className:"w-[160px]",children:s.jsx(Zn,{placeholder:"Filter by type"})}),s.jsxs(Hn,{children:[s.jsx(_r,{value:"all",children:"All Types"}),g==null?void 0:g.filter(ge=>ge.active).map(ge=>s.jsx(_r,{value:ge.id,children:ge.name},ge.id))]})]}),s.jsxs(Kn,{value:O,onValueChange:R,children:[s.jsx(qn,{className:"w-[160px]",children:s.jsx(Zn,{placeholder:"Filter by status"})}),s.jsxs(Hn,{children:[s.jsx(_r,{value:"all",children:"All Status"}),s.jsx(_r,{value:"warm",children:"🟢 Warm"}),s.jsx(_r,{value:"cooling",children:"🟡 Cooling Off"}),s.jsx(_r,{value:"at-risk",children:"🔴 At Risk"})]})]}),s.jsxs(de,{onClick:()=>W(!0),children:[s.jsx(Qn,{className:"h-4 w-4 mr-1"}),"Add Contact"]}),s.jsxs(de,{variant:"outline",onClick:()=>te(!0),children:[s.jsx(Vu,{className:"h-4 w-4 mr-1"}),"Import CSV"]})]})})}),n?s.jsx("div",{className:"space-y-3",children:m?s.jsx(at,{className:"p-6 text-center text-muted-foreground",children:"Loading contacts..."}):he.length===0?s.jsx(at,{className:"p-6 text-center text-muted-foreground",children:C||A!=="all"||O!=="all"?"No contacts match your search":"No contacts yet. Add your first contact!"}):he.map(ge=>{var Ce;const{relationshipScore:ke}=ge;return s.jsx(at,{className:"cursor-pointer hover:bg-accent/50 transition-colors",onClick:()=>t(`/innercircle/contacts/${ge.id}`),children:s.jsx(ct,{className:"p-4",children:s.jsxs("div",{className:"flex items-start justify-between",children:[s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[s.jsxs("h3",{className:"font-semibold text-base truncate",children:[ge.first_name," ",ge.last_name]}),s.jsx(wd,{className:"h-4 w-4 text-muted-foreground shrink-0"})]}),s.jsxs("div",{className:"space-y-1 text-sm mb-3",children:[ge.email&&s.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[s.jsx(Fo,{className:"h-3.5 w-3.5 shrink-0"}),s.jsx("span",{className:"truncate",children:ge.email})]}),ge.phone&&s.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[s.jsx(Yl,{className:"h-3.5 w-3.5 shrink-0"}),s.jsx("span",{children:ge.phone})]})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-1 mb-2",children:[s.jsx(eee,{score:ke,size:"sm"}),(Ce=ge.tags)==null?void 0:Ce.map(Se=>{var je;return s.jsx(ir,{variant:"secondary",className:"text-xs",children:(je=Se.relationship_type)==null?void 0:je.name},Se.id)})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-xs text-muted-foreground",children:[ke.lastTouchDate?s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsx(No,{className:"h-3 w-3"}),Vn(new Date(ke.lastTouchDate),"MMM d")]}):s.jsx("span",{className:"italic",children:"Never contacted"}),ge.birthday&&s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsx(ko,{className:"h-3 w-3"}),Vn(new Date(ge.birthday),"MMM d")]}),ge.home_anniversary&&s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsx(ou,{className:"h-3 w-3"}),Vn(new Date(ge.home_anniversary),"MMM d")]})]})]}),s.jsxs("div",{className:"flex flex-col gap-1 ml-2",children:[s.jsx(de,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:Se=>{Se.stopPropagation(),K(ge)},children:s.jsx(io,{className:"h-4 w-4"})}),s.jsx(de,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:Se=>{Se.stopPropagation(),ve(ge.id)},children:s.jsx(oi,{className:"h-4 w-4 text-destructive"})})]})]})})},ge.id)})}):s.jsx(at,{children:s.jsx(ct,{className:"p-0 overflow-x-auto",children:s.jsxs(ni,{className:"min-w-[600px]",children:[s.jsx(si,{children:s.jsxs(Dr,{children:[s.jsx(Nt,{children:"Name"}),s.jsx(Nt,{children:"Status"}),s.jsx(Nt,{children:"Contact Info"}),s.jsx(Nt,{children:"Relationship Types"}),s.jsx(Nt,{children:"Last Contact"}),s.jsx(Nt,{children:"Important Dates"}),s.jsx(Nt,{className:"w-[100px]",children:"Actions"})]})}),s.jsx(ii,{children:m?s.jsx(Dr,{children:s.jsx(xt,{colSpan:7,className:"text-center py-8",children:"Loading contacts..."})}):he.length===0?s.jsx(Dr,{children:s.jsx(xt,{colSpan:7,className:"text-center py-8 text-muted-foreground",children:C||A!=="all"||O!=="all"?"No contacts match your search":"No contacts yet. Add your first contact!"})}):he.map(ge=>{var Ce;const{relationshipScore:ke}=ge;return s.jsxs(Dr,{className:"cursor-pointer hover:bg-accent/50",onClick:()=>t(`/innercircle/contacts/${ge.id}`),children:[s.jsx(xt,{className:"font-medium",children:s.jsxs("div",{className:"flex items-center gap-2",children:[ge.first_name," ",ge.last_name]})}),s.jsx(xt,{children:s.jsx(eee,{score:ke,size:"sm"})}),s.jsx(xt,{children:s.jsxs("div",{className:"space-y-1 text-sm",children:[ge.email&&s.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[s.jsx(Fo,{className:"h-3 w-3"}),ge.email]}),ge.phone&&s.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[s.jsx(Yl,{className:"h-3 w-3"}),ge.phone]})]})}),s.jsx(xt,{children:s.jsx("div",{className:"flex flex-wrap gap-1",children:(Ce=ge.tags)==null?void 0:Ce.map(Se=>{var je;return s.jsx(ir,{variant:"secondary",className:"text-xs",children:(je=Se.relationship_type)==null?void 0:je.name},Se.id)})})}),s.jsx(xt,{children:s.jsx("div",{className:"text-sm",children:ke.lastTouchDate?s.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[s.jsx(No,{className:"h-3 w-3"}),Vn(new Date(ke.lastTouchDate),"MMM d, yyyy")]}):s.jsx("span",{className:"text-muted-foreground text-xs italic",children:"Never contacted"})})}),s.jsx(xt,{children:s.jsxs("div",{className:"space-y-1 text-sm text-muted-foreground",children:[ge.birthday&&s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsx(ko,{className:"h-3 w-3"}),Vn(new Date(ge.birthday),"MMM d")]}),ge.home_anniversary&&s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsx(ou,{className:"h-3 w-3"}),Vn(new Date(ge.home_anniversary),"MMM d")]})]})}),s.jsx(xt,{children:s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsx(de,{variant:"ghost",size:"sm",onClick:Se=>{Se.stopPropagation(),K(ge)},children:s.jsx(io,{className:"h-4 w-4"})}),s.jsx(de,{variant:"ghost",size:"sm",onClick:Se=>{Se.stopPropagation(),ve(ge.id)},children:s.jsx(oi,{className:"h-4 w-4 text-destructive"})})]})})]},ge.id)})})]})})}),s.jsx(mn,{open:z||!!V,onOpenChange:ge=>{ge||(W(!1),K(null),xe())},children:s.jsxs(pn,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[s.jsx(xn,{children:s.jsx(gn,{children:V?"Edit Contact":"Add Contact"})}),s.jsxs("form",{onSubmit:pe,className:"space-y-4",children:[s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"first_name",children:"First Name *"}),s.jsx(Et,{id:"first_name",value:X.first_name,onChange:ge=>ie({...X,first_name:ge.target.value}),required:!0})]}),s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"last_name",children:"Last Name"}),s.jsx(Et,{id:"last_name",value:X.last_name,onChange:ge=>ie({...X,last_name:ge.target.value})})]})]}),s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"email",children:"Email"}),s.jsx(Et,{id:"email",type:"email",value:X.email,onChange:ge=>ie({...X,email:ge.target.value})})]}),s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"phone",children:"Phone"}),s.jsx(Et,{id:"phone",value:X.phone,onChange:ge=>ie({...X,phone:ge.target.value})})]}),s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"address",children:"Address"}),s.jsx(Et,{id:"address",value:X.address,onChange:ge=>ie({...X,address:ge.target.value}),placeholder:"Street address"})]}),s.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"city",children:"City"}),s.jsx(Et,{id:"city",value:X.city,onChange:ge=>ie({...X,city:ge.target.value})})]}),s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"state",children:"State"}),s.jsx(Et,{id:"state",value:X.state,onChange:ge=>ie({...X,state:ge.target.value})})]}),s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"zip",children:"Zip"}),s.jsx(Et,{id:"zip",value:X.zip,onChange:ge=>ie({...X,zip:ge.target.value})})]})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"birthday",children:"Birthday"}),s.jsx(Et,{id:"birthday",type:"date",value:X.birthday,onChange:ge=>ie({...X,birthday:ge.target.value})})]}),s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"home_anniversary",children:"Home Anniversary"}),s.jsx(Et,{id:"home_anniversary",type:"date",value:X.home_anniversary,onChange:ge=>ie({...X,home_anniversary:ge.target.value})})]})]}),s.jsxs("div",{children:[s.jsx(mt,{children:"Relationship Types"}),s.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:g==null?void 0:g.filter(ge=>ge.active).map(ge=>s.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[s.jsx(dx,{checked:X.tagIds.includes(ge.id),onCheckedChange:ke=>{ie(ke?{...X,tagIds:[...X.tagIds,ge.id]}:{...X,tagIds:X.tagIds.filter(Ce=>Ce!==ge.id)})}}),s.jsx("span",{className:"text-sm",children:ge.name})]},ge.id))})]}),s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"notes",children:"Notes"}),s.jsx(mi,{id:"notes",value:X.notes,onChange:ge=>ie({...X,notes:ge.target.value}),rows:3})]}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(de,{type:"button",variant:"outline",onClick:()=>{W(!1),K(null),xe()},children:"Cancel"}),s.jsxs(de,{type:"submit",disabled:_.isPending||j.isPending,children:[V?"Update":"Create"," Contact"]})]})]})]})}),s.jsx(i7e,{open:Q,onOpenChange:te,relationshipTypes:(g==null?void 0:g.filter(ge=>ge.active))||[],onSuccess:()=>{te(!1)}})]})})}function o7e(){return Sr({queryKey:["video-script-categories"],queryFn:async()=>{const{data:t,error:e}=await ae.from("video_script_categories").select("*").order("sort_order");if(e)throw e;return t}})}function l7e(t){return Sr({queryKey:["video-scripts",t],queryFn:async()=>{let e=ae.from("video_scripts").select("*, category:video_script_categories(*)").eq("is_active",!0).order("title");const{data:r,error:n}=await e;if(n)throw n;return r}})}function c7e(){const{user:t}=rn();return Sr({queryKey:["user-video-scripts",t==null?void 0:t.id],queryFn:async()=>{if(!(t!=null&&t.id))return[];const{data:e,error:r}=await ae.from("user_video_scripts").select("*, category:video_script_categories(*)").eq("owner_user_id",t.id).order("title");if(r)throw r;return e},enabled:!!(t!=null&&t.id)})}function u7e(){const{user:t}=rn(),e=Wn();return zr({mutationFn:async r=>{if(!(t!=null&&t.id))throw new Error("Not authenticated");const{data:n,error:i}=await ae.from("user_video_scripts").insert([{owner_user_id:t.id,source_script_id:r.id,category_id:r.category_id,title:r.title,script_text:r.script_text,tags:r.tags,is_custom:!1}]).select().single();if(i)throw i;return n},onSuccess:()=>{e.invalidateQueries({queryKey:["user-video-scripts"]})}})}function d7e(t){const{user:e}=rn();return Sr({queryKey:["agent-videos",e==null?void 0:e.id,t],queryFn:async()=>{if(!(e!=null&&e.id))return[];let r=ae.from("agent_videos").select("*, contact:innercircle_contacts(id, first_name, last_name)").eq("owner_user_id",e.id).order("created_at",{ascending:!1});r=r.eq("is_deleted",!1);const{data:n,error:i}=await r;if(i)throw i;return n},enabled:!!(e!=null&&e.id)})}function h7e(t){return Sr({queryKey:["agent-video",t],queryFn:async()=>{const{data:e,error:r}=await ae.from("agent_videos").select("*, contact:innercircle_contacts(id, first_name, last_name)").eq("id",t).single();if(r)throw r;return e},enabled:!!t})}function f7e(){const{user:t}=rn(),e=Wn();return zr({mutationFn:async r=>{if(!(t!=null&&t.id))throw new Error("Not authenticated");const{data:n,error:i}=await ae.from("agent_videos").insert([{owner_user_id:t.id,contact_id:r.contact_id,bunny_video_id:r.bunny_video_id,playback_url:r.playback_url,thumbnail_url:r.thumbnail_url,preview_url:r.preview_url,duration_seconds:r.duration_seconds,file_size_mb:r.file_size_mb||0,title:r.title,notes:r.notes,task_id:r.task_id,status:r.status||"processing",touch_type:r.touch_type||"video"}]).select("*, share_token").single();if(i)throw i;return n},onSuccess:()=>{e.invalidateQueries({queryKey:["agent-videos"]}),e.invalidateQueries({queryKey:["storage-usage"]})}})}function p7e(){const t=Wn();return zr({mutationFn:async({id:e,bunnyVideoId:r,hardDelete:n=!1})=>{if(console.log("Deleting video:",{id:e,bunnyVideoId:r,hardDelete:n}),r){console.log("Calling bunny-upload delete for videoId:",r);const{data:i,error:o}=await ae.functions.invoke("bunny-upload",{body:{action:"delete",videoId:r,isAgentVideo:!0}});o?console.error("Failed to delete from Bunny:",o):console.log("Bunny delete response:",i)}else console.warn("No bunnyVideoId provided, skipping Bunny.net deletion");if(n){console.log("Hard deleting from database:",e);const{error:i}=await ae.from("agent_videos").delete().eq("id",e);if(i)throw i}else{console.log("Soft deleting from database:",e);const{error:i}=await ae.from("agent_videos").update({is_deleted:!0}).eq("id",e);if(i)throw i}console.log("Video deletion complete")},onSuccess:()=>{t.invalidateQueries({queryKey:["agent-videos"]}),t.invalidateQueries({queryKey:["storage-usage"]})}})}function Lye(){const{user:t}=rn();return Sr({queryKey:["storage-usage",t==null?void 0:t.id],queryFn:async()=>{if(!(t!=null&&t.id))return null;const{data:e,error:r}=await ae.from("agent_storage_usage").select("*").eq("user_id",t.id).maybeSingle();if(r)throw r;return e||{user_id:t.id,total_storage_mb:0,storage_tier:"basic",max_storage_mb:1024}},enabled:!!(t!=null&&t.id)})}function m7e(){const{data:t,isLoading:e}=Lye(),r=t?t.total_storage_mb0?t.total_storage_mb/t.max_storage_mb*100:0,o=i>=80;return{canRecord:r,remainingMb:n,usagePercent:i,isNearLimit:o,storage:t,isLoading:e}}async function g7e(t){const{data:e,error:r}=await ae.functions.invoke("bunny-upload",{body:{action:"create",title:t,isAgentVideo:!0}});if(r)throw r;return e}async function y7e(t){const{data:e,error:r}=await ae.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:t,isAgentVideo:!0}});if(r)throw r;return e}async function x7e(t){const{data:e,error:r}=await ae.functions.invoke("bunny-upload",{body:{action:"status",videoId:t,isAgentVideo:!0}});if(r)throw r;return e}function v7e(){const{user:t}=rn(),e=Wn();return zr({mutationFn:async({contactId:r,videoId:n,notes:i})=>{if(!(t!=null&&t.id))throw new Error("Not authenticated");const{data:o}=await ae.from("action_types").select("id").eq("name","Video").single();if(!o)throw new Error("Video action type not found");const{data:c,error:a}=await ae.from("contact_touch_logs").insert([{owner_user_id:t.id,contact_id:r,action_type_id:o.id,notes:i||`Quick Video Touch - Video ID: ${n}`}]).select().single();if(a)throw a;return c},onSuccess:()=>{e.invalidateQueries({queryKey:["contact-touch-logs"]}),e.invalidateQueries({queryKey:["contacts"]})}})}const Fye=()=>{const{user:t}=rn();return Sr({queryKey:["popby-items",t==null?void 0:t.id],queryFn:async()=>{const{data:e,error:r}=await ae.from("popby_items").select("*").or(`owner_user_id.is.null,owner_user_id.eq.${t==null?void 0:t.id}`).eq("is_active",!0).order("name");if(r)throw r;return e},enabled:!!t})},lL=t=>{const{user:e}=rn();return Sr({queryKey:["popby-logs",e==null?void 0:e.id,t],queryFn:async()=>{let r=ae.from("popby_logs").select("*").order("completed_at",{ascending:!1});if(t){const o=new Date;o.setDate(o.getDate()-t),r=r.gte("completed_at",o.toISOString())}const{data:n,error:i}=await r;if(i)throw i;return n},enabled:!!e})},zye=()=>{const{user:t}=rn();return Sr({queryKey:["relationship-type-popby-defaults",t==null?void 0:t.id],queryFn:async()=>{const{data:e,error:r}=await ae.from("relationship_type_popby_defaults").select("*");if(r)throw r;return e},enabled:!!t})},_7e=()=>{const{user:t}=rn();return Sr({queryKey:["contact-popby-settings",t==null?void 0:t.id],queryFn:async()=>{const{data:e,error:r}=await ae.from("contact_popby_settings").select("*");if(r)throw r;return e},enabled:!!t})},Bye=()=>{const{data:t}=ig(),{data:e}=sg(),{data:r}=lL(),{data:n}=_7e(),{data:i}=zye(),o=new Map;r==null||r.forEach(_=>{const j=o.get(_.contact_id);(!j||new Date(_.completed_at)>new Date(j))&&o.set(_.contact_id,_.completed_at)});const c=new Map;i==null||i.forEach(_=>c.set(_.relationship_type_id,_.frequency_days));const a=new Map;n==null||n.filter(_=>_.is_active).forEach(_=>{a.set(_.contact_id,_.frequency_days)});const m=Cp(new Date);return(t||[]).map(_=>{let j=90;if(a.has(_.id))j=a.get(_.id);else if(_.tags&&_.tags.length>0){const I=_.tags.map(O=>c.get(O.relationship_type_id)).filter(O=>O!==void 0);I.length>0&&(j=Math.min(...I))}const N=o.get(_.id)||null,C=N?Qhe(m,Cp(new Date(N))):null,P=C===null||C>=j,A=P&&C!==null?C-j:0;return{..._,lastPopby:N,daysSinceLastPopby:C,frequencyDays:j,isDue:P,daysOverdue:A}}).sort((_,j)=>j.daysOverdue-_.daysOverdue)},$ye=()=>Bye().filter(e=>e.isDue),b7e=()=>{const t=Wn(),{user:e}=rn();return zr({mutationFn:async r=>{const{error:n}=await ae.from("popby_items").insert({...r,owner_user_id:e==null?void 0:e.id});if(n)throw n},onSuccess:()=>{t.invalidateQueries({queryKey:["popby-items"]}),na({title:"Popby item created!"})},onError:r=>{na({title:"Error creating popby item",description:r.message,variant:"destructive"})}})},Uye=()=>{const t=Wn(),{user:e}=rn();return zr({mutationFn:async r=>{const{error:n}=await ae.from("popby_logs").insert({...r,owner_user_id:e==null?void 0:e.id});if(n)throw n},onSuccess:()=>{t.invalidateQueries({queryKey:["popby-logs"]}),na({title:"Popby logged!"})},onError:r=>{na({title:"Error logging popby",description:r.message,variant:"destructive"})}})},w7e=()=>{const t=Wn(),{user:e}=rn();return zr({mutationFn:async r=>{const{error:n}=await ae.from("relationship_type_popby_defaults").upsert({...r,owner_user_id:e==null?void 0:e.id},{onConflict:"relationship_type_id,owner_user_id"});if(n)throw n},onSuccess:()=>{t.invalidateQueries({queryKey:["relationship-type-popby-defaults"]}),na({title:"Frequency updated!"})},onError:r=>{na({title:"Error updating frequency",description:r.message,variant:"destructive"})}})},j7e=()=>{const{data:t}=lL(30),e=$ye(),r=new Date;r.setDate(r.getDate()-7);const n=(t==null?void 0:t.filter(o=>new Date(o.completed_at)>=r).length)||0,i=(t==null?void 0:t.length)||0;return{thisWeekCount:n,thisMonthCount:i,dueCount:e.length}};function S7e({videoId:t}){const{data:e,isLoading:r,error:n}=h7e(t);return r?s.jsxs("div",{className:"space-y-4",children:[s.jsx(Dn,{className:"w-full aspect-video rounded-lg"}),s.jsx(Dn,{className:"h-4 w-1/3"})]}):n||!e||e.is_deleted?s.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[s.jsx(yT,{className:"h-12 w-12 text-muted-foreground mb-4"}),s.jsx("h3",{className:"font-medium",children:"Video Unavailable"}),s.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"This video has been deleted or is no longer available."})]}):s.jsxs("div",{className:"space-y-4",children:[e.playback_url?s.jsx("video",{src:e.playback_url,controls:!0,autoPlay:!0,className:"w-full rounded-lg bg-black",style:{maxHeight:"60vh"}}):s.jsx("div",{className:"w-full aspect-video bg-muted rounded-lg flex items-center justify-center",children:s.jsx("p",{className:"text-muted-foreground",children:"Video is still processing..."})}),e.title&&s.jsxs("div",{children:[s.jsx("h4",{className:"font-medium",children:e.title}),e.notes&&s.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:e.notes})]})]})}function N7e(){var pe;const{contactId:t}=mu(),e=Bs(),{data:r,isLoading:n}=cBe(t||""),{data:i}=sg(),{data:o}=Cq(),{data:c}=zD(365),{data:a}=lL(365),m=spe(),g=ipe(),_=ope(),[j,N]=D.useState(!1),[C,P]=D.useState({}),[A,I]=D.useState(!1),[O,R]=D.useState(null),[z,W]=D.useState(""),[V,K]=D.useState(null),Q=ve=>{if(!ve)return null;const ge=ve.match(/Video ID:\s*([a-f0-9-]+)/i);return ge?ge[1]:null},te=D.useMemo(()=>{const ve=((c==null?void 0:c.filter(ke=>ke.contact_id===t))||[]).map(ke=>{var Se,je;const Ce=Q(ke.notes);return{id:ke.id,type:"touch",completed_at:ke.completed_at,name:((Se=ke.action_type)==null?void 0:Se.name)||"Touch",color:((je=ke.action_type)==null?void 0:je.color)||"#3B82F6",notes:ke.notes,videoId:Ce}}),ge=((a==null?void 0:a.filter(ke=>ke.contact_id===t))||[]).map(ke=>({id:ke.id,type:"popby",completed_at:ke.completed_at,name:"Pop-by",color:"#F97316",notes:ke.notes,videoId:null}));return[...ve,...ge].sort((ke,Ce)=>new Date(Ce.completed_at).getTime()-new Date(ke.completed_at).getTime())},[c,a,t]),X=()=>{var ve;r&&(P({first_name:r.first_name||"",last_name:r.last_name||"",email:r.email||"",phone:r.phone||"",address:r.address||"",birthday:r.birthday||"",home_anniversary:r.home_anniversary||"",spouse_name:r.spouse_name||"",company_name:r.company_name||"",job_title:r.job_title||"",notes:r.notes||"",tagIds:((ve=r.tags)==null?void 0:ve.map(ge=>ge.relationship_type_id))||[]}),N(!0))},ie=async()=>{await m.mutateAsync({id:t,...C}),N(!1)},he=async()=>{confirm("Are you sure you want to delete this contact?")&&(await g.mutateAsync(t),e("/innercircle/contacts"))},xe=async()=>{O&&(await _.mutateAsync({contactId:t,actionTypeId:O,notes:z}),I(!1),R(null),W(""))};return n?s.jsx(Jr,{title:"Contact Details",children:s.jsx("div",{className:"flex items-center justify-center py-12",children:s.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full"})})}):r?s.jsx(Jr,{title:`${r.first_name} ${r.last_name||""}`,description:"Contact details and activity",children:s.jsxs("div",{className:"space-y-6 overflow-x-hidden",children:[s.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3",children:[s.jsxs(de,{variant:"ghost",size:"sm",onClick:()=>e("/innercircle/contacts"),children:[s.jsx(I1,{className:"h-4 w-4 mr-1"}),"Back to Contacts"]}),s.jsxs("div",{className:"flex items-center gap-2 w-full sm:w-auto justify-end flex-wrap",children:[s.jsxs(de,{variant:"default",onClick:()=>e(`/innercircle/video/record?contact_id=${t}`),className:"bg-gradient-to-r from-primary to-primary/80",children:[s.jsx(Ia,{className:"h-4 w-4 mr-1"}),"Quick Video Touch"]}),s.jsxs(mn,{open:A,onOpenChange:I,children:[s.jsx(Do,{asChild:!0,children:s.jsxs(de,{variant:"outline",children:[s.jsx(Qn,{className:"h-4 w-4 mr-1"}),"Log Action"]})}),s.jsxs(pn,{children:[s.jsx(xn,{children:s.jsx(gn,{children:"Log an Action"})}),s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsx(mt,{children:"Action Type"}),s.jsx("div",{className:"grid grid-cols-2 gap-2 mt-2",children:o==null?void 0:o.filter(ve=>ve.active).map(ve=>s.jsxs("button",{onClick:()=>R(ve.id),className:` p-3 rounded-lg border text-left transition-all ${O===ve.id?"border-primary bg-primary/10":"hover:bg-accent"} `,children:[s.jsx("div",{className:"font-medium",children:ve.name}),s.jsx("div",{className:"text-xs text-muted-foreground",children:ve.description})]},ve.id))})]}),s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"action-notes",children:"Notes (optional)"}),s.jsx(mi,{id:"action-notes",value:z,onChange:ve=>W(ve.target.value),placeholder:"Add any notes about this interaction...",rows:3})]}),s.jsxs(de,{onClick:xe,disabled:!O||_.isPending,className:"w-full",children:[s.jsx(ru,{className:"h-4 w-4 mr-1"}),"Complete Action"]})]})]})]}),s.jsxs(de,{variant:"outline",onClick:X,children:[s.jsx(P_,{className:"h-4 w-4 mr-1"}),"Edit"]}),s.jsx(de,{variant:"destructive",size:"icon",onClick:he,children:s.jsx(oi,{className:"h-4 w-4"})})]})]}),s.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[s.jsxs(at,{className:"md:col-span-2",children:[s.jsx(xr,{children:s.jsx(wr,{children:"Contact Information"})}),s.jsx(ct,{children:j?s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"first_name",children:"First Name"}),s.jsx(Et,{id:"first_name",value:C.first_name,onChange:ve=>P({...C,first_name:ve.target.value})})]}),s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"last_name",children:"Last Name"}),s.jsx(Et,{id:"last_name",value:C.last_name,onChange:ve=>P({...C,last_name:ve.target.value})})]})]}),s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"email",children:"Email"}),s.jsx(Et,{id:"email",type:"email",value:C.email,onChange:ve=>P({...C,email:ve.target.value})})]}),s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"phone",children:"Phone"}),s.jsx(Et,{id:"phone",value:C.phone,onChange:ve=>P({...C,phone:ve.target.value})})]}),s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"address",children:"Address"}),s.jsx(Et,{id:"address",value:C.address,onChange:ve=>P({...C,address:ve.target.value})})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"birthday",children:"Birthday"}),s.jsx(Et,{id:"birthday",type:"date",value:C.birthday,onChange:ve=>P({...C,birthday:ve.target.value})})]}),s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"home_anniversary",children:"Home Anniversary"}),s.jsx(Et,{id:"home_anniversary",type:"date",value:C.home_anniversary,onChange:ve=>P({...C,home_anniversary:ve.target.value})})]})]}),s.jsx(xf,{}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4",children:[s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"spouse_name",children:"Spouse/Partner Name"}),s.jsx(Et,{id:"spouse_name",value:C.spouse_name,onChange:ve=>P({...C,spouse_name:ve.target.value}),placeholder:"Enter spouse name"})]}),s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"company_name",children:"Company"}),s.jsx(Et,{id:"company_name",value:C.company_name,onChange:ve=>P({...C,company_name:ve.target.value}),placeholder:"Enter company name"})]}),s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"job_title",children:"Job Title"}),s.jsx(Et,{id:"job_title",value:C.job_title,onChange:ve=>P({...C,job_title:ve.target.value}),placeholder:"Enter job title"})]})]}),s.jsxs("div",{children:[s.jsx(mt,{children:"Relationship Types"}),s.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:i==null?void 0:i.filter(ve=>ve.active).map(ve=>{var ge;return s.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[s.jsx(dx,{checked:(ge=C.tagIds)==null?void 0:ge.includes(ve.id),onCheckedChange:ke=>{var Ce;P(ke?{...C,tagIds:[...C.tagIds||[],ve.id]}:{...C,tagIds:(Ce=C.tagIds)==null?void 0:Ce.filter(Se=>Se!==ve.id)})}}),s.jsx("span",{className:"text-sm",children:ve.name})]},ve.id)})})]}),s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"notes",children:"Notes"}),s.jsx(mi,{id:"notes",value:C.notes,onChange:ve=>P({...C,notes:ve.target.value}),rows:4})]}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(de,{onClick:ie,disabled:m.isPending,children:"Save Changes"}),s.jsx(de,{variant:"outline",onClick:()=>N(!1),children:"Cancel"})]})]}):s.jsxs("div",{className:"space-y-4",children:[te.length>0&&s.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 flex items-center gap-2",children:[s.jsx(ko,{className:"h-4 w-4 text-primary"}),s.jsxs("span",{className:"text-sm",children:[s.jsx("span",{className:"font-medium",children:"Last Contacted:"})," ",Vn(new Date(te[0].completed_at),"MMM d, yyyy")," ","(",te[0].name,")"]})]}),s.jsxs("div",{className:"flex flex-col sm:flex-row sm:gap-6 gap-2",children:[r.email&&s.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s.jsx(Fo,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),s.jsx("a",{href:`mailto:${r.email}`,className:"text-primary hover:underline truncate",children:r.email})]}),r.phone&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Yl,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),s.jsx("a",{href:`tel:${r.phone}`,className:"text-primary hover:underline",children:r.phone})]})]}),r.address&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(wp,{className:"h-4 w-4 text-muted-foreground"}),s.jsx("span",{children:r.address})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[r.birthday&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(ko,{className:"h-4 w-4 text-muted-foreground"}),s.jsxs("span",{children:["Birthday: ",Vn(new Date(r.birthday),"MMMM d")]})]}),r.home_anniversary&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(ou,{className:"h-4 w-4 text-muted-foreground"}),s.jsxs("span",{children:["Home Anniversary: ",Vn(new Date(r.home_anniversary),"MMMM d")]})]})]}),(r.spouse_name||r.company_name||r.job_title)&&s.jsxs(s.Fragment,{children:[s.jsx(xf,{}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[r.spouse_name&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(bf,{className:"h-4 w-4 text-muted-foreground"}),s.jsxs("span",{children:["Spouse: ",r.spouse_name]})]}),(r.company_name||r.job_title)&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(yc,{className:"h-4 w-4 text-muted-foreground"}),s.jsx("span",{children:r.job_title&&r.company_name?`${r.job_title} at ${r.company_name}`:r.job_title||r.company_name})]})]})]}),s.jsx(xf,{}),s.jsxs("div",{children:[s.jsx("h4",{className:"font-medium mb-2",children:"Relationship Types"}),s.jsx("div",{className:"flex flex-wrap gap-2",children:(pe=r.tags)!=null&&pe.length?r.tags.map(ve=>{var ge;return s.jsx(ir,{variant:"secondary",children:(ge=ve.relationship_type)==null?void 0:ge.name},ve.id)}):s.jsx("span",{className:"text-sm text-muted-foreground",children:"No relationship types assigned"})})]}),r.notes&&s.jsxs(s.Fragment,{children:[s.jsx(xf,{}),s.jsxs("div",{children:[s.jsx("h4",{className:"font-medium mb-2",children:"Notes"}),s.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:r.notes})]})]})]})})]}),s.jsxs(at,{children:[s.jsx(xr,{children:s.jsx(wr,{children:"Activity Log"})}),s.jsx(ct,{children:te.length>0?s.jsx("div",{className:"space-y-4",children:te.map(ve=>{var ge;return s.jsxs("div",{className:"flex items-start gap-3 pb-3 border-b last:border-0",children:[s.jsx("div",{className:"h-8 w-8 rounded-full flex items-center justify-center text-white text-xs",style:{backgroundColor:ve.color},children:ve.type==="popby"?s.jsx(yd,{className:"h-4 w-4"}):(ge=ve.name)==null?void 0:ge.charAt(0)}),s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"font-medium text-sm",children:ve.name}),ve.videoId&&s.jsxs(de,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>K(ve.videoId),children:[s.jsx(Sf,{className:"h-3 w-3 mr-1"}),"Preview"]})]}),s.jsx("div",{className:"text-xs text-muted-foreground",children:Vn(new Date(ve.completed_at),"MMM d, yyyy h:mm a")}),ve.notes&&!ve.videoId&&s.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:ve.notes})]})]},ve.id)})}):s.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No activity logged yet"})})]}),s.jsx(mn,{open:!!V,onOpenChange:ve=>!ve&&K(null),children:s.jsxs(pn,{className:"max-w-2xl",children:[s.jsx(xn,{children:s.jsx(gn,{children:"Video Preview"})}),V&&s.jsx(S7e,{videoId:V})]})})]})]})}):s.jsx(Jr,{title:"Contact Not Found",children:s.jsxs("div",{className:"text-center py-12",children:[s.jsx("p",{className:"text-muted-foreground mb-4",children:"This contact was not found."}),s.jsx(de,{onClick:()=>e("/innercircle/contacts"),children:"Back to Contacts"})]})})}const tee={Crown:G6,FileText:Ii,Users:_i,Globe:hoe,Star:mh,Phone:Yl,MessageSquare:Tf,PenTool:_oe,Video:Ia,Gift:yd},Qz=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function C7e(){var Ar,rt;const t=Bs(),{user:e}=rn(),{data:r}=sg(),{data:n}=dBe(),{data:i}=yBe(),{data:o}=rpe(),{data:c}=Cq(),{data:a}=uBe(),m=xBe(),g=hBe();fBe();const _=pBe(),j=mBe(),N=gBe(),[C,P]=D.useState(null),[A,I]=D.useState(!1),[O,R]=D.useState(null),[z,W]=D.useState(""),[V,K]=D.useState(""),[Q,te]=D.useState([]),[X,ie]=D.useState(null),[he,xe]=D.useState(null),[pe,ve]=D.useState(!1),[ge,ke]=D.useState(""),[Ce,Se]=D.useState(""),[je,et]=D.useState(""),[bt,_e]=D.useState(""),Ye=(We,_t)=>i==null?void 0:i.some(Gt=>Gt.plan_id===We&&Gt.relationship_type_id===_t&&Gt.active),pt=We=>i==null?void 0:i.find(_t=>_t.relationship_type_id===We&&_t.active),nt=async(We,_t)=>{const Gt=Ye(We,_t);await m.mutateAsync({planId:We,relationshipTypeId:_t,active:!Gt})},Qt=(n==null?void 0:n.filter(We=>We.active&&!We.owner_user_id))||[],gt=(n==null?void 0:n.filter(We=>We.owner_user_id===(e==null?void 0:e.id)))||[],Me=r==null?void 0:r.find(We=>We.id===C),Oe=C?pt(C):null,Ie=n==null?void 0:n.find(We=>We.id===(Oe==null?void 0:Oe.plan_id)),Be=async()=>{if(!z.trim())return;const We=await g.mutateAsync({name:z,description:V});We&&Q.length>0&&await j.mutateAsync({planId:We.id,items:Q}),I(!1),W(""),K(""),te([])},Pe=(We,_t)=>{xe(_t)},ut=(We,_t,Gt)=>{te(rr=>[...rr.filter(kr=>kr.month_number!==We),{month_number:We,action_type_id:_t,default_script_id:Gt}]),ie(null),xe(null)},jt=We=>{te(_t=>_t.filter(Gt=>Gt.month_number!==We))},$t=async()=>{if(!ge.trim()||!Ce.trim()||!he)return;const We=await N.mutateAsync({actionTypeId:he,title:ge,scriptBody:Ce,emailSubject:je||void 0,tone:bt||void 0});We&&X!==null&&ut(X,he,We.id),ve(!1),ke(""),Se(""),et(""),_e("")},Ht=he?a==null?void 0:a.filter(We=>We.action_type_id===he&&We.active):[],Lt=We=>tee[We||"Phone"]||Yl,Kt=We=>tee[We||"Users"]||_i;return s.jsxs(Jr,{title:"Touchpoint Plans",description:"Assign plans to your contact groups",children:[s.jsxs("div",{className:"space-y-6 overflow-x-hidden",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("h1",{className:"text-2xl font-bold",children:"Touchpoint Plans"}),s.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-amber-500 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),s.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3",children:[s.jsxs(de,{variant:"ghost",size:"sm",onClick:()=>t("/innercircle"),children:[s.jsx(I1,{className:"h-4 w-4 mr-1"}),"Back"]}),s.jsxs(de,{onClick:()=>I(!0),className:"w-full sm:w-auto",children:[s.jsx(Qn,{className:"h-4 w-4 mr-2"}),"Create Custom Plan"]})]}),s.jsxs("div",{className:"grid lg:grid-cols-3 gap-6",children:[s.jsxs("div",{className:"space-y-3",children:[s.jsx("h3",{className:"font-semibold text-lg",children:"Your Contact Groups"}),s.jsx("p",{className:"text-sm text-muted-foreground",children:"Select a group to assign a touchpoint plan"}),r==null?void 0:r.filter(We=>We.active).map(We=>{const _t=Kt(We.icon),Gt=(o==null?void 0:o[We.id])||0,rr=pt(We.id),pr=n==null?void 0:n.find(Hr=>Hr.id===(rr==null?void 0:rr.plan_id)),kr=C===We.id;return s.jsxs("button",{onClick:()=>P(We.id),className:` w-full flex items-center gap-3 p-4 rounded-lg border text-left transition-all ${kr?"border-primary bg-primary/5 ring-2 ring-primary":"hover:bg-accent"} `,children:[s.jsx(_t,{className:"h-5 w-5 text-muted-foreground"}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("div",{className:"font-medium",children:We.name}),s.jsxs("div",{className:"text-sm text-muted-foreground",children:[Gt," contacts"]})]}),pr?s.jsxs(ir,{variant:"secondary",className:"text-xs",children:[s.jsx(gc,{className:"h-3 w-3 mr-1"}),pr.name.split(" ")[0]]}):s.jsx(ir,{variant:"outline",className:"text-xs text-muted-foreground",children:"No plan"})]},We.id)})]}),s.jsx("div",{className:"lg:col-span-2",children:C&&Me?s.jsxs(at,{children:[s.jsxs(xr,{children:[s.jsxs(wr,{className:"flex items-center gap-2",children:[(()=>{const We=Kt(Me.icon);return s.jsx(We,{className:"h-5 w-5"})})(),Me.name," Touchpoint Plan"]}),s.jsxs(us,{children:["Choose a plan for your ",Me.name," contacts"]})]}),s.jsxs(ct,{className:"space-y-6",children:[Ie&&s.jsxs("div",{className:"p-4 bg-primary/5 rounded-lg border border-primary/20",children:[s.jsxs("div",{className:"flex items-center justify-between mb-3",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"font-medium flex items-center gap-2",children:[s.jsx(gc,{className:"h-4 w-4 text-green-500"}),"Currently using: ",Ie.name]}),Ie.description&&s.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Ie.description})]}),s.jsx(de,{variant:"outline",size:"sm",onClick:()=>nt(Ie.id,C),children:"Disable"})]}),Ie.items&&Ie.items.length>0&&s.jsxs("div",{className:"mt-4",children:[s.jsxs("div",{className:"text-sm font-medium mb-2 flex items-center gap-2",children:[s.jsx(ko,{className:"h-4 w-4"}),"12-Month Schedule"]}),s.jsx("div",{className:"grid grid-cols-4 sm:grid-cols-6 gap-2",children:Qz.map((We,_t)=>{var kr,Hr;const Gt=((kr=Ie.items)==null?void 0:kr.filter(Fn=>Fn.month_number===_t+1))||[],rr=(Hr=Gt[0])==null?void 0:Hr.action_type,pr=rr?Lt(rr.icon):null;return s.jsxs("div",{className:` p-2 rounded border text-center ${Gt.length>0?"bg-primary/10 border-primary":"bg-muted"} `,children:[s.jsx("div",{className:"text-xs text-muted-foreground",children:We}),pr&&s.jsx(pr,{className:"h-4 w-4 mx-auto mt-1",style:{color:(rr==null?void 0:rr.color)||"#3B82F6"}})]},_t)})})]})]}),s.jsxs("div",{children:[s.jsx("h4",{className:"font-medium mb-3",children:Ie?"Switch to a Different Plan":"Choose a Plan"}),Qt.length>0&&s.jsxs("div",{className:"space-y-2 mb-4",children:[s.jsx("div",{className:"text-sm text-muted-foreground",children:"Pre-built Templates"}),Qt.map(We=>{var Gt;const _t=(Ie==null?void 0:Ie.id)===We.id;return s.jsxs("div",{className:` flex items-center justify-between p-3 rounded-lg border ${_t?"opacity-50":"hover:bg-accent"} `,children:[s.jsxs("div",{children:[s.jsx("div",{className:"font-medium",children:We.name}),s.jsxs("div",{className:"text-sm text-muted-foreground",children:[((Gt=We.items)==null?void 0:Gt.length)||0," touchpoints/year"]})]}),s.jsx(de,{size:"sm",variant:_t?"outline":"default",disabled:_t||m.isPending,onClick:()=>nt(We.id,C),children:_t?"Active":"Use This"})]},We.id)})]}),gt.length>0&&s.jsxs("div",{className:"space-y-2",children:[s.jsx("div",{className:"text-sm text-muted-foreground",children:"My Custom Plans"}),gt.map(We=>{var Gt;const _t=(Ie==null?void 0:Ie.id)===We.id;return s.jsxs("div",{className:` flex items-center justify-between p-3 rounded-lg border ${_t?"opacity-50":"hover:bg-accent"} `,children:[s.jsxs("div",{children:[s.jsx("div",{className:"font-medium",children:We.name}),s.jsxs("div",{className:"text-sm text-muted-foreground",children:[((Gt=We.items)==null?void 0:Gt.length)||0," touchpoints/year"]})]}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(de,{size:"sm",variant:"ghost",onClick:()=>_.mutate(We.id),children:s.jsx(oi,{className:"h-4 w-4"})}),s.jsx(de,{size:"sm",variant:_t?"outline":"default",disabled:_t||m.isPending,onClick:()=>nt(We.id,C),children:_t?"Active":"Use This"})]})]},We.id)})]}),Qt.length===0&>.length===0&&s.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No plans available. Create a custom plan to get started."})]})]})]}):s.jsx(at,{children:s.jsxs(ct,{className:"py-12 text-center text-muted-foreground",children:[s.jsx(ko,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),s.jsx("p",{children:"Select a contact group to view and assign plans"})]})})})]}),s.jsx(at,{className:"bg-muted/50",children:s.jsx(ct,{className:"py-4",children:s.jsxs("p",{className:"text-sm text-muted-foreground",children:[s.jsx("strong",{children:"How it works:"})," When you assign a plan to a contact group, those contacts will appear in your daily suggested actions based on the plan's schedule."]})})})]}),s.jsx(mn,{open:A,onOpenChange:I,children:s.jsxs(pn,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[s.jsx(xn,{children:s.jsx(gn,{children:"Create Custom Touchpoint Plan"})}),s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"grid gap-4",children:[s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"plan-name",children:"Plan Name"}),s.jsx(Et,{id:"plan-name",value:z,onChange:We=>W(We.target.value),placeholder:"e.g., My VIP Plan"})]}),s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"plan-description",children:"Description (optional)"}),s.jsx(mi,{id:"plan-description",value:V,onChange:We=>K(We.target.value),placeholder:"Describe your plan...",rows:2})]})]}),s.jsxs("div",{children:[s.jsx(mt,{children:"12-Month Schedule"}),s.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"Click on a month to add a touchpoint"}),s.jsx("div",{className:"grid grid-cols-6 gap-2",children:Qz.map((We,_t)=>{const Gt=_t+1,rr=Q.find(Hr=>Hr.month_number===Gt),pr=rr?c==null?void 0:c.find(Hr=>Hr.id===rr.action_type_id):null,kr=pr?Lt(pr.icon):null;return s.jsxs("div",{className:"relative",children:[s.jsxs("button",{type:"button",onClick:()=>ie(X===Gt?null:Gt),className:` w-full p-3 rounded-lg border text-center transition-all ${rr?"bg-primary/10 border-primary":"bg-muted hover:bg-accent"} ${X===Gt?"ring-2 ring-primary":""} `,children:[s.jsx("div",{className:"text-xs text-muted-foreground font-medium",children:We}),kr?s.jsx(kr,{className:"h-5 w-5 mx-auto mt-1",style:{color:(pr==null?void 0:pr.color)||"#3B82F6"}}):s.jsx(Qn,{className:"h-5 w-5 mx-auto mt-1 text-muted-foreground/50"})]}),rr&&s.jsx("button",{type:"button",onClick:Hr=>{Hr.stopPropagation(),jt(Gt)},className:"absolute -top-1 -right-1 p-1 bg-destructive text-destructive-foreground rounded-full",children:s.jsx(Ni,{className:"h-3 w-3"})})]},_t)})}),X!==null&&!he&&s.jsxs("div",{className:"mt-4 p-3 bg-muted rounded-lg",children:[s.jsxs("div",{className:"text-sm font-medium mb-2",children:["Step 1: Select action for ",Qz[X-1],":"]}),s.jsx("div",{className:"flex flex-wrap gap-2",children:c==null?void 0:c.filter(We=>We.active).map(We=>{const _t=Lt(We.icon);return s.jsxs("button",{type:"button",onClick:()=>Pe(X,We.id),className:"flex items-center gap-2 px-3 py-2 rounded-lg border bg-background hover:bg-accent transition-colors",children:[s.jsx(_t,{className:"h-4 w-4",style:{color:We.color||"#3B82F6"}}),s.jsx("span",{className:"text-sm",children:We.name})]},We.id)})})]}),X!==null&&he&&s.jsxs("div",{className:"mt-4 p-3 bg-muted rounded-lg space-y-3",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("div",{className:"text-sm font-medium",children:"Step 2: Select a script (optional)"}),s.jsxs(de,{variant:"ghost",size:"sm",onClick:()=>xe(null),children:[s.jsx(I1,{className:"h-4 w-4 mr-1"})," Back"]})]}),s.jsxs("div",{className:"space-y-2 max-h-[300px] overflow-y-auto pr-1",children:[s.jsx("button",{type:"button",onClick:()=>ut(X,he),className:"w-full flex items-center gap-3 p-3 rounded-lg border bg-background hover:bg-accent transition-colors text-left",children:s.jsxs("div",{className:"flex-1",children:[s.jsx("div",{className:"font-medium text-sm",children:"No Script"}),s.jsx("div",{className:"text-xs text-muted-foreground",children:"Use without a predefined script"})]})}),Ht==null?void 0:Ht.map(We=>s.jsx("button",{type:"button",onClick:()=>ut(X,he,We.id),className:"w-full flex items-center gap-3 p-3 rounded-lg border bg-background hover:bg-accent transition-colors text-left",children:s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("div",{className:"font-medium text-sm",children:We.title}),We.tone&&s.jsx(ir,{variant:"secondary",className:"text-xs mt-1",children:We.tone}),s.jsxs("div",{className:"text-xs text-muted-foreground mt-1 line-clamp-2",children:[We.script_body.substring(0,100),"..."]})]})},We.id)),s.jsxs("button",{type:"button",onClick:()=>ve(!0),className:"w-full flex items-center gap-3 p-3 rounded-lg border border-dashed bg-background hover:bg-accent transition-colors text-left",children:[s.jsx(Qn,{className:"h-5 w-5 text-muted-foreground"}),s.jsxs("div",{className:"flex-1",children:[s.jsx("div",{className:"font-medium text-sm",children:"Create Custom Script"}),s.jsx("div",{className:"text-xs text-muted-foreground",children:"Write your own script for this action"})]})]})]})]})]}),Q.length>0&&s.jsxs("div",{className:"text-sm text-muted-foreground",children:[Q.length," touchpoint",Q.length!==1?"s":""," per year"]})]}),s.jsxs(zi,{children:[s.jsx(de,{variant:"outline",onClick:()=>I(!1),children:"Cancel"}),s.jsxs(de,{onClick:Be,disabled:!z.trim()||g.isPending,children:[s.jsx(K2,{className:"h-4 w-4 mr-2"}),"Create Plan"]})]})]})}),s.jsx(mn,{open:pe,onOpenChange:ve,children:s.jsxs(pn,{className:"max-w-lg",children:[s.jsx(xn,{children:s.jsx(gn,{children:"Create Custom Script"})}),s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"script-title",children:"Script Title"}),s.jsx(Et,{id:"script-title",value:ge,onChange:We=>ke(We.target.value),placeholder:"e.g., Friendly Check-in Call"})]}),s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"script-tone",children:"Tone (optional)"}),s.jsxs(Kn,{value:bt,onValueChange:_e,children:[s.jsx(qn,{children:s.jsx(Zn,{placeholder:"Select tone..."})}),s.jsxs(Hn,{children:[s.jsx(_r,{value:"friendly",children:"Friendly"}),s.jsx(_r,{value:"professional",children:"Professional"}),s.jsx(_r,{value:"casual",children:"Casual"}),s.jsx(_r,{value:"formal",children:"Formal"})]})]})]}),((rt=(Ar=c==null?void 0:c.find(We=>We.id===he))==null?void 0:Ar.name)==null?void 0:rt.toLowerCase().includes("email"))&&s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"script-email-subject",children:"Email Subject"}),s.jsx(Et,{id:"script-email-subject",value:je,onChange:We=>et(We.target.value),placeholder:"e.g., Quick Hello!"})]}),s.jsxs("div",{children:[s.jsx(mt,{htmlFor:"script-body",children:"Script Content"}),s.jsx(mi,{id:"script-body",value:Ce,onChange:We=>Se(We.target.value),placeholder:"Write your script here... You can use {{FirstName}} and {{LastName}} as placeholders.",rows:6}),s.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Tip: Use ","{{FirstName}}"," and ","{{LastName}}"," as placeholders"]})]})]}),s.jsxs(zi,{children:[s.jsx(de,{variant:"outline",onClick:()=>ve(!1),children:"Cancel"}),s.jsxs(de,{onClick:$t,disabled:!ge.trim()||!Ce.trim()||N.isPending,children:[s.jsx(K2,{className:"h-4 w-4 mr-2"}),"Create & Use Script"]})]})]})})]})}const k7e=[{value:"30",label:"Monthly (30 days)"},{value:"60",label:"Bi-Monthly (60 days)"},{value:"90",label:"Quarterly (90 days)"},{value:"180",label:"Twice a Year (180 days)"},{value:"365",label:"Yearly (365 days)"}];function T7e(){const t=Bs(),e=$ye(),{data:r}=Fye(),{data:n}=sg(),{data:i}=zye(),{data:o}=lL(90),{data:c}=ig(),a=j7e(),m=Uye(),g=b7e(),_=w7e(),j=pe=>{const ve=c==null?void 0:c.find(ge=>ge.id===pe);return ve?`${ve.first_name} ${ve.last_name||""}`.trim():"Unknown"},N=pe=>{if(!pe)return null;const ve=r==null?void 0:r.find(ge=>ge.id===pe);return(ve==null?void 0:ve.name)||null},[C,P]=D.useState(null),[A,I]=D.useState(!1),[O,R]=D.useState(!1),[z,W]=D.useState(!1),[V,K]=D.useState({popby_item_id:"",notes:""}),[Q,te]=D.useState({name:"",description:""}),X=async()=>{C&&(await m.mutateAsync({contact_id:C.id,popby_item_id:V.popby_item_id||void 0,notes:V.notes||void 0}),I(!1),P(null),K({popby_item_id:"",notes:""}))},ie=async()=>{Q.name.trim()&&(await g.mutateAsync({name:Q.name.trim(),description:Q.description.trim()||void 0}),W(!1),te({name:"",description:""}))},he=async(pe,ve)=>{await _.mutateAsync({relationship_type_id:pe,frequency_days:parseInt(ve)})},xe=pe=>{var ge;const ve=i==null?void 0:i.find(ke=>ke.relationship_type_id===pe);return((ge=ve==null?void 0:ve.frequency_days)==null?void 0:ge.toString())||"90"};return s.jsx(Jr,{title:"Popbys",description:"Drop off gifts to stay top of mind",children:s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("h1",{className:"text-2xl font-bold",children:"Popbys"}),s.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-amber-500 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),s.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[s.jsx(at,{children:s.jsxs(ct,{className:"p-4 text-center",children:[s.jsx("div",{className:"text-3xl font-bold text-primary",children:a.thisWeekCount}),s.jsx("div",{className:"text-sm text-muted-foreground",children:"This Week"})]})}),s.jsx(at,{children:s.jsxs(ct,{className:"p-4 text-center",children:[s.jsx("div",{className:"text-3xl font-bold text-emerald-500",children:a.thisMonthCount}),s.jsx("div",{className:"text-sm text-muted-foreground",children:"This Month"})]})}),s.jsx(at,{children:s.jsxs(ct,{className:"p-4 text-center",children:[s.jsx("div",{className:"text-3xl font-bold text-amber-500",children:a.dueCount}),s.jsx("div",{className:"text-sm text-muted-foreground",children:"Due Now"})]})})]}),s.jsxs("div",{className:"flex gap-2 flex-wrap",children:[s.jsxs(de,{onClick:()=>t("/innercircle/popbys/map"),children:[s.jsx(wp,{className:"h-4 w-4 mr-2"}),"View Map"]}),s.jsxs(de,{variant:"outline",onClick:()=>R(!0),children:[s.jsx(eg,{className:"h-4 w-4 mr-2"}),"Frequency Settings"]}),s.jsxs(de,{variant:"outline",onClick:()=>W(!0),children:[s.jsx(Qn,{className:"h-4 w-4 mr-2"}),"Add Popby Idea"]})]}),s.jsxs(go,{defaultValue:"due",children:[s.jsxs(ao,{children:[s.jsx(Bn,{value:"due",children:"Due for Popby"}),s.jsx(Bn,{value:"activity",children:"Recent Activity"}),s.jsx(Bn,{value:"library",children:"Popby Library"})]}),s.jsx(xs,{value:"due",className:"space-y-4 mt-4",children:!e||e.length===0?s.jsx(at,{children:s.jsxs(ct,{className:"p-8 text-center text-muted-foreground",children:[s.jsx(yd,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),s.jsx("p",{children:"No contacts due for a popby right now!"}),s.jsx("p",{className:"text-sm mt-1",children:"Great job staying connected."})]})}):s.jsx("div",{className:"space-y-3",children:e.map(pe=>s.jsx(at,{className:"hover:shadow-md transition-shadow",children:s.jsx(ct,{className:"p-4",children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("span",{className:"font-medium",children:[pe.first_name," ",pe.last_name]}),pe.daysOverdue>0&&s.jsxs(ir,{variant:"destructive",className:"text-xs",children:[pe.daysOverdue,"+ days overdue"]}),pe.daysSinceLastPopby===null&&s.jsx(ir,{variant:"outline",className:"text-xs",children:"Never visited"})]}),s.jsxs("div",{className:"flex items-center gap-4 mt-1 text-sm text-muted-foreground",children:[pe.address&&s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(wp,{className:"h-3 w-3"}),pe.city||pe.address]}),pe.tags&&pe.tags.length>0&&s.jsx("span",{children:pe.tags.map(ve=>{var ge;return(ge=ve.relationship_type)==null?void 0:ge.name}).join(", ")})]}),pe.lastPopby&&s.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Last popby: ",Vn(new Date(pe.lastPopby),"MMM d, yyyy")]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[pe.phone&&s.jsx(de,{size:"sm",variant:"ghost",asChild:!0,children:s.jsx("a",{href:`tel:${pe.phone}`,children:s.jsx(Yl,{className:"h-4 w-4"})})}),s.jsxs(de,{size:"sm",onClick:()=>{P(pe),I(!0)},children:[s.jsx(gc,{className:"h-4 w-4 mr-1"}),"Log Popby"]})]})]})})},pe.id))})}),s.jsx(xs,{value:"activity",className:"space-y-4 mt-4",children:!o||o.length===0?s.jsx(at,{children:s.jsxs(ct,{className:"p-8 text-center text-muted-foreground",children:[s.jsx(No,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),s.jsx("p",{children:"No popby activity yet!"}),s.jsx("p",{className:"text-sm mt-1",children:"Start logging popbys to see your history here."})]})}):s.jsxs(at,{children:[s.jsx(xr,{children:s.jsx(wr,{className:"text-lg",children:"Recent Popby Log"})}),s.jsx(ct,{className:"space-y-3",children:o.map(pe=>s.jsxs("div",{className:"flex items-start gap-3 pb-3 border-b last:border-0 last:pb-0",children:[s.jsx("div",{className:"h-10 w-10 rounded-full bg-orange-500/10 flex items-center justify-center",children:s.jsx(yd,{className:"h-5 w-5 text-orange-500"})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:"font-medium",children:j(pe.contact_id)}),N(pe.popby_item_id)&&s.jsx(ir,{variant:"secondary",className:"text-xs",children:N(pe.popby_item_id)})]}),s.jsx("div",{className:"text-sm text-muted-foreground",children:Vn(new Date(pe.completed_at),"MMM d, yyyy h:mm a")}),pe.notes&&s.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:pe.notes})]})]},pe.id))})]})}),s.jsx(xs,{value:"library",className:"space-y-4 mt-4",children:s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[r==null?void 0:r.map(pe=>s.jsx(at,{children:s.jsx(ct,{className:"p-4",children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:s.jsx(yd,{className:"h-5 w-5 text-primary"})}),s.jsxs("div",{className:"flex-1",children:[s.jsx("h3",{className:"font-medium",children:pe.name}),pe.description&&s.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:pe.description}),!pe.owner_user_id&&s.jsx(ir,{variant:"secondary",className:"mt-2 text-xs",children:"Shared"})]})]})})},pe.id)),s.jsx(at,{className:"border-dashed cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>W(!0),children:s.jsx(ct,{className:"p-4 flex items-center justify-center h-full min-h-[100px]",children:s.jsxs("div",{className:"text-center text-muted-foreground",children:[s.jsx(Qn,{className:"h-8 w-8 mx-auto mb-2"}),s.jsx("p",{children:"Add New Popby Idea"})]})})})]})})]}),s.jsx(mn,{open:A,onOpenChange:I,children:s.jsxs(pn,{children:[s.jsx(xn,{children:s.jsxs(gn,{children:["Log Popby for ",C==null?void 0:C.first_name," ",C==null?void 0:C.last_name]})}),s.jsxs("div",{className:"space-y-4 py-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Popby Item (optional)"}),s.jsxs(Kn,{value:V.popby_item_id,onValueChange:pe=>K(ve=>({...ve,popby_item_id:pe})),children:[s.jsx(qn,{children:s.jsx(Zn,{placeholder:"Select a popby item..."})}),s.jsx(Hn,{children:r==null?void 0:r.map(pe=>s.jsx(_r,{value:pe.id,children:pe.name},pe.id))})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Notes (optional)"}),s.jsx(mi,{placeholder:"Any notes about this popby...",value:V.notes,onChange:pe=>K(ve=>({...ve,notes:pe.target.value}))})]})]}),s.jsxs(zi,{children:[s.jsx(de,{variant:"outline",onClick:()=>I(!1),children:"Cancel"}),s.jsx(de,{onClick:X,disabled:m.isPending,children:"Log Popby"})]})]})}),s.jsx(mn,{open:O,onOpenChange:R,children:s.jsxs(pn,{className:"max-w-md",children:[s.jsx(xn,{children:s.jsx(gn,{children:"Popby Frequency Settings"})}),s.jsxs("div",{className:"space-y-4 py-4",children:[s.jsx("p",{className:"text-sm text-muted-foreground",children:"Set default popby frequency for each relationship type. You can override these per-contact."}),n==null?void 0:n.map(pe=>s.jsxs("div",{className:"flex items-center justify-between gap-4",children:[s.jsx(mt,{className:"font-medium",children:pe.name}),s.jsxs(Kn,{value:xe(pe.id),onValueChange:ve=>he(pe.id,ve),children:[s.jsx(qn,{className:"w-[180px]",children:s.jsx(Zn,{})}),s.jsx(Hn,{children:k7e.map(ve=>s.jsx(_r,{value:ve.value,children:ve.label},ve.value))})]})]},pe.id))]}),s.jsx(zi,{children:s.jsx(de,{onClick:()=>R(!1),children:"Done"})})]})}),s.jsx(mn,{open:z,onOpenChange:W,children:s.jsxs(pn,{children:[s.jsx(xn,{children:s.jsx(gn,{children:"Add Popby Idea"})}),s.jsxs("div",{className:"space-y-4 py-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Name *"}),s.jsx(Et,{placeholder:"e.g., Homemade cookies",value:Q.name,onChange:pe=>te(ve=>({...ve,name:pe.target.value}))})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Description"}),s.jsx(mi,{placeholder:"Optional description...",value:Q.description,onChange:pe=>te(ve=>({...ve,description:pe.target.value}))})]})]}),s.jsxs(zi,{children:[s.jsx(de,{variant:"outline",onClick:()=>W(!1),children:"Cancel"}),s.jsx(de,{onClick:ie,disabled:!Q.name.trim()||g.isPending,children:"Add Item"})]})]})})]})})}var Vye={exports:{}};(function(t,e){(function(r,n){t.exports=n()})(IC,function(){var r,n,i;function o(a,m){if(!r)r=m;else if(!n)n=m;else{var g="self.onerror = function() { console.error('An error occurred while parsing the WebWorker bundle. This is most likely due to improper transpilation by Babel; please see https://docs.mapbox.com/mapbox-gl-js/guides/install/#transpiling'); }; var sharedChunk = {}; ("+r+")(sharedChunk); ("+n+")(sharedChunk); self.onerror = null;",_={};r(_),i=m(_),typeof window<"u"&&window&&window.URL&&window.URL.createObjectURL&&(i.workerUrl=window.URL.createObjectURL(new Blob([g],{type:"text/javascript"})))}}o(["exports"],function(a){var m=1e-6,g=typeof Float32Array<"u"?Float32Array:Array;function _(h,l){var d=l[0],p=l[1],y=l[2],b=l[3],w=d*b-y*p;return w?(h[0]=b*(w=1/w),h[1]=-p*w,h[2]=-y*w,h[3]=d*w,h):null}function j(){var h=new g(9);return g!=Float32Array&&(h[1]=0,h[2]=0,h[3]=0,h[5]=0,h[6]=0,h[7]=0),h[0]=1,h[4]=1,h[8]=1,h}function N(h,l){var d=l[0],p=l[1],y=l[2],b=l[3],w=l[4],k=l[5],M=l[6],F=l[7],$=l[8];return h[0]=w*$-k*F,h[1]=y*F-p*$,h[2]=p*k-y*w,h[3]=k*M-b*$,h[4]=d*$-y*M,h[5]=y*b-d*k,h[6]=b*F-w*M,h[7]=p*M-d*F,h[8]=d*w-p*b,h}function C(h,l,d){var p=l[0],y=l[1],b=l[2],w=l[3],k=l[4],M=l[5],F=l[6],$=l[7],U=l[8],H=d[0],Z=d[1],Y=d[2],ne=d[3],ce=d[4],le=d[5],ye=d[6],we=d[7],Ee=d[8];return h[0]=H*p+Z*w+Y*F,h[1]=H*y+Z*k+Y*$,h[2]=H*b+Z*M+Y*U,h[3]=ne*p+ce*w+le*F,h[4]=ne*y+ce*k+le*$,h[5]=ne*b+ce*M+le*U,h[6]=ye*p+we*w+Ee*F,h[7]=ye*y+we*k+Ee*$,h[8]=ye*b+we*M+Ee*U,h}function P(){var h=new g(16);return g!=Float32Array&&(h[1]=0,h[2]=0,h[3]=0,h[4]=0,h[6]=0,h[7]=0,h[8]=0,h[9]=0,h[11]=0,h[12]=0,h[13]=0,h[14]=0),h[0]=1,h[5]=1,h[10]=1,h[15]=1,h}function A(h){var l=new g(16);return l[0]=h[0],l[1]=h[1],l[2]=h[2],l[3]=h[3],l[4]=h[4],l[5]=h[5],l[6]=h[6],l[7]=h[7],l[8]=h[8],l[9]=h[9],l[10]=h[10],l[11]=h[11],l[12]=h[12],l[13]=h[13],l[14]=h[14],l[15]=h[15],l}function I(h){return h[0]=1,h[1]=0,h[2]=0,h[3]=0,h[4]=0,h[5]=1,h[6]=0,h[7]=0,h[8]=0,h[9]=0,h[10]=1,h[11]=0,h[12]=0,h[13]=0,h[14]=0,h[15]=1,h}function O(h,l){var d=l[0],p=l[1],y=l[2],b=l[3],w=l[4],k=l[5],M=l[6],F=l[7],$=l[8],U=l[9],H=l[10],Z=l[11],Y=l[12],ne=l[13],ce=l[14],le=l[15],ye=d*k-p*w,we=d*M-y*w,Ee=d*F-b*w,Ue=p*M-y*k,Le=p*F-b*k,Ke=y*F-b*M,Je=$*ne-U*Y,it=$*ce-H*Y,Pt=$*le-Z*Y,ft=U*ce-H*ne,Ft=U*le-Z*ne,Vt=H*le-Z*ce,qt=ye*Vt-we*Ft+Ee*ft+Ue*Pt-Le*it+Ke*Je;return qt?(h[0]=(k*Vt-M*Ft+F*ft)*(qt=1/qt),h[1]=(y*Ft-p*Vt-b*ft)*qt,h[2]=(ne*Ke-ce*Le+le*Ue)*qt,h[3]=(H*Le-U*Ke-Z*Ue)*qt,h[4]=(M*Pt-w*Vt-F*it)*qt,h[5]=(d*Vt-y*Pt+b*it)*qt,h[6]=(ce*Ee-Y*Ke-le*we)*qt,h[7]=($*Ke-H*Ee+Z*we)*qt,h[8]=(w*Ft-k*Pt+F*Je)*qt,h[9]=(p*Pt-d*Ft-b*Je)*qt,h[10]=(Y*Le-ne*Ee+le*ye)*qt,h[11]=(U*Ee-$*Le-Z*ye)*qt,h[12]=(k*it-w*ft-M*Je)*qt,h[13]=(d*ft-p*it+y*Je)*qt,h[14]=(ne*we-Y*Ue-ce*ye)*qt,h[15]=($*Ue-U*we+H*ye)*qt,h):null}function R(h,l,d){var p=l[0],y=l[1],b=l[2],w=l[3],k=l[4],M=l[5],F=l[6],$=l[7],U=l[8],H=l[9],Z=l[10],Y=l[11],ne=l[12],ce=l[13],le=l[14],ye=l[15],we=d[0],Ee=d[1],Ue=d[2],Le=d[3];return h[0]=we*p+Ee*k+Ue*U+Le*ne,h[1]=we*y+Ee*M+Ue*H+Le*ce,h[2]=we*b+Ee*F+Ue*Z+Le*le,h[3]=we*w+Ee*$+Ue*Y+Le*ye,h[4]=(we=d[4])*p+(Ee=d[5])*k+(Ue=d[6])*U+(Le=d[7])*ne,h[5]=we*y+Ee*M+Ue*H+Le*ce,h[6]=we*b+Ee*F+Ue*Z+Le*le,h[7]=we*w+Ee*$+Ue*Y+Le*ye,h[8]=(we=d[8])*p+(Ee=d[9])*k+(Ue=d[10])*U+(Le=d[11])*ne,h[9]=we*y+Ee*M+Ue*H+Le*ce,h[10]=we*b+Ee*F+Ue*Z+Le*le,h[11]=we*w+Ee*$+Ue*Y+Le*ye,h[12]=(we=d[12])*p+(Ee=d[13])*k+(Ue=d[14])*U+(Le=d[15])*ne,h[13]=we*y+Ee*M+Ue*H+Le*ce,h[14]=we*b+Ee*F+Ue*Z+Le*le,h[15]=we*w+Ee*$+Ue*Y+Le*ye,h}function z(h,l,d){var p,y,b,w,k,M,F,$,U,H,Z,Y,ne=d[0],ce=d[1],le=d[2];return l===h?(h[12]=l[0]*ne+l[4]*ce+l[8]*le+l[12],h[13]=l[1]*ne+l[5]*ce+l[9]*le+l[13],h[14]=l[2]*ne+l[6]*ce+l[10]*le+l[14],h[15]=l[3]*ne+l[7]*ce+l[11]*le+l[15]):(y=l[1],b=l[2],w=l[3],k=l[4],M=l[5],F=l[6],$=l[7],U=l[8],H=l[9],Z=l[10],Y=l[11],h[0]=p=l[0],h[1]=y,h[2]=b,h[3]=w,h[4]=k,h[5]=M,h[6]=F,h[7]=$,h[8]=U,h[9]=H,h[10]=Z,h[11]=Y,h[12]=p*ne+k*ce+U*le+l[12],h[13]=y*ne+M*ce+H*le+l[13],h[14]=b*ne+F*ce+Z*le+l[14],h[15]=w*ne+$*ce+Y*le+l[15]),h}function W(h,l,d){var p=d[0],y=d[1],b=d[2];return h[0]=l[0]*p,h[1]=l[1]*p,h[2]=l[2]*p,h[3]=l[3]*p,h[4]=l[4]*y,h[5]=l[5]*y,h[6]=l[6]*y,h[7]=l[7]*y,h[8]=l[8]*b,h[9]=l[9]*b,h[10]=l[10]*b,h[11]=l[11]*b,h[12]=l[12],h[13]=l[13],h[14]=l[14],h[15]=l[15],h}function V(h,l,d){var p=Math.sin(d),y=Math.cos(d),b=l[4],w=l[5],k=l[6],M=l[7],F=l[8],$=l[9],U=l[10],H=l[11];return l!==h&&(h[0]=l[0],h[1]=l[1],h[2]=l[2],h[3]=l[3],h[12]=l[12],h[13]=l[13],h[14]=l[14],h[15]=l[15]),h[4]=b*y+F*p,h[5]=w*y+$*p,h[6]=k*y+U*p,h[7]=M*y+H*p,h[8]=F*y-b*p,h[9]=$*y-w*p,h[10]=U*y-k*p,h[11]=H*y-M*p,h}function K(h,l,d){var p=Math.sin(d),y=Math.cos(d),b=l[0],w=l[1],k=l[2],M=l[3],F=l[8],$=l[9],U=l[10],H=l[11];return l!==h&&(h[4]=l[4],h[5]=l[5],h[6]=l[6],h[7]=l[7],h[12]=l[12],h[13]=l[13],h[14]=l[14],h[15]=l[15]),h[0]=b*y-F*p,h[1]=w*y-$*p,h[2]=k*y-U*p,h[3]=M*y-H*p,h[8]=b*p+F*y,h[9]=w*p+$*y,h[10]=k*p+U*y,h[11]=M*p+H*y,h}function Q(h,l,d){var p=Math.sin(d),y=Math.cos(d),b=l[0],w=l[1],k=l[2],M=l[3],F=l[4],$=l[5],U=l[6],H=l[7];return l!==h&&(h[8]=l[8],h[9]=l[9],h[10]=l[10],h[11]=l[11],h[12]=l[12],h[13]=l[13],h[14]=l[14],h[15]=l[15]),h[0]=b*y+F*p,h[1]=w*y+$*p,h[2]=k*y+U*p,h[3]=M*y+H*p,h[4]=F*y-b*p,h[5]=$*y-w*p,h[6]=U*y-k*p,h[7]=H*y-M*p,h}function te(h,l){return h[0]=l[0],h[1]=0,h[2]=0,h[3]=0,h[4]=0,h[5]=l[1],h[6]=0,h[7]=0,h[8]=0,h[9]=0,h[10]=l[2],h[11]=0,h[12]=0,h[13]=0,h[14]=0,h[15]=1,h}function X(h,l,d){var p,y,b,w=d[0],k=d[1],M=d[2],F=Math.sqrt(w*w+k*k+M*M);return F0&&(b=1/Math.sqrt(b)),h[0]=l[0]*b,h[1]=l[1]*b,h[2]=l[2]*b,h}function Ie(h,l){return h[0]*l[0]+h[1]*l[1]+h[2]*l[2]}function Be(h,l,d){var p=l[0],y=l[1],b=l[2],w=d[0],k=d[1],M=d[2];return h[0]=y*M-b*k,h[1]=b*w-p*M,h[2]=p*k-y*w,h}function Pe(h,l,d,p){var y=l[0],b=l[1],w=l[2];return h[0]=y+p*(d[0]-y),h[1]=b+p*(d[1]-b),h[2]=w+p*(d[2]-w),h}function ut(h,l,d){var p=l[0],y=l[1],b=l[2],w=d[3]*p+d[7]*y+d[11]*b+d[15];return h[0]=(d[0]*p+d[4]*y+d[8]*b+d[12])/(w=w||1),h[1]=(d[1]*p+d[5]*y+d[9]*b+d[13])/w,h[2]=(d[2]*p+d[6]*y+d[10]*b+d[14])/w,h}function jt(h,l,d){var p=l[0],y=l[1],b=l[2];return h[0]=p*d[0]+y*d[3]+b*d[6],h[1]=p*d[1]+y*d[4]+b*d[7],h[2]=p*d[2]+y*d[5]+b*d[8],h}function $t(h,l,d){var p=d[0],y=d[1],b=d[2],w=d[3],k=l[0],M=l[1],F=l[2],$=y*F-b*M,U=b*k-p*F,H=p*M-y*k;return h[0]=k+w*($+=$)+y*(H+=H)-b*(U+=U),h[1]=M+w*U+b*$-p*H,h[2]=F+w*H+p*U-y*$,h}function Ht(h){return h[0]=0,h[1]=0,h[2]=0,h}function Lt(h,l){return h[0]===l[0]&&h[1]===l[1]&&h[2]===l[2]}var Kt=je,Ar=et,rt=ge;function We(){var h=new g(4);return g!=Float32Array&&(h[0]=0,h[1]=0,h[2]=0,h[3]=0),h}function _t(h,l,d){return h[0]=l[0]*d,h[1]=l[1]*d,h[2]=l[2]*d,h[3]=l[3]*d,h}function Gt(h,l){var d=l[0],p=l[1],y=l[2],b=l[3],w=d*d+p*p+y*y+b*b;return w>0&&(w=1/Math.sqrt(w)),h[0]=d*w,h[1]=p*w,h[2]=y*w,h[3]=b*w,h}function rr(h,l,d){var p=l[0],y=l[1],b=l[2],w=l[3];return h[0]=d[0]*p+d[4]*y+d[8]*b+d[12]*w,h[1]=d[1]*p+d[5]*y+d[9]*b+d[13]*w,h[2]=d[2]*p+d[6]*y+d[10]*b+d[14]*w,h[3]=d[3]*p+d[7]*y+d[11]*b+d[15]*w,h}function pr(){var h=new g(4);return g!=Float32Array&&(h[0]=0,h[1]=0,h[2]=0),h[3]=1,h}function kr(h){return h[0]=0,h[1]=0,h[2]=0,h[3]=1,h}function Hr(h,l,d){d*=.5;var p=l[0],y=l[1],b=l[2],w=l[3],k=Math.sin(d),M=Math.cos(d);return h[0]=p*M+w*k,h[1]=y*M+b*k,h[2]=b*M-y*k,h[3]=w*M-p*k,h}function Fn(h,l,d){d*=.5;var p=l[0],y=l[1],b=l[2],w=l[3],k=Math.sin(d),M=Math.cos(d);return h[0]=p*M-b*k,h[1]=y*M+w*k,h[2]=b*M+p*k,h[3]=w*M-y*k,h}pe(),We();var Os,ia,pa,zo=Gt,Xo=(Os=pe(),ia=ke(1,0,0),pa=ke(0,1,0),function(h,l,d){var p=Ie(l,d);return p<-.999999?(Be(Os,ia,l),rt(Os)<1e-6&&Be(Os,pa,l),Oe(Os,Os),function(y,b,w){w*=.5;var k=Math.sin(w);y[0]=k*b[0],y[1]=k*b[1],y[2]=k*b[2],y[3]=Math.cos(w)}(h,Os,Math.PI),h):p>.999999?(h[0]=0,h[1]=0,h[2]=0,h[3]=1,h):(Be(Os,l,d),h[0]=Os[0],h[1]=Os[1],h[2]=Os[2],h[3]=1+p,zo(h,h))});function Xs(){var h=new g(2);return g!=Float32Array&&(h[0]=0,h[1]=0),h}function Ma(h,l){var d=new g(2);return d[0]=h,d[1]=l,d}function Qo(h,l,d){return h[0]=l,h[1]=d,h}function ec(h,l,d){return h[0]=l[0]+d[0],h[1]=l[1]+d[1],h}function yl(h,l,d){return h[0]=l[0]-d[0],h[1]=l[1]-d[1],h}function tc(h,l,d){return h[0]=l[0]*d,h[1]=l[1]*d,h}function Jo(h){var l=h[0],d=h[1];return Math.sqrt(l*l+d*d)}function wh(h,l){var d=l[0],p=l[1],y=d*d+p*p;return y>0&&(y=1/Math.sqrt(y)),h[0]=l[0]*y,h[1]=l[1]*y,h}function xa(h,l){return h[0]*l[0]+h[1]*l[1]}pr(),pr(),j();var Qs,La,Ss=yl;function bi(h){return h&&h.__esModule&&Object.prototype.hasOwnProperty.call(h,"default")?h.default:h}Xs();var ki=function(){if(La)return Qs;function h(l,d,p,y){this.cx=3*l,this.bx=3*(p-l)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*d,this.by=3*(y-d)-this.cy,this.ay=1-this.cy-this.by,this.p1x=l,this.p1y=d,this.p2x=p,this.p2y=y}return La=1,Qs=h,h.prototype={sampleCurveX:function(l){return((this.ax*l+this.bx)*l+this.cx)*l},sampleCurveY:function(l){return((this.ay*l+this.by)*l+this.cy)*l},sampleCurveDerivativeX:function(l){return(3*this.ax*l+2*this.bx)*l+this.cx},solveCurveX:function(l,d){if(d===void 0&&(d=1e-6),l<0)return 0;if(l>1)return 1;for(var p=l,y=0;y<8;y++){var b=this.sampleCurveX(p)-l;if(Math.abs(b)b?k=p:M=p,p=.5*(M-k)+k;return p},solve:function(l,d){return this.sampleCurveY(this.solveCurveX(l,d))}},Qs}(),yo=bi(ki);function Wt(h,l){this.x=h,this.y=l}function xo(h,l){if(Array.isArray(h)){if(!Array.isArray(l)||h.length!==l.length)return!1;for(let d=0;d=1)return 1;const l=h*h,d=l*h;return 4*(h<.5?d:3*(h-l)+d-.75)}function Fp(h,l,d,p){const y=new yo(h,l,d,p);return function(b){return y.solve(b)}}const vt=Fp(.25,.1,.25,1);function ue(h,l,d){return Math.min(d,Math.max(l,h))}function be(h,l,d){return(d=ue((d-h)/(l-h),0,1))*d*(3-2*d)}function Re(h,l,d){const p=d-l,y=((h-l)%p+p)%p+l;return y===l?d:y}function tt(h,l,d){if(!h.length)return d(null,[]);let p=h.length;const y=new Array(h.length);let b=null;h.forEach((w,k)=>{l(w,(M,F)=>{M&&(b=M),y[k]=F,--p==0&&d(b,y)})})}let Xe=1;function lt(){return Xe++}function Ct(h){return h<=1?1:Math.pow(2,Math.ceil(Math.log2(h)))}function dt(h,l){h.forEach(d=>{l[d]&&(l[d]=l[d].bind(l))})}function St(h,l,d){const p={};for(const y in h)p[y]=l.call(this,h[y],y,h);return p}function sr(h,l,d){const p={};for(const y in h)l.call(this,h[y],y,h)&&(p[y]=h[y]);return p}function Ut(h){return Array.isArray(h)?h.map(Ut):typeof h=="object"&&h?St(h,Ut):h}function Ir(h,l){for(let d=0;d=0)return!0;return!1}const en={};function Ge(h){en[h]||(typeof console<"u"&&console.warn(h),en[h]=!0)}function ur(h,l,d){return(d.y-h.y)*(l.x-h.x)>(l.y-h.y)*(d.x-h.x)}function jr(h){let l=0;for(let d,p,y=0,b=h.length,w=b-1;y@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g,(d,p,y,b)=>{const w=y||b;return l[p]=!w||w.toLowerCase(),""}),l["max-age"]){const d=parseInt(l["max-age"],10);isNaN(d)?delete l["max-age"]:l["max-age"]=d}return l}let Mi=null;function Zi(h,l){return[h[4*l],h[4*l+1],h[4*l+2],h[4*l+3]]}function Oa(h,l,d,p){for(;l>1;h[y]>1;h[y]<=p?l=y+1:d=y}return l}function _s(h){return h>0?1/(1.001-h):1+h}function Xi(h){return h>0?1-1/(1.001-h):-h}function gi(h,l,d){return(h-l.min)*(d.max-d.min)/(l.max-l.min)+d.min}const is={API_URL:"https://api.mapbox.com",get API_URL_REGEX(){return/^((https?:)?\/\/)?([^\/]+\.)?mapbox\.c(n|om)(\/|\?|$)/i},get API_TILEJSON_REGEX(){return/^((https?:)?\/\/)?([^\/]+\.)?mapbox\.c(n|om)(\/v[0-9]*\/.*\.json.*$)/i},get API_SPRITE_REGEX(){return/^((https?:)?\/\/)?([^\/]+\.)?mapbox\.c(n|om)(\/styles\/v[0-9]*\/)(.*\/sprite.*\..*$)/i},get API_FONTS_REGEX(){return/^((https?:)?\/\/)?([^\/]+\.)?mapbox\.c(n|om)(\/fonts\/v[0-9]*\/)(.*\.pbf.*$)/i},get API_STYLE_REGEX(){return/^((https?:)?\/\/)?([^\/]+\.)?mapbox\.c(n|om)(\/styles\/v[0-9]*\/)(.*$)/i},get API_CDN_URL_REGEX(){return/^((https?:)?\/\/)?api\.mapbox\.c(n|om)(\/mapbox-gl-js\/)(.*$)/i},get EVENTS_URL(){if(!is.API_URL)return null;try{const h=new URL(is.API_URL);return h.hostname==="api.mapbox.cn"?"https://events.mapbox.cn/events/v2":h.hostname==="api.mapbox.com"?"https://events.mapbox.com/events/v2":null}catch{return null}},SESSION_PATH:"/map-sessions/v1",FEEDBACK_URL:"https://apps.mapbox.com/feedback",TILE_URL_VERSION:"v4",RASTER_URL_PREFIX:"raster/v1",RASTERARRAYS_URL_PREFIX:"rasterarrays/v1",REQUIRE_ACCESS_TOKEN:!0,ACCESS_TOKEN:null,DEFAULT_STYLE:"mapbox://styles/mapbox/standard",MAX_PARALLEL_IMAGE_REQUESTS:16,DRACO_URL:"https://api.mapbox.com/mapbox-gl-js/draco_decoder_gltf_v1.5.6.wasm",MESHOPT_URL:"https://api.mapbox.com/mapbox-gl-js/meshopt_base_v0.20.wasm",MESHOPT_SIMD_URL:"https://api.mapbox.com/mapbox-gl-js/meshopt_simd_v0.20.wasm",BUILDING_GEN_URL:"https://api.mapbox.com/mapbox-gl-js/building-gen/building_gen_v1.2.4.wasm",GLYPHS_URL:"mapbox://fonts/mapbox/{fontstack}/{range}.pbf",TILES3D_URL_PREFIX:"3dtiles/v1"};function ca(h){return is.API_URL_REGEX.test(h)}function $o(h){return is.API_SPRITE_REGEX.test(h)}let el,rc,zp,vo,Bc,xl;function Td(){return el==null&&(el=self.OffscreenCanvas&&new OffscreenCanvas(1,1).getContext("2d")&&typeof self.createImageBitmap=="function"),el}const lo={now:()=>vo!==void 0?vo:performance.now(),setNow(h){vo=h},restoreNow(){vo=void 0},frame(h){const l=requestAnimationFrame(h);return{cancel:()=>cancelAnimationFrame(l)}},getImageData(h,l=0){const{width:d,height:p}=h;Bc||(Bc=document.createElement("canvas"));const y=Bc.getContext("2d",{willReadFrequently:!0});if(!y)throw new Error("failed to create canvas 2d context");return(d>Bc.width||p>Bc.height)&&(Bc.width=d,Bc.height=p),y.clearRect(-l,-l,d+2*l,p+2*l),y.drawImage(h,0,0,d,p),y.getImageData(-l,-l,d+2*l,p+2*l)},resolveURL:h=>(rc||(rc=document.createElement("a")),rc.href=h,rc.href),get devicePixelRatio(){return window.devicePixelRatio},get prefersReducedMotion(){return!!window.matchMedia&&(zp==null&&(zp=window.matchMedia("(prefers-reduced-motion: reduce)")),zp.matches)},hasCanvasFingerprintNoise(){if(xl!==void 0)return xl;if(!Td())return xl=!1,!1;const h=new OffscreenCanvas(85,1),l=h.getContext("2d",{willReadFrequently:!0});let d=0;for(let y=0;y0?`?${b}`:""}`}const p0="mapbox-tiles";let m0=500,g0=50;const Ix=["language","worldview","jobid"];let Ed,nc;function Gu(){try{return caches}catch{}}function Ku(){const h=Gu();h&&Ed==null&&(Ed=h.open(p0))}let yu=1/0;const Ad={supported:!1,testSupport:function(h){!y0&&$p&&(Up?XT(h):If=h)}};let If,$p,y0=!1,Up=!1;const x0=typeof self<"u"?self:{};function XT(h){const l=h.createTexture();h.bindTexture(h.TEXTURE_2D,l);try{if(h.texImage2D(h.TEXTURE_2D,0,h.RGBA,h.RGBA,h.UNSIGNED_BYTE,$p),h.isContextLost())return;Ad.supported=!0}catch{}h.deleteTexture(l),y0=!0}x0.document&&($p=x0.document.createElement("img"),$p.onload=function(){If&&XT(If),If=null,Up=!0},$p.onerror=function(){y0=!0,If=null},$p.src="data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA=");const Mx={Unknown:"Unknown",Style:"Style",Source:"Source",Tile:"Tile",Glyphs:"Glyphs",SpriteImage:"SpriteImage",SpriteJSON:"SpriteJSON",Iconset:"Iconset",Image:"Image",Model:"Model"};typeof Object.freeze=="function"&&Object.freeze(Mx);class jc extends Error{constructor(l,d,p){d===401&&ca(p)&&(l+=": you may have provided an invalid Mapbox access token. See https://docs.mapbox.com/api/overview/#access-tokens-and-token-scopes"),super(l),this.status=d,this.url=p}toString(){return`${this.name}: ${this.message} (${this.status}): ${this.url}`}}const v0=cn()?()=>self.worker.referrer:()=>(location.protocol==="blob:"?parent:self).location.href,Vp=function(h,l){if(!(/^file:/.test(d=h.url)||/^file:/.test(v0())&&!/^\w+:/.test(d))){if(self.fetch&&self.Request&&self.AbortController&&Request.prototype.hasOwnProperty("signal"))return function(p,y){const b=new AbortController,w=new Request(p.url,{method:p.method||"GET",body:p.body,credentials:p.credentials,headers:p.headers,referrer:v0(),referrerPolicy:p.referrerPolicy,signal:b.signal});let k=!1,M=!1;const F=($=w.url).indexOf("sku=")>0&&ca($);var $;p.type==="json"&&w.headers.set("Accept","application/json");const U=(Z,Y,ne)=>{if(M)return;if(Z&&Z.message!=="SecurityError"&&Ge(Z.toString()),Y&&ne)return H(Y);const ce=Date.now();fetch(w).then(le=>{if(le.ok){const ye=F?le.clone():null;return H(le,ye,ce)}return y(new jc(le.statusText,le.status,p.url))}).catch(le=>{le.name!=="AbortError"&&y(new Error(`${le.message} ${p.url}`))})},H=(Z,Y,ne)=>{(p.type==="arrayBuffer"?Z.arrayBuffer():p.type==="json"?Z.json():Z.text()).then(ce=>{M||(Y&&ne&&function(le,ye,we){if(Ku(),Ed==null)return;const Ee=Ns(ye.headers.get("Cache-Control")||"");if(Ee["no-store"])return;const Ue={status:ye.status,statusText:ye.statusText,headers:new Headers};ye.headers.forEach((Je,it)=>Ue.headers.set(it,Je)),Ee["max-age"]&&Ue.headers.set("Expires",new Date(we+1e3*Ee["max-age"]).toUTCString());const Le=Ue.headers.get("Expires");if(!Le||new Date(Le).getTime()-we<42e4)return;let Ke=hg(le.url,{persistentParams:Ix});if(ye.status===206){const Je=le.headers.get("Range");if(!Je)return;Ue.status=200,Ke=Bp(Ke,{range:Je})}(function(Je,it){if(nc===void 0)try{new Response(new ReadableStream),nc=!0}catch{nc=!1}nc?it(Je.body):Je.blob().then(it).catch(Pt=>Ge(Pt.message))})(ye,Je=>{const it=new Response((Pt=ye.status)!==200&&Pt!==404&&[101,103,204,205,304].includes(Pt)?null:Je,Ue);var Pt;Ku(),Ed!=null&&Ed.then(ft=>ft.put(Ke,it)).catch(ft=>Ge(ft.message))})}(w,Y,ne),k=!0,y(null,ce,Z.headers))}).catch(ce=>{M||y(new Error(ce.message))})};return F?function(Z,Y){if(Ku(),Ed==null)return Y(null);Ed.then(ne=>{let ce=hg(Z.url,{persistentParams:Ix});const le=Z.headers.get("Range");le&&(ce=Bp(ce,{range:le})),ne.match(ce).then(ye=>{const we=function(Ee){if(!Ee)return!1;const Ue=new Date(Ee.headers.get("Expires")||0),Le=Ns(Ee.headers.get("Cache-Control")||"");return Number(Ue)>Date.now()&&!Le["no-cache"]}(ye);ne.delete(ce).catch(Y),we&&ne.put(ce,ye.clone()).catch(Y),Y(null,ye,we)}).catch(Y)}).catch(Y)}(w,U):U(null,null),{cancel:()=>{M=!0,k||b.abort()}}}(h,l);if(cn(self)&&self.worker.actor)return self.worker.actor.send("getResource",h,l,void 0,!0)}var d;return function(p,y){const b=new XMLHttpRequest;b.open(p.method||"GET",p.url,!0),p.type==="arrayBuffer"&&(b.responseType="arraybuffer");for(const w in p.headers)b.setRequestHeader(w,p.headers[w]);return p.type==="json"&&(b.responseType="text",b.setRequestHeader("Accept","application/json")),b.withCredentials=p.credentials==="include",b.onerror=()=>{y(new Error(b.statusText))},b.onload=()=>{if((b.status>=200&&b.status<300||b.status===0)&&b.response!==null){let w=b.response;if(p.type==="json")try{w=JSON.parse(b.response)}catch(M){return y(M)}const k=new Headers;b.getAllResponseHeaders().trim().split(/[\r\n]+/).forEach(M=>{const F=M.split(": "),$=F.shift(),U=F.join(": ");k.append($,U)}),y(null,w,k)}else y(new jc(b.statusText,b.status,p.url))},b.send(p.body),{cancel:()=>b.abort()}}(h,l)},Sh=function(h,l){return Vp(Object.assign(h,{type:"arrayBuffer"}),l)};function i4(h){const l=document.createElement("a");return l.href=h,l.protocol===location.protocol&&l.host===location.host}const QT="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYV2NgAAIAAAUAAarVyFEAAAAASUVORK5CYII=";let Ox,bs;Ox=[],bs=0;const _0=function(h,l){if(Ad.supported&&(h.headers||(h.headers={}),h.headers.accept="image/webp,*/*"),bs>=is.MAX_PARALLEL_IMAGE_REQUESTS){const b={requestParameters:h,callback:l,cancelled:!1,cancel(){this.cancelled=!0}};return Ox.push(b),b}bs++;let d=!1;const p=()=>{if(!d)for(d=!0,bs--;Ox.length&&bs{p(),b?l(b):w&&(self.createImageBitmap?function(M,F){const $=new Blob([new Uint8Array(M)],{type:"image/png"});createImageBitmap($).then(U=>{F(null,U)}).catch(U=>{F(new Error(`Could not load image because of ${U.message}. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.`))})}(w,(M,F)=>l(M,F,k)):function(M,F){const $=new Image;$.onload=()=>{F(null,$),URL.revokeObjectURL($.src),$.onload=null,requestAnimationFrame(()=>{$.src=QT})},$.onerror=()=>F(new Error("Could not load image. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported."));const U=new Blob([new Uint8Array(M)],{type:"image/png"});$.src=M.byteLength?URL.createObjectURL(U):QT}(w,(M,F)=>l(M,F,k)))});return{cancel:()=>{y.cancel(),p()}}};var oS,JT,eE,Mf={exports:{}},Rx={exports:{}},Dx={exports:{}},lS=function(){if(eE)return Mf.exports;eE=1;var h=(oS||(oS=1,Rx.exports=function(d,p){var y,b,w,k,M,F,$,U;for(b=d.length-(y=3&d.length),w=p,M=3432918353,F=461845907,U=0;U>>16)*M&65535)<<16)&4294967295)<<15|$>>>17))*F+((($>>>16)*F&65535)<<16)&4294967295)<<13|w>>>19))+((5*(w>>>16)&65535)<<16)&4294967295))+((58964+(k>>>16)&65535)<<16);switch($=0,y){case 3:$^=(255&d.charCodeAt(U+2))<<16;case 2:$^=(255&d.charCodeAt(U+1))<<8;case 1:w^=$=(65535&($=($=(65535&($^=255&d.charCodeAt(U)))*M+((($>>>16)*M&65535)<<16)&4294967295)<<15|$>>>17))*F+((($>>>16)*F&65535)<<16)&4294967295}return w^=d.length,w=2246822507*(65535&(w^=w>>>16))+((2246822507*(w>>>16)&65535)<<16)&4294967295,w=3266489909*(65535&(w^=w>>>13))+((3266489909*(w>>>16)&65535)<<16)&4294967295,(w^=w>>>16)>>>0}),Rx.exports),l=(JT||(JT=1,Dx.exports=function(d,p){for(var y,b=d.length,w=p^b,k=0;b>=4;)y=1540483477*(65535&(y=255&d.charCodeAt(k)|(255&d.charCodeAt(++k))<<8|(255&d.charCodeAt(++k))<<16|(255&d.charCodeAt(++k))<<24))+((1540483477*(y>>>16)&65535)<<16),w=1540483477*(65535&w)+((1540483477*(w>>>16)&65535)<<16)^(y=1540483477*(65535&(y^=y>>>24))+((1540483477*(y>>>16)&65535)<<16)),b-=4,++k;switch(b){case 3:w^=(255&d.charCodeAt(k+2))<<16;case 2:w^=(255&d.charCodeAt(k+1))<<8;case 1:w=1540483477*(65535&(w^=255&d.charCodeAt(k)))+((1540483477*(w>>>16)&65535)<<16)}return w=1540483477*(65535&(w^=w>>>13))+((1540483477*(w>>>16)&65535)<<16),(w^=w>>>15)>>>0}),Dx.exports);return Mf.exports=h,Mf.exports.murmur3=h,Mf.exports.murmur2=l,Mf.exports}(),b0=bi(lS);class Pd{constructor(l,...d){Object.assign(this,d[0]||{}),this.type=l}}class Lx extends Pd{constructor(l,d={}){super("error",Object.assign({error:l},d))}}function cS(h,l,d){d[h]&&d[h].indexOf(l)!==-1||(d[h]=d[h]||[],d[h].push(l))}function Of(h,l,d){if(d&&d[h]){const p=d[h].indexOf(l);p!==-1&&d[h].splice(p,1)}}class qp{on(l,d){return this._listeners=this._listeners||{},cS(l,d,this._listeners),this}off(l,d){return Of(l,d,this._listeners),Of(l,d,this._oneTimeListeners),this}once(l,d){return d?(this._oneTimeListeners=this._oneTimeListeners||{},cS(l,d,this._oneTimeListeners),this):new Promise(p=>{this.once(l,p)})}fire(l,d){const p=typeof l=="string"?new Pd(l,d):l,y=p.type;if(this.listens(y)){p.target=this;const b=this._listeners&&this._listeners[y]?this._listeners[y].slice():[];for(const M of b)M.call(this,p);const w=this._oneTimeListeners&&this._oneTimeListeners[y]?this._oneTimeListeners[y].slice():[];for(const M of w)Of(y,M,this._oneTimeListeners),M.call(this,p);const k=this._eventedParent;if(k){const M=typeof this._eventedParentData=="function"?this._eventedParentData():this._eventedParentData;Object.assign(p,M),k.fire(p)}}else p instanceof Lx&&console.error(p.error);return this}listens(l){return!!(this._listeners&&this._listeners[l]&&this._listeners[l].length>0||this._oneTimeListeners&&this._oneTimeListeners[l]&&this._oneTimeListeners[l].length>0||this._eventedParent&&this._eventedParent.listens(l))}setEventedParent(l,d){return this._eventedParent=l,this._eventedParentData=d,this}}class vl{constructor(l){typeof l=="string"?this.name=l:(this.name=l.name,this.iconsetId=l.iconsetId)}static from(l){return new vl(l)}static toString(l){return l.iconsetId?`${l.name}${l.iconsetId}`:l.name}static parse(l){const[d,p]=l.split("");return new vl({name:d,iconsetId:p})}static isEqual(l,d){return l.name===d.name&&l.iconsetId===d.iconsetId}toString(){return vl.toString(this)}serialize(){return{name:this.name,iconsetId:this.iconsetId}}}var w0,Fx={},xu=function(){if(w0)return Fx;w0=1;var h={transparent:[0,0,0,0],aliceblue:[240,248,255,1],antiquewhite:[250,235,215,1],aqua:[0,255,255,1],aquamarine:[127,255,212,1],azure:[240,255,255,1],beige:[245,245,220,1],bisque:[255,228,196,1],black:[0,0,0,1],blanchedalmond:[255,235,205,1],blue:[0,0,255,1],blueviolet:[138,43,226,1],brown:[165,42,42,1],burlywood:[222,184,135,1],cadetblue:[95,158,160,1],chartreuse:[127,255,0,1],chocolate:[210,105,30,1],coral:[255,127,80,1],cornflowerblue:[100,149,237,1],cornsilk:[255,248,220,1],crimson:[220,20,60,1],cyan:[0,255,255,1],darkblue:[0,0,139,1],darkcyan:[0,139,139,1],darkgoldenrod:[184,134,11,1],darkgray:[169,169,169,1],darkgreen:[0,100,0,1],darkgrey:[169,169,169,1],darkkhaki:[189,183,107,1],darkmagenta:[139,0,139,1],darkolivegreen:[85,107,47,1],darkorange:[255,140,0,1],darkorchid:[153,50,204,1],darkred:[139,0,0,1],darksalmon:[233,150,122,1],darkseagreen:[143,188,143,1],darkslateblue:[72,61,139,1],darkslategray:[47,79,79,1],darkslategrey:[47,79,79,1],darkturquoise:[0,206,209,1],darkviolet:[148,0,211,1],deeppink:[255,20,147,1],deepskyblue:[0,191,255,1],dimgray:[105,105,105,1],dimgrey:[105,105,105,1],dodgerblue:[30,144,255,1],firebrick:[178,34,34,1],floralwhite:[255,250,240,1],forestgreen:[34,139,34,1],fuchsia:[255,0,255,1],gainsboro:[220,220,220,1],ghostwhite:[248,248,255,1],gold:[255,215,0,1],goldenrod:[218,165,32,1],gray:[128,128,128,1],green:[0,128,0,1],greenyellow:[173,255,47,1],grey:[128,128,128,1],honeydew:[240,255,240,1],hotpink:[255,105,180,1],indianred:[205,92,92,1],indigo:[75,0,130,1],ivory:[255,255,240,1],khaki:[240,230,140,1],lavender:[230,230,250,1],lavenderblush:[255,240,245,1],lawngreen:[124,252,0,1],lemonchiffon:[255,250,205,1],lightblue:[173,216,230,1],lightcoral:[240,128,128,1],lightcyan:[224,255,255,1],lightgoldenrodyellow:[250,250,210,1],lightgray:[211,211,211,1],lightgreen:[144,238,144,1],lightgrey:[211,211,211,1],lightpink:[255,182,193,1],lightsalmon:[255,160,122,1],lightseagreen:[32,178,170,1],lightskyblue:[135,206,250,1],lightslategray:[119,136,153,1],lightslategrey:[119,136,153,1],lightsteelblue:[176,196,222,1],lightyellow:[255,255,224,1],lime:[0,255,0,1],limegreen:[50,205,50,1],linen:[250,240,230,1],magenta:[255,0,255,1],maroon:[128,0,0,1],mediumaquamarine:[102,205,170,1],mediumblue:[0,0,205,1],mediumorchid:[186,85,211,1],mediumpurple:[147,112,219,1],mediumseagreen:[60,179,113,1],mediumslateblue:[123,104,238,1],mediumspringgreen:[0,250,154,1],mediumturquoise:[72,209,204,1],mediumvioletred:[199,21,133,1],midnightblue:[25,25,112,1],mintcream:[245,255,250,1],mistyrose:[255,228,225,1],moccasin:[255,228,181,1],navajowhite:[255,222,173,1],navy:[0,0,128,1],oldlace:[253,245,230,1],olive:[128,128,0,1],olivedrab:[107,142,35,1],orange:[255,165,0,1],orangered:[255,69,0,1],orchid:[218,112,214,1],palegoldenrod:[238,232,170,1],palegreen:[152,251,152,1],paleturquoise:[175,238,238,1],palevioletred:[219,112,147,1],papayawhip:[255,239,213,1],peachpuff:[255,218,185,1],peru:[205,133,63,1],pink:[255,192,203,1],plum:[221,160,221,1],powderblue:[176,224,230,1],purple:[128,0,128,1],rebeccapurple:[102,51,153,1],red:[255,0,0,1],rosybrown:[188,143,143,1],royalblue:[65,105,225,1],saddlebrown:[139,69,19,1],salmon:[250,128,114,1],sandybrown:[244,164,96,1],seagreen:[46,139,87,1],seashell:[255,245,238,1],sienna:[160,82,45,1],silver:[192,192,192,1],skyblue:[135,206,235,1],slateblue:[106,90,205,1],slategray:[112,128,144,1],slategrey:[112,128,144,1],snow:[255,250,250,1],springgreen:[0,255,127,1],steelblue:[70,130,180,1],tan:[210,180,140,1],teal:[0,128,128,1],thistle:[216,191,216,1],tomato:[255,99,71,1],turquoise:[64,224,208,1],violet:[238,130,238,1],wheat:[245,222,179,1],white:[255,255,255,1],whitesmoke:[245,245,245,1],yellow:[255,255,0,1],yellowgreen:[154,205,50,1]};function l(b){return(b=Math.round(b))<0?0:b>255?255:b}function d(b){return l(b[b.length-1]==="%"?parseFloat(b)/100*255:parseInt(b))}function p(b){return(w=b[b.length-1]==="%"?parseFloat(b)/100:parseFloat(b))<0?0:w>1?1:w;var w}function y(b,w,k){return k<0?k+=1:k>1&&(k-=1),6*k<1?b+(w-b)*k*6:2*k<1?w:3*k<2?b+(w-b)*(2/3-k)*6:b}try{Fx.parseCSSColor=function(b){var w,k=b.replace(/ /g,"").toLowerCase();if(k in h)return h[k].slice();if(k[0]==="#")return k.length===4?(w=parseInt(k.substr(1),16))>=0&&w<=4095?[(3840&w)>>4|(3840&w)>>8,240&w|(240&w)>>4,15&w|(15&w)<<4,1]:null:k.length===7&&(w=parseInt(k.substr(1),16))>=0&&w<=16777215?[(16711680&w)>>16,(65280&w)>>8,255&w,1]:null;var M=k.indexOf("("),F=k.indexOf(")");if(M!==-1&&F+1===k.length){var $=k.substr(0,M),U=k.substr(M+1,F-(M+1)).split(","),H=1;switch($){case"rgba":if(U.length!==4)return null;H=p(U.pop());case"rgb":return U.length!==3?null:[d(U[0]),d(U[1]),d(U[2]),H];case"hsla":if(U.length!==4)return null;H=p(U.pop());case"hsl":if(U.length!==3)return null;var Z=(parseFloat(U[0])%360+360)%360/360,Y=p(U[1]),ne=p(U[2]),ce=ne<=.5?ne*(Y+1):ne+Y-ne*Y,le=2*ne-ce;return[l(255*y(le,ce,Z+1/3)),l(255*y(le,ce,Z)),l(255*y(le,ce,Z-1/3)),H];default:return null}}return null}}catch{}return Fx}();class Us{constructor(l,d,p,y=1){this.r=l,this.g=d,this.b=p,this.a=y}static parse(l){if(!l)return;if(l instanceof Us)return l;if(typeof l!="string")return;const d=xu.parseCSSColor(l);return d?new Us(d[0]/255,d[1]/255,d[2]/255,d[3]):void 0}toString(){const[l,d,p,y]=[this.r,this.g,this.b,this.a];return`rgba(${Math.round(255*l)},${Math.round(255*d)},${Math.round(255*p)},${y})`}toNonPremultipliedRenderColor(l){const{r:d,g:p,b:y,a:b}=this;return new rE(l,d,p,y,b)}toPremultipliedRenderColor(l){const{r:d,g:p,b:y,a:b}=this;return new nE(l,d*b,p*b,y*b,b)}clone(){return new Us(this.r,this.g,this.b,this.a)}}class tE{constructor(l,d,p,y,b,w=!1){if(this.premultiplied=!1,this.premultiplied=w,l){const k=l.image.height,M=k*k;this.premultiplied?(d=b===0?0:d/b*(k-1),p=b===0?0:p/b*(k-1),y=b===0?0:y/b*(k-1)):(d*=k-1,p*=k-1,y*=k-1);const F=Math.floor(d),$=Math.floor(p),U=Math.floor(y),H=Math.ceil(d),Z=Math.ceil(p),Y=Math.ceil(y),ne=d-F,ce=p-$,le=y-U,ye=l.image.data,we=4*(F+$*M+U*k),Ee=4*(F+$*M+Y*k),Ue=4*(F+Z*M+U*k),Le=4*(F+Z*M+Y*k),Ke=4*(H+$*M+U*k),Je=4*(H+$*M+Y*k),it=4*(H+Z*M+U*k),Pt=4*(H+Z*M+Y*k);if(we<0||Pt>=ye.length)throw new Error("out of range");this.r=fn(fn(fn(ye[we],ye[Ee],le),fn(ye[Ue],ye[Le],le),ce),fn(fn(ye[Ke],ye[Je],le),fn(ye[it],ye[Pt],le),ce),ne)/255*(this.premultiplied?b:1),this.g=fn(fn(fn(ye[we+1],ye[Ee+1],le),fn(ye[Ue+1],ye[Le+1],le),ce),fn(fn(ye[Ke+1],ye[Je+1],le),fn(ye[it+1],ye[Pt+1],le),ce),ne)/255*(this.premultiplied?b:1),this.b=fn(fn(fn(ye[we+2],ye[Ee+2],le),fn(ye[Ue+2],ye[Le+2],le),ce),fn(fn(ye[Ke+2],ye[Je+2],le),fn(ye[it+2],ye[Pt+2],le),ce),ne)/255*(this.premultiplied?b:1),this.a=b}else this.r=d,this.g=p,this.b=y,this.a=b}toArray(){const{r:l,g:d,b:p,a:y}=this;return[255*l,255*d,255*p,y]}toHslaArray(){let{r:l,g:d,b:p,a:y}=this;if(this.premultiplied){if(y===0)return[0,0,0,0];const Y=1/y;l*=Y,d*=Y,p*=Y}const b=Math.min(Math.max(l,0),1),w=Math.min(Math.max(d,0),1),k=Math.min(Math.max(p,0),1),M=Math.min(b,w,k),F=Math.max(b,w,k),$=F-M,U=.5*(M+F);if($===0)return[0,0,100*U,y];const H=U>.5?$/(2-F-M):$/(F+M);let Z;switch(F){case b:Z=60*((w-k)/$+(wfn(p,l[y],d))}Us.black=new Us(0,0,0,1),Us.white=new Us(1,1,1,1),Us.transparent=new Us(0,0,0,0),Us.red=new Us(1,0,0,1),Us.blue=new Us(0,0,1,1);var zx=Object.freeze({__proto__:null,array:uS,color:function(h,l,d){return new Us(fn(h.r,l.r,d),fn(h.g,l.g,d),fn(h.b,l.b,d),fn(h.a,l.a,d))},number:fn});class vu extends Error{constructor(l,d){super(d),this.message=d,this.key=l}}class fg{constructor(l,d=[]){this.parent=l,this.bindings={};for(const[p,y]of d)this.bindings[p]=y}concat(l){return new fg(this,l)}get(l){if(this.bindings[l])return this.bindings[l];if(this.parent)return this.parent.get(l);throw new Error(`${l} not found in scope.`)}has(l){return!!this.bindings[l]||!!this.parent&&this.parent.has(l)}}const Zu={kind:"null"},Zr={kind:"number"},fs={kind:"string"},Zs={kind:"boolean"},sc={kind:"color"},Id={kind:"object"},$s={kind:"value"},j0={kind:"collator"},Bx={kind:"formatted"},$x={kind:"resolvedImage"};function tl(h,l){return{kind:"array",itemType:h,N:l}}function Ta(h){if(h.kind==="array"){const l=Ta(h.itemType);return typeof h.N=="number"?`array<${l}, ${h.N}>`:h.itemType.kind==="value"?"array":`array<${l}>`}return h.kind}const a4=[Zu,Zr,fs,Zs,sc,Bx,Id,tl($s),$x];function Rf(h,l){if(l.kind==="error")return null;if(h.kind==="array"){if(l.kind==="array"&&(l.N===0&&l.itemType.kind==="value"||!Rf(h.itemType,l.itemType))&&(typeof h.N!="number"||h.N===l.N))return null}else{if(h.kind===l.kind)return null;if(h.kind==="value"){for(const d of a4)if(!Rf(d,l))return null}}return`Expected ${Ta(h)} but found ${Ta(l)} instead.`}function dS(h,l){return l.some(d=>d.kind===h.kind)}function Ux(h,l){return l.some(d=>d==="null"?h===null:d==="array"?Array.isArray(h):d==="object"?h&&!Array.isArray(h)&&typeof h=="object":d===typeof h)}function S0(h,l){return h.kind==="array"&&l.kind==="array"?h.N===l.N&&S0(h.itemType,l.itemType):h.kind===l.kind}class hS{constructor(l,d,p){this.sensitivity=l?d?"variant":"case":d?"accent":"base",this.locale=p,this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:"search"})}compare(l,d){return this.collator.compare(l,d)}resolvedLocale(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale}}class N0{constructor(l,d,p,y,b){this.text=l.normalize?l.normalize():l,this.image=d,this.scale=p,this.fontStack=y,this.textColor=b}}class Il{constructor(l){this.sections=l}static fromString(l){return new Il([new N0(l,null,null,null,null)])}isEmpty(){return this.sections.length===0||!this.sections.some(l=>l.text.length!==0||!!l.image&&l.image.hasPrimary())}static factory(l){return l instanceof Il?l:Il.fromString(l)}toString(){return this.sections.length===0?"":this.sections.map(l=>l.text).join("")}serialize(){const l=["format"];for(const d of this.sections){if(d.image){const y=d.image.getPrimary().id.toString();l.push(["image",y]);continue}l.push(d.text);const p={};d.fontStack&&(p["text-font"]=["literal",d.fontStack.split(",")]),d.scale&&(p["font-scale"]=d.scale),d.textColor&&(p["text-color"]=["rgba"].concat(d.textColor.toNonPremultipliedRenderColor(null).toArray())),l.push(p)}return l}}class Nh{constructor(l,d={}){this.id=vl.from(l),this.params=d.params,this.sx=d.sx||1,this.sy=d.sy||1}toString(){return JSON.stringify(this)}static parse(l){let d,p,y,b;try{({id:d,params:p,sx:y,sy:b}=JSON.parse(l)||{})}catch{return null}return d?new Nh(d,{params:p,sx:y,sy:b}):null}scaleSelf(l,d=l){return this.sx*=l,this.sy*=d,this}}class Ml{constructor(l,d,p,y,b=!1){this.primaryId=vl.from(l),this.primaryOptions=d,p&&(this.secondaryId=vl.from(p)),this.secondaryOptions=y,this.available=b}toString(){return this.primaryId&&this.secondaryId?`[${this.primaryId.name},${this.secondaryId.name}]`:this.primaryId.name}hasPrimary(){return!!this.primaryId}getPrimary(){return new Nh(this.primaryId,this.primaryOptions)}hasSecondary(){return!!this.secondaryId}getSecondary(){return this.secondaryId?new Nh(this.secondaryId,this.secondaryOptions):null}static from(l){return typeof l=="string"?Ml.build({name:l}):l}static build(l,d,p,y){return!l||typeof l=="object"&&!("name"in l)?null:new Ml(l,p,d,y)}}function Hp(h,l,d,p){return typeof h=="number"&&h>=0&&h<=255&&typeof l=="number"&&l>=0&&l<=255&&typeof d=="number"&&d>=0&&d<=255?p===void 0||typeof p=="number"&&p>=0&&p<=1?null:`Invalid rgba value [${[h,l,d,p].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid rgba value [${(typeof p=="number"?[h,l,d,p]:[h,l,d]).join(", ")}]: 'r', 'g', and 'b' must be between 0 and 255.`}function pg(h){if(h===null||typeof h=="string"||typeof h=="boolean"||typeof h=="number"||h instanceof Us||h instanceof hS||h instanceof Il||h instanceof Ml)return!0;if(Array.isArray(h)){for(const l of h)if(!pg(l))return!1;return!0}if(typeof h=="object"){for(const l in h)if(!pg(h[l]))return!1;return!0}return!1}function co(h){if(h===null)return Zu;if(typeof h=="string")return fs;if(typeof h=="boolean")return Zs;if(typeof h=="number")return Zr;if(h instanceof Us)return sc;if(h instanceof hS)return j0;if(h instanceof Il)return Bx;if(h instanceof Ml)return $x;if(Array.isArray(h)){const l=h.length;let d;for(const p of h){const y=co(p);if(d){if(d===y)continue;d=$s;break}d=y}return tl(d||$s,l)}return Id}function _u(h){const l=typeof h;return h===null?"":l==="string"||l==="number"||l==="boolean"?String(h):h instanceof Il||h instanceof Ml||h instanceof Us?h.toString():JSON.stringify(h)}class Ch{constructor(l,d){this.type=l,this.value=d}static parse(l,d){if(l.length!==2)return d.error(`'literal' expression requires exactly one argument, but found ${l.length-1} instead.`);if(!pg(l[1]))return d.error("invalid value");const p=l[1];let y=co(p);const b=d.expectedType;return y.kind!=="array"||y.N!==0||!b||b.kind!=="array"||typeof b.N=="number"&&b.N!==0||(y=b),new Ch(y,p)}evaluate(){return this.value}eachChild(){}outputDefined(){return!0}serialize(){return this.type.kind==="array"||this.type.kind==="object"?["literal",this.value]:this.value instanceof Us?["rgba"].concat(this.value.toNonPremultipliedRenderColor(null).toArray()):this.value instanceof Il?this.value.serialize():this.value}}class Ya{constructor(l){this.name="ExpressionEvaluationError",this.message=l}toJSON(){return this.message}}const fS={string:fs,number:Zr,boolean:Zs,object:Id};class Yu{constructor(l,d){this.type=l,this.args=d}static parse(l,d){if(l.length<2)return d.error("Expected at least one argument.");let p,y=1;const b=l[0];if(b==="array"){let k,M;if(l.length>2){const F=l[1];if(typeof F!="string"||!(F in fS)||F==="object")return d.error('The item type argument of "array" must be one of string, number, boolean',1);k=fS[F],y++}else k=$s;if(l.length>3){if(l[2]!==null&&(typeof l[2]!="number"||l[2]<0||l[2]!==Math.floor(l[2])))return d.error('The length argument to "array" must be a positive integer literal',2);M=l[2],y++}p=tl(k,M)}else p=fS[b];const w=[];for(;yl.outputDefined())}serialize(){const l=this.type,d=[l.kind];if(l.kind==="array"){const p=l.itemType;if(p.kind==="string"||p.kind==="number"||p.kind==="boolean"){d.push(p.kind);const y=l.N;(typeof y=="number"||this.args.length>1)&&d.push(y)}}return d.concat(this.args.map(p=>p.serialize()))}}class Md{constructor(l){this.type=Bx,this.sections=l}static parse(l,d){if(l.length<2)return d.error("Expected at least one argument.");const p=l[1];if(!Array.isArray(p)&&typeof p=="object")return d.error("First argument must be an image or text section.");const y=[];let b=!1;for(let w=1;w<=l.length-1;++w){const k=l[w];if(b&&typeof k=="object"&&!Array.isArray(k)){b=!1;let M=null;if(k["font-scale"]&&(M=d.parseObjectValue(k["font-scale"],w,"font-scale",Zr),!M))return null;let F=null;if(k["text-font"]&&(F=d.parseObjectValue(k["text-font"],w,"text-font",tl(fs)),!F))return null;let $=null;if(k["text-color"]&&($=d.parseObjectValue(k["text-color"],w,"text-color",sc),!$))return null;const U=y[y.length-1];U.scale=M,U.font=F,U.textColor=$}else{const M=d.parse(l[w],w,$s);if(!M)return null;const F=M.type.kind;if(F!=="string"&&F!=="value"&&F!=="null"&&F!=="resolvedImage")return d.error("Formatted text type must be 'string', 'value', 'image' or 'null'.");b=!0,y.push({content:M,scale:null,font:null,textColor:null})}}return new Md(y)}evaluate(l){return new Il(this.sections.map(d=>{const p=d.content.evaluate(l);return S0(co(p),$x)?new N0("",p,null,null,null):new N0(_u(p),null,d.scale?d.scale.evaluate(l):null,d.font?d.font.evaluate(l).join(","):null,d.textColor?d.textColor.evaluate(l):null)}))}eachChild(l){for(const d of this.sections)l(d.content),d.scale&&l(d.scale),d.font&&l(d.font),d.textColor&&l(d.textColor)}outputDefined(){return!1}serialize(){const l=["format"];for(const d of this.sections){l.push(d.content.serialize());const p={};d.scale&&(p["font-scale"]=d.scale.serialize()),d.font&&(p["text-font"]=d.font.serialize()),d.textColor&&(p["text-color"]=d.textColor.serialize()),l.push(p)}return l}}class En{constructor(l,d,p,y){this._imageWarnHistory={},this.type=$x,this.namePrimary=l,this.nameSecondary=d,p&&(this.paramsPrimary=p.params,this.iconsetIdPrimary=p.iconset?p.iconset.id:void 0),y&&(this.paramsSecondary=y.params,this.iconsetIdSecondary=y.iconset?y.iconset.id:void 0)}static parse(l,d){if(l.length<2)return d.error("Expected two or more arguments.");let p=1;const y=[];function b(){if(pvl.isEqual(w,b)),y.available){const w=y.getSecondary()?y.getSecondary().id:null;w&&(y.available=l.availableImages.some(k=>vl.isEqual(k,w)))}}return y}eachChild(l){if(l(this.namePrimary),this.paramsPrimary)for(const d in this.paramsPrimary)this.paramsPrimary[d]&&l(this.paramsPrimary[d]);if(this.nameSecondary&&(l(this.nameSecondary),this.paramsSecondary))for(const d in this.paramsSecondary)this.paramsSecondary[d]&&l(this.paramsSecondary[d])}outputDefined(){return!1}serializeOptions(l,d){const p={};if(d&&(p.iconset={id:d}),l){p.params={};for(const y in l)l[y]&&(p.params[y]=l[y].serialize())}return Object.keys(p).length>0?p:void 0}serialize(){const l=["image",this.namePrimary.serialize()];if(this.paramsPrimary||this.iconsetIdPrimary){const d=this.serializeOptions(this.paramsPrimary,this.iconsetIdPrimary);d&&l.push(d)}if(this.nameSecondary&&(l.push(this.nameSecondary.serialize()),this.paramsSecondary||this.iconsetIdSecondary)){const d=this.serializeOptions(this.paramsSecondary,this.iconsetIdSecondary);d&&l.push(d)}return l}}function Wr(h){return _n(h)?"string":mg(h)?"number":k0(h)?"boolean":Array.isArray(h)?"array":h===null?"null":C0(h)?"object":typeof h}function C0(h){return h!=null&&!Array.isArray(h)&&typeof h!="function"&&!(h instanceof String||h instanceof Number||h instanceof Boolean)&&typeof h=="object"}function _n(h){return typeof h=="string"||h instanceof String}function mg(h){return typeof h=="number"||h instanceof Number}function k0(h){return typeof h=="boolean"||h instanceof Boolean}const vn={"to-boolean":Zs,"to-color":sc,"to-number":Zr,"to-string":fs};class Od{constructor(l,d){this.type=l,this.args=d}static parse(l,d){if(l.length<2)return d.error("Expected at least one argument.");const p=l[0],y=[];let b=Zu;if(p==="to-array"){if(!Array.isArray(l[1]))return null;const w=l[1].length;if(d.expectedType){if(d.expectedType.kind!=="array")return d.error(`Expected ${d.expectedType.kind} but found array.`);b=tl(d.expectedType.itemType,w)}else{if(!(w>0&&pg(l[1][0])))return null;b=tl(co(l[1][0]),w)}for(let k=0;k4?`Invalid rbga value ${JSON.stringify(d)}: expected an array containing either three or four numeric values.`:Hp(d[0],d[1],d[2],d[3]),!p))return new Us(d[0]/255,d[1]/255,d[2]/255,d[3])}throw new Ya(p||`Could not parse color from value '${typeof d=="string"?d:String(JSON.stringify(d))}'`)}if(this.type.kind==="number"){let d=null;for(const p of this.args){if(d=p.evaluate(l),d===null)return 0;const y=Number(d);if(!isNaN(y))return y}throw new Ya(`Could not convert ${JSON.stringify(d)} to number.`)}return this.type.kind==="formatted"?Il.fromString(_u(this.args[0].evaluate(l))):this.type.kind==="resolvedImage"?Ml.build(_u(this.args[0].evaluate(l))):this.type.kind==="array"?this.args.map(d=>d.evaluate(l)):_u(this.args[0].evaluate(l))}eachChild(l){this.args.forEach(l)}outputDefined(){return this.args.every(l=>l.outputDefined())}serialize(){if(this.type.kind==="formatted")return new Md([{content:this.args[0],scale:null,font:null,textColor:null}]).serialize();if(this.type.kind==="resolvedImage")return new En(this.args[0]).serialize();const l=this.type.kind==="array"?[]:[`to-${this.type.kind}`];return this.eachChild(d=>{l.push(d.serialize())}),l}}const pS=["Unknown","Point","LineString","Polygon"];class T0{constructor(l,d,p){this.globals=null,this.feature=null,this.featureState=null,this.formattedSection=null,this._parseColorCache={},this.availableImages=null,this.canonical=null,this.featureTileCoord=null,this.featureDistanceData=null,this.scope=l,this.options=d,this.iconImageUseTheme=p}id(){return this.feature&&this.feature.id!==void 0?this.feature.id:null}geometryType(){return this.feature?typeof this.feature.type=="number"?pS[this.feature.type]:this.feature.type:null}geometry(){return this.feature&&"geometry"in this.feature?this.feature.geometry:null}canonicalID(){return this.canonical}properties(){return this.feature&&this.feature.properties||{}}measureLight(l){return this.globals.brightness||0}distanceFromCenter(){if(this.featureTileCoord&&this.featureDistanceData){const l=this.featureDistanceData.center,d=this.featureDistanceData.scale,{x:p,y}=this.featureTileCoord;return this.featureDistanceData.bearing[0]*(p*d-l[0])+this.featureDistanceData.bearing[1]*(y*d-l[1])}return 0}parseColor(l){let d=this._parseColorCache[l];return d||(d=this._parseColorCache[l]=Us.parse(l)),d}getConfig(l){return this.options?this.options.get(l):null}}class Ol{constructor(l,d,p,y,b){this.name=l,this.type=d,this._evaluate=p,this.args=y,this._overloadIndex=b}evaluate(l){if(!this._evaluate){const d=Ol.definitions[this.name];this._evaluate=Array.isArray(d)?d[2]:d.overloads[this._overloadIndex][1]}return this._evaluate(l,this.args)}eachChild(l){this.args.forEach(l)}outputDefined(){return!1}serialize(){return[this.name].concat(this.args.map(l=>l.serialize()))}static parse(l,d){const p=l[0],y=Ol.definitions[p];if(!y)return d.error(`Unknown expression "${p}". If you wanted a literal array, use ["literal", [...]].`,0);const b=Array.isArray(y)?y[0]:y.type,w=Array.isArray(y)?[[y[1],y[2]]]:y.overloads,k=[];let M=null,F=-1;for(const[$,U]of w){if(Array.isArray($)&&$.length!==l.length-1)continue;k.push($),F++,M=new B0(d.registry,d.path,null,d.scope,void 0,d._scope,d.options,d.iconImageUseTheme);const H=[];let Z=!1;for(let Y=1;YH)).map(E0).join(" | "),U=[];for(let H=1;Hd;){if(p-d>600){const M=p-d+1,F=l-d+1,$=Math.log(M),U=.5*Math.exp(2*$/3),H=.5*Math.sqrt($*U*(M-U)/M)*(F-M/2<0?-1:1);A0(h,l,Math.max(d,Math.floor(l-F*U/M+H)),Math.min(p,Math.floor(l+(M-F)*U/M+H)),y)}const b=h[l];let w=d,k=p;for(Xu(h,d,l),y(h[p],b)>0&&Xu(h,d,p);w0;)k--}y(h[d],b)===0?Xu(h,d,k):(k++,Xu(h,k,p)),k<=l&&(d=k+1),l<=k&&(p=k-1)}}function Xu(h,l,d){const p=h[l];h[l]=h[d],h[d]=p}function mS(h,l){return hl?1:0}function Df(h){let l=0;for(let d,p,y=0,b=h.length,w=b-1;y=l[2]||h[1]<=l[1]||h[3]>=l[3])}function o4(h,l,d){const p=h[0]-l[0],y=h[1]-l[1],b=h[0]-d[0],w=h[1]-d[1];return p*w-b*y==0&&p*b<=0&&y*w<=0}function gg(h,l,d=!1){let p=!1;for(let k=0,M=l.length;k(y=h)[1]!=(w=Y)[1]>y[1]&&y[0]<(w[0]-b[0])*(y[1]-b[1])/(w[1]-b[1])+b[0]&&(p=!p)}}var y,b,w;return p}function qx(h,l,d,p){const y=p[0]-d[0],b=p[1]-d[1],w=(h[0]-d[0])*b-y*(h[1]-d[1]),k=(l[0]-d[0])*b-y*(l[1]-d[1]);return w>0&&k<0||w<0&&k>0}function Hx(h,l,d,p){return(y=[p[0]-d[0],p[1]-d[1]])[0]*(b=[l[0]-h[0],l[1]-h[1]])[1]-y[1]*b[0]!=0&&!(!qx(h,l,d,p)||!qx(d,p,h,l));var y,b}function kh(h){const l=new Wt(Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY),d=new Wt(Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY);for(const p of h[0])l.x>p.x&&(l.x=p.x),l.y>p.y&&(l.y=p.y),d.xd[2]){const y=.5*p;let b=h[0]-d[0]>y?-p:d[0]-h[0]>y?p:0;b===0&&(b=h[0]-d[2]>y?-p:d[2]-h[0]>y?p:0),h[0]+=b}bu(l,h)}function oE(h,l,d,p){const y=Math.pow(2,p.z)*Lf,b=[p.x*Lf,p.y*Lf],w=[];if(!h)return w;for(const k of h)for(const M of k){const F=[M.x+b[0],M.y+b[1]];aE(F,l,d,y),w.push(F)}return w}function P0(h,l,d,p){const y=Math.pow(2,p.z)*Lf,b=[p.x*Lf,p.y*Lf],w=[];if(!h)return w;for(const M of h){const F=[];for(const $ of M){const U=[$.x+b[0],$.y+b[1]];bu(l,U),F.push(U)}w.push(F)}if(l[2]-l[0]<=y/2){(k=l)[0]=k[1]=1/0,k[2]=k[3]=-1/0;for(const M of w)for(const F of M)aE(F,l,d,y)}var k;return w}class zf{constructor(l,d){this.type=Zs,this.geojson=l,this.geometries=d}static parse(l,d){if(l.length!==2)return d.error(`'within' expression requires exactly one argument, but found ${l.length-1} instead.`);if(pg(l[1])){const p=l[1];if(p.type==="FeatureCollection")for(let y=0;yd)return I0(b,w,(d-(p-k))/k)}return l[l.length-1]}pointToSegmentDistance(l,d,p){let[y,b]=d,w=$c(p[0]-y)*this.kx,k=(p[1]-b)*this.ky;if(w!==0||k!==0){const M=($c(l[0]-y)*this.kx*w+(l[1]-b)*this.ky*k)/(w*w+k*k);M>1?(y=p[0],b=p[1]):M>0&&(y+=w/this.kx*M,b+=k/this.ky*M)}return w=$c(l[0]-y)*this.kx,k=(l[1]-b)*this.ky,Math.sqrt(w*w+k*k)}pointOnLine(l,d){let p=1/0,y=l[0][0],b=l[0][1],w=0,k=0;for(let M=0;M1?(F=l[M+1][0],$=l[M+1][1]):Z>0&&(F+=U/this.kx*Z,$+=H/this.ky*Z)),U=$c(d[0]-F)*this.kx,H=(d[1]-$)*this.ky;const Y=U*U+H*H;Yb.index||y.index===b.index&&y.t>b.t){const F=y;y=b,b=F}const w=[y.point],k=y.index+1,M=b.index;!xS(p[k],w[0])&&k<=M&&w.push(p[k]);for(let F=k+1;F<=M;F++)w.push(p[F]);return xS(p[M],b.point)||w.push(b.point),w}lineSliceAlong(l,d,p){let y=0;const b=[];for(let w=0;wl&&b.length===0&&b.push(I0(k,M,(l-(y-F))/F)),y>=d)return b.push(I0(k,M,(d-(y-F))/F)),b;y>l&&b.push(M)}return b}bufferPoint(l,d){const p=d/this.ky,y=d/this.kx;return[l[0]-y,l[1]-p,l[0]+y,l[1]+p]}bufferBBox(l,d){const p=d/this.ky,y=d/this.kx;return[l[0]-y,l[1]-p,l[2]+y,l[3]+p]}insideBBox(l,d){return $c(l[0]-d[0])>=0&&$c(l[0]-d[2])<=0&&l[1]>=d[1]&&l[1]<=d[3]}}function xS(h,l){return h[0]===l[0]&&h[1]===l[1]}function I0(h,l,d){const p=$c(l[0]-h[0]);return[h[0]+p*d,h[1]+(l[1]-h[1])*d]}function $c(h){for(;h<-180;)h+=360;for(;h>180;)h-=360;return h}class M0{constructor(l=[],d=(p,y)=>py?1:0){if(this.data=l,this.length=this.data.length,this.compare=d,this.length>0)for(let p=(this.length>>1)-1;p>=0;p--)this._down(p)}push(l){this.data.push(l),this._up(this.length++)}pop(){if(this.length===0)return;const l=this.data[0],d=this.data.pop();return--this.length>0&&(this.data[0]=d,this._down(0)),l}peek(){return this.data[0]}_up(l){const{data:d,compare:p}=this,y=d[l];for(;l>0;){const b=l-1>>1,w=d[b];if(p(y,w)>=0)break;d[l]=w,l=b}d[l]=y}_down(l){const{data:d,compare:p}=this,y=this.length>>1,b=d[l];for(;l=0)break;d[l]=d[w],l=w}d[l]=b}}var mr=8192;function vS(h,l){return l.dist-h.dist}const O0=100,R0=50;function _S(h){const l=[1/0,1/0,-1/0,-1/0];if(l.length!==h.length)return!1;for(let d=0;d=h[0]&&h[1]h[1])return[null,null];const d=Gx(h);if(l){if(d===2)return[h,null];const p=Math.floor(d/2);return[[h[0],h[0]+p],[h[0]+p,h[1]]]}{if(d===1)return[h,null];const p=Math.floor(d/2)-1;return[[h[0],h[0]+p],[h[0]+p+1,h[1]]]}}function Wp(h,l){const d=[1/0,1/0,-1/0,-1/0];if(!Rd(l,h.length))return d;for(let p=l[0];p<=l[1];++p)bu(d,h[p]);return d}function Gp(h){const l=[1/0,1/0,-1/0,-1/0];for(let d=0;dl[2]&&(p=h[0]-l[2]),h[1]>l[3]&&(y=h[1]-l[3]),h[3]=p)return p;if(Vx(y,b)){if(jS(h,l))return 0}else if(jS(l,h))return 0;let w=p;for(const k of h)for(let M=0,F=k.length,$=F-1;M=b)continue;const $=F.range1;if(Gx($)<=k){if(!Rd($,h.length))return NaN;if(l){const U=f4(h,$,d,p);if((b=Math.min(b,U))===0)return b}else for(let U=$[0];U<=$[1];++U){const H=h4(h[U],d,p);if((b=Math.min(b,H))===0)return b}}else{const U=bS($,l);if(U[0]!==null){const H=Bf(Wp(h,U[0]),M,p);H=w)continue;const U=$.range1,H=$.range2;if(Gx(U)<=M&&Gx(H)<=F){if(!Rd(U,h.length)||!Rd(H,d.length))return NaN;if(l&&p?w=Math.min(w,ps(h,U,d,H,y)):l||p?l&&!p?w=Math.min(w,wS(d,H,h,U,y)):!l&&p&&(w=Math.min(w,wS(h,U,d,H,y))):w=Math.min(w,d4(h,U,d,H,y)),w===0)return w}else{const Z=bS(U,l),Y=bS(H,p);Ui(k,w,y,h,d,Z[0],Y[0]),Ui(k,w,y,h,d,Z[0],Y[1]),Ui(k,w,y,h,d,Z[1],Y[0]),Ui(k,w,y,h,d,Z[1],Y[1])}}return w}function SS(h,l,d,p,y=1/0){let b=y;const w=Wp(h,[0,h.length-1]);for(const k of d)if(!(b!==1/0&&Bf(w,Wp(k,[0,k.length-1]),p)>=b)&&(b=Math.min(b,dE(h,l,k,!0,p,b)),b===0))return b;return b}function F0(h,l,d,p,y=1/0){let b=y;const w=Wp(h,[0,h.length-1]);for(const k of d){if(b!==1/0&&Bf(w,Gp(k),p)>=b)continue;const M=m4(h,l,k,p,b);if(isNaN(M))return M;if((b=Math.min(b,M))===0)return b}return b}function NS(h){return h==="Point"||h==="MultiPoint"||h==="LineString"||h==="MultiLineString"||h==="Polygon"||h==="MultiPolygon"}class Kp{constructor(l,d){this.type=Zr,this.geojson=l,this.geometries=d}static parse(l,d){if(l.length!==2)return d.error(`'distance' expression requires either one argument, but found ' ${l.length-1} instead.`);if(pg(l[1])){const p=l[1];if(p.type==="FeatureCollection"){for(let y=0;y{l&&!vg(d)&&(l=!1)}),l}function Kx(h){if(h instanceof Ol&&h.name==="feature-state")return!1;let l=!0;return h.eachChild(d=>{l&&!Kx(d)&&(l=!1)}),l}function _g(h,l){if(h instanceof Ol&&l.indexOf(h.name)>=0)return!1;let d=!0;return h.eachChild(p=>{d&&!_g(p,l)&&(d=!1)}),d}function hE(h,l,d){return[h,l,d].filter(Boolean).join("")}function CS(h,l){switch(h){case"string":return _u(l);case"number":return+l;case"boolean":return!!l;case"color":return Us.parse(l);case"formatted":return Il.fromString(_u(l));case"resolvedImage":return Ml.build(_u(l))}return l}function fE(h,l,d,p){return p!==void 0&&(h=p*Math.round(h/p)),l!==void 0&&hd&&(h=d),h}class bg{constructor(l,d,p,y=!1){this.type=l,this.key=d,this.scope=p,this.featureConstant=y}static parse(l,d){let p=d.expectedType;if(p==null&&(p=$s),l.length<2||l.length>3)return d.error("Invalid number of arguments for 'config' expression.");const y=d.parse(l[1],1);if(!(y instanceof Ch))return d.error("Key name of 'config' expression must be a string literal.");let b,w=!0;const k=_u(y.value);if(l.length>=3){const M=d.parse(l[2],2);if(!(M instanceof Ch))return d.error("Scope of 'config' expression must be a string literal.");b=_u(M.value)}if(d.options){const M=hE(k,b,d._scope),F=d.options.get(M);F&&(w=vg(F.value||F.default))}return new bg(p,k,b,w)}evaluate(l){const d=hE(this.key,this.scope,l.scope),p=l.getConfig(d);if(!p)return null;const{type:y,value:b,values:w,minValue:k,maxValue:M,stepValue:F}=p,$=p.default.evaluate(l);let U=$;if(b){const H=l.scope;l.scope=(H||"").split("").slice(1).join(""),U=b.evaluate(l),l.scope=H}return y&&(U=CS(y,U)),U===void 0||k===void 0&&M===void 0&&F===void 0||(typeof U=="number"?U=fE(U,k,M,F):Array.isArray(U)&&(U=U.map(H=>typeof H=="number"?fE(H,k,M,F):H))),b!==void 0&&U!==void 0&&w&&!w.includes(U)&&(U=$,y&&(U=CS(y,U))),(y&&y!==this.type||U!==void 0&&!S0(co(U),this.type))&&(U=CS(this.type.kind,U)),U}eachChild(){}outputDefined(){return!1}serialize(){const l=["config",this.key];return this.scope&&l.concat(this.scope),l}}class z0{constructor(l,d){this.type=d.type,this.name=l,this.boundExpression=d}static parse(l,d){if(l.length!==2||typeof l[1]!="string")return d.error("'var' expression requires exactly one string literal argument.");const p=l[1];return d.scope.has(p)?new z0(p,d.scope.get(p)):d.error(`Unknown variable "${p}". Make sure "${p}" has been bound in an enclosing "let" expression before using it.`,1)}evaluate(l){return this.boundExpression.evaluate(l)}eachChild(){}outputDefined(){return!1}serialize(){return["var",this.name]}}class B0{constructor(l,d=[],p,y=new fg,b=[],w,k,M){this.registry=l,this.path=d,this.key=d.map(F=>typeof F=="string"?`['${F}']`:`[${F}]`).join(""),this.scope=y,this.errors=b,this.expectedType=p,this._scope=w,this.options=k,this.iconImageUseTheme=M}parse(l,d,p,y,b={}){return d||p?this.concat(d,null,p,y)._parse(l,b):this._parse(l,b)}parseObjectValue(l,d,p,y,b,w={}){return this.concat(d,p,y,b)._parse(l,w)}_parse(l,d){function p(y,b,w){return w==="assert"?new Yu(b,[y]):w==="coerce"?new Od(b,[y]):y}if(l!==null&&typeof l!="string"&&typeof l!="boolean"&&typeof l!="number"||(l=["literal",l]),Array.isArray(l)){if(l.length===0)return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');const y=typeof l[0]=="string"?this.registry[l[0]]:void 0;if(y){let b=y.parse(l,this);if(!b)return null;if(this.expectedType){const w=this.expectedType,k=b.type;if(w.kind!=="string"&&w.kind!=="number"&&w.kind!=="boolean"&&w.kind!=="object"&&w.kind!=="array"||k.kind!=="value")if(w.kind!=="color"&&w.kind!=="formatted"&&w.kind!=="resolvedImage"||k.kind!=="value"&&k.kind!=="string"){if(this.checkSubtype(w,k))return null}else b=p(b,w,d.typeAnnotation||"coerce");else b=p(b,w,d.typeAnnotation||"assert")}if(!(b instanceof Ch)&&b.type.kind!=="resolvedImage"&&kS(b)){const w=new T0(this._scope,this.options,this.iconImageUseTheme);try{b=new Ch(b.type,b.evaluate(w))}catch(k){return this.error(k.message),null}}return b}return Od.parse(["to-array",l],this)}return this.error(l===void 0?"'undefined' value invalid. Use null instead.":typeof l=="object"?'Bare objects invalid. Use ["literal", {...}] instead.':`Expected an array, but found ${typeof l} instead.`)}concat(l,d,p,y){let b=typeof l=="number"?this.path.concat(l):this.path;b=typeof d=="string"?b.concat(d):b;const w=y?this.scope.concat(y):this.scope;return new B0(this.registry,b,p||null,w,this.errors,this._scope,this.options,this.iconImageUseTheme)}error(l,...d){const p=`${this.key}${d.map(y=>`[${y}]`).join("")}`;this.errors.push(new vu(p,l))}checkSubtype(l,d){const p=Rf(l,d);return p&&this.error(p),p}}function kS(h){if(h instanceof z0)return kS(h.boundExpression);if(h instanceof Ol&&h.name==="error"||h instanceof _o||h instanceof zf||h instanceof Kp||h instanceof bg)return!1;const l=h instanceof Od||h instanceof Yu;let d=!0;return h.eachChild(p=>{d=l?d&&kS(p):d&&p instanceof Ch}),!!d&&vg(h)&&_g(h,["zoom","heatmap-density","worldview","line-progress","raster-value","sky-radial-progress","accumulated","is-supported-script","pitch","distance-from-center","measure-light","raster-particle-speed"])}function $0(h,l){const d=h.length-1;let p,y,b=0,w=d,k=0;for(;b<=w;)if(k=Math.floor((b+w)/2),p=h[k],y=h[k+1],p<=l){if(k===d||ll))throw new Ya("Input is not a number.");w=k-1}return 0}class Zx{constructor(l,d,p){this.type=l,this.input=d,this.labels=[],this.outputs=[];for(const[y,b]of p)this.labels.push(y),this.outputs.push(b)}static parse(l,d){if(l.length-1<4)return d.error(`Expected at least 4 arguments, but found only ${l.length-1}.`);if((l.length-1)%2!=0)return d.error("Expected an even number of arguments.");const p=d.parse(l[1],1,Zr);if(!p)return null;const y=[];let b=null;d.expectedType&&d.expectedType.kind!=="value"&&(b=d.expectedType);for(let w=1;w=k)return d.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',F);const U=d.parse(M,$,b);if(!U)return null;b=b||U.type,y.push([k,U])}return new Zx(b,p,y)}evaluate(l){const d=this.labels,p=this.outputs;if(d.length===1)return p[0].evaluate(l);const y=this.input.evaluate(l);if(y<=d[0])return p[0].evaluate(l);const b=d.length;return y>=d[b-1]?p[b-1].evaluate(l):p[$0(d,y)].evaluate(l)}eachChild(l){l(this.input);for(const d of this.outputs)l(d)}outputDefined(){return this.outputs.every(l=>l.outputDefined())}serialize(){const l=["step",this.input.serialize()];for(let d=0;d0&&l.push(this.labels[d]),l.push(this.outputs[d].serialize());return l}}const pE=.95047,mE=1.08883,gE=4/29,wg=6/29,yE=3*wg*wg,g4=wg*wg*wg,y4=Math.PI/180,x4=180/Math.PI;function TS(h){return h>g4?Math.pow(h,1/3):h/yE+gE}function ES(h){return h>wg?h*h*h:yE*(h-gE)}function AS(h){return 255*(h<=.0031308?12.92*h:1.055*Math.pow(h,1/2.4)-.055)}function PS(h){return(h/=255)<=.04045?h/12.92:Math.pow((h+.055)/1.055,2.4)}function xE(h){const l=PS(h.r),d=PS(h.g),p=PS(h.b),y=TS((.4124564*l+.3575761*d+.1804375*p)/pE),b=TS((.2126729*l+.7151522*d+.072175*p)/1);return{l:116*b-16,a:500*(y-b),b:200*(b-TS((.0193339*l+.119192*d+.9503041*p)/mE)),alpha:h.a}}function U0(h){let l=(h.l+16)/116,d=isNaN(h.a)?l:l+h.a/500,p=isNaN(h.b)?l:l-h.b/200;return l=1*ES(l),d=pE*ES(d),p=mE*ES(p),new Us(AS(3.2404542*d-1.5371385*l-.4985314*p),AS(-.969266*d+1.8760108*l+.041556*p),AS(.0556434*d-.2040259*l+1.0572252*p),h.alpha)}function V0(h,l,d){const p=l-h;return h+d*(p>180||p<-180?p-360*Math.round(p/360):p)}const jg={forward:xE,reverse:U0,interpolate:function(h,l,d){return{l:fn(h.l,l.l,d),a:fn(h.a,l.a,d),b:fn(h.b,l.b,d),alpha:fn(h.alpha,l.alpha,d)}}},Yx={forward:function(h){const{l,a:d,b:p}=xE(h),y=Math.atan2(p,d)*x4;return{h:y<0?y+360:y,c:Math.sqrt(d*d+p*p),l,alpha:h.a}},reverse:function(h){const l=h.h*y4,d=h.c;return U0({l:h.l,a:Math.cos(l)*d,b:Math.sin(l)*d,alpha:h.alpha})},interpolate:function(h,l,d){return{h:V0(h.h,l.h,d),c:fn(h.c,l.c,d),l:fn(h.l,l.l,d),alpha:fn(h.alpha,l.alpha,d)}}};var vE=Object.freeze({__proto__:null,hcl:Yx,lab:jg});class Uc{constructor(l,d,p,y,b){this.type=l,this.operator=d,this.interpolation=p,this.input=y,this.labels=[],this.outputs=[];for(const[w,k]of b)this.labels.push(w),this.outputs.push(k)}static interpolationFactor(l,d,p,y){let b=0;if(l.name==="exponential")b=q0(d,l.base,p,y);else if(l.name==="linear")b=q0(d,1,p,y);else if(l.name==="cubic-bezier"){const w=l.controlPoints;b=new yo(w[0],w[1],w[2],w[3]).solve(q0(d,1,p,y))}return b}static parse(l,d){let[p,y,b,...w]=l;if(!Array.isArray(y)||y.length===0)return d.error("Expected an interpolation type expression.",1);if(y[0]==="linear")y={name:"linear"};else if(y[0]==="exponential"){const F=y[1];if(typeof F!="number")return d.error("Exponential interpolation requires a numeric base.",1,1);y={name:"exponential",base:F}}else{if(y[0]!=="cubic-bezier")return d.error(`Unknown interpolation type ${String(y[0])}`,1,0);{const F=y.slice(1);if(F.length!==4||F.some($=>typeof $!="number"||$<0||$>1))return d.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);y={name:"cubic-bezier",controlPoints:F}}}if(l.length-1<4)return d.error(`Expected at least 4 arguments, but found only ${l.length-1}.`);if(l.length-1>3&&(l.length-1)%2!=0)return d.error("Expected an even number of arguments.");if(b=d.parse(b,2,Zr),!b)return null;const k=[];let M=null;p==="interpolate-hcl"||p==="interpolate-lab"?M=sc:d.expectedType&&d.expectedType.kind!=="value"&&(M=d.expectedType);for(let F=0;F=$)return d.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',H);const Y=d.parse(U,Z,M);if(!Y)return null;M=M||Y.type,k.push([$,Y])}return M.kind==="number"||M.kind==="color"||M.kind==="array"&&M.itemType.kind==="number"&&typeof M.N=="number"?new Uc(M,p,y,b,k):d.error(`Type ${Ta(M)} is not interpolatable.`)}evaluate(l){const d=this.labels,p=this.outputs;if(d.length===1)return p[0].evaluate(l);const y=this.input.evaluate(l);if(y<=d[0])return p[0].evaluate(l);const b=d.length;if(y>=d[b-1])return p[b-1].evaluate(l);const w=$0(d,y),k=Uc.interpolationFactor(this.interpolation,y,d[w],d[w+1]),M=p[w].evaluate(l),F=p[w+1].evaluate(l);return this.operator==="interpolate"?zx[this.type.kind.toLowerCase()](M,F,k):this.operator==="interpolate-hcl"?Yx.reverse(Yx.interpolate(Yx.forward(M),Yx.forward(F),k)):jg.reverse(jg.interpolate(jg.forward(M),jg.forward(F),k))}eachChild(l){l(this.input);for(const d of this.outputs)l(d)}outputDefined(){return this.outputs.every(l=>l.outputDefined())}serialize(){let l;l=this.interpolation.name==="linear"?["linear"]:this.interpolation.name==="exponential"?this.interpolation.base===1?["linear"]:["exponential",this.interpolation.base]:["cubic-bezier",...this.interpolation.controlPoints];const d=[this.operator,l,this.input.serialize()];for(let p=0;pRf(y,k.type));return new Xx(w?$s:p,b)}evaluate(l){let d,p=null,y=0;for(const b of this.args){if(y++,p=b.evaluate(l),p&&p instanceof Ml&&!p.available&&(d||(d=p),p=null,y===this.args.length))return d;if(p!==null)break}return p}eachChild(l){this.args.forEach(l)}outputDefined(){return this.args.every(l=>l.outputDefined())}serialize(){const l=["coalesce"];return this.eachChild(d=>{l.push(d.serialize())}),l}}class Th{constructor(l,d){this.type=d.type,this.bindings=[].concat(l),this.result=d}evaluate(l){return this.result.evaluate(l)}eachChild(l){for(const d of this.bindings)l(d[1]);l(this.result)}static parse(l,d){if(l.length<4)return d.error(`Expected at least 3 arguments, but found ${l.length-1} instead.`);const p=[];for(let b=1;b=p.length)throw new Ya("Array index out of bounds: index exceeds array size");if(d!==Math.floor(d))throw new Ya("Array index must be an integer. Use at-interpolated for fractional indices");return p[d]}eachChild(l){l(this.index),l(this.input)}outputDefined(){return!1}serialize(){return["at",this.index.serialize(),this.input.serialize()]}}class W0{constructor(l,d,p){this.type=l,this.index=d,this.input=p}static parse(l,d){if(l.length!==3)return d.error(`Expected 2 arguments, but found ${l.length-1} instead.`);const p=d.parse(l[1],1,Zr),y=d.parse(l[2],2,tl(d.expectedType||$s));return p&&y?new W0(y.type.itemType,p,y):null}evaluate(l){const d=this.index.evaluate(l),p=this.input.evaluate(l);if(d<0)throw new Ya(`Array index out of bounds: ${d} < 0.`);if(d>p.length-1)throw new Ya(`Array index out of bounds: ${d} > ${p.length-1}.`);if(d===Math.floor(d))return p[d];const y=Math.floor(d),b=Math.ceil(d),w=p[y],k=p[b];if(typeof w!="number"||typeof k!="number")throw new Ya(`Cannot interpolate between non-number values at index ${d}.`);const M=d-y;return w*(1-M)+k*M}eachChild(l){l(this.index),l(this.input)}outputDefined(){return!1}serialize(){return["at-interpolated",this.index.serialize(),this.input.serialize()]}}class IS{constructor(l,d){this.type=Zs,this.needle=l,this.haystack=d}static parse(l,d){if(l.length!==3)return d.error(`Expected 2 arguments, but found ${l.length-1} instead.`);const p=d.parse(l[1],1,$s),y=d.parse(l[2],2,$s);return p&&y?dS(p.type,[Zs,fs,Zr,Zu,$s])?new IS(p,y):d.error(`Expected first argument to be of type boolean, string, number or null, but found ${Ta(p.type)} instead`):null}evaluate(l){const d=this.needle.evaluate(l),p=this.haystack.evaluate(l);if(p==null)return!1;if(!Ux(d,["boolean","string","number","null"]))throw new Ya(`Expected first argument to be of type boolean, string, number or null, but found ${Ta(co(d))} instead.`);if(!Ux(p,["string","array"]))throw new Ya(`Expected second argument to be of type array or string, but found ${Ta(co(p))} instead.`);return p.indexOf(d)>=0}eachChild(l){l(this.needle),l(this.haystack)}outputDefined(){return!0}serialize(){return["in",this.needle.serialize(),this.haystack.serialize()]}}class Sg{constructor(l,d,p){this.type=Zr,this.needle=l,this.haystack=d,this.fromIndex=p}static parse(l,d){if(l.length<=2||l.length>=5)return d.error(`Expected 3 or 4 arguments, but found ${l.length-1} instead.`);const p=d.parse(l[1],1,$s),y=d.parse(l[2],2,$s);if(!p||!y)return null;if(!dS(p.type,[Zs,fs,Zr,Zu,$s]))return d.error(`Expected first argument to be of type boolean, string, number or null, but found ${Ta(p.type)} instead`);if(l.length===4){const b=d.parse(l[3],3,Zr);return b?new Sg(p,y,b):null}return new Sg(p,y)}evaluate(l){const d=this.needle.evaluate(l),p=this.haystack.evaluate(l);if(!Ux(d,["boolean","string","number","null"]))throw new Ya(`Expected first argument to be of type boolean, string, number or null, but found ${Ta(co(d))} instead.`);if(!Ux(p,["string","array"]))throw new Ya(`Expected second argument to be of type array or string, but found ${Ta(co(p))} instead.`);if(this.fromIndex){const y=this.fromIndex.evaluate(l);return p.indexOf(d,y)}return p.indexOf(d)}eachChild(l){l(this.needle),l(this.haystack),this.fromIndex&&l(this.fromIndex)}outputDefined(){return!1}serialize(){if(this.fromIndex!=null&&this.fromIndex!==void 0){const l=this.fromIndex.serialize();return["index-of",this.needle.serialize(),this.haystack.serialize(),l]}return["index-of",this.needle.serialize(),this.haystack.serialize()]}}class Qx{constructor(l,d,p,y,b,w){this.inputType=l,this.type=d,this.input=p,this.cases=y,this.outputs=b,this.otherwise=w}static parse(l,d){if(l.length<5)return d.error(`Expected at least 4 arguments, but found only ${l.length-1}.`);if(l.length%2!=1)return d.error("Expected an even number of arguments.");let p,y;d.expectedType&&d.expectedType.kind!=="value"&&(y=d.expectedType);const b={},w=[];for(let F=2;FNumber.MAX_SAFE_INTEGER)return H.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`);if(typeof Y=="number"&&Math.floor(Y)!==Y)return H.error("Numeric branch labels must be integer values.");if(p){if(H.checkSubtype(p,co(Y)))return null}else p=co(Y);if(b[String(Y)]!==void 0)return H.error("Branch labels must be unique.");b[String(Y)]=w.length}const Z=d.parse(U,F,y);if(!Z)return null;y=y||Z.type,w.push(Z)}const k=d.parse(l[1],1,$s);if(!k)return null;const M=d.parse(l[l.length-1],l.length-1,y);return M?k.type.kind!=="value"&&d.concat(1).checkSubtype(p,k.type)?null:new Qx(p,y,k,b,w,M):null}evaluate(l){const d=this.input.evaluate(l);return(S0(co(d),this.inputType)&&this.outputs[this.cases[d]]||this.otherwise).evaluate(l)}eachChild(l){l(this.input),this.outputs.forEach(l),l(this.otherwise)}outputDefined(){return this.outputs.every(l=>l.outputDefined())&&this.otherwise.outputDefined()}serialize(){const l=["match",this.input.serialize()],d=Object.keys(this.cases).sort(),p=[],y={};for(const w of d){const k=y[this.cases[w]];k===void 0?(y[this.cases[w]]=p.length,p.push([this.cases[w],[w]])):p[k][1].push(w)}const b=w=>this.inputType.kind==="number"?Number(w):w;for(const[w,k]of p)l.push(k.length===1?b(k[0]):k.map(b)),l.push(this.outputs[w].serialize());return l.push(this.otherwise.serialize()),l}}class Jx{constructor(l,d,p){this.type=l,this.branches=d,this.otherwise=p}static parse(l,d){if(l.length<4)return d.error(`Expected at least 3 arguments, but found only ${l.length-1}.`);if(l.length%2!=0)return d.error("Expected an odd number of arguments.");let p;d.expectedType&&d.expectedType.kind!=="value"&&(p=d.expectedType);const y=[];for(let w=1;wd.outputDefined())&&this.otherwise.outputDefined()}serialize(){const l=["case"];return this.eachChild(d=>{l.push(d.serialize())}),l}}class G0{constructor(l,d,p,y){this.type=l,this.input=d,this.beginIndex=p,this.endIndex=y}static parse(l,d){if(l.length<=2||l.length>=5)return d.error(`Expected 3 or 4 arguments, but found ${l.length-1} instead.`);const p=d.parse(l[1],1,$s),y=d.parse(l[2],2,Zr);if(!p||!y)return null;if(!dS(p.type,[tl($s),fs,$s]))return d.error(`Expected first argument to be of type array or string, but found ${Ta(p.type)} instead`);if(l.length===4){const b=d.parse(l[3],3,Zr);return b?new G0(p.type,p,y,b):null}return new G0(p.type,p,y)}evaluate(l){const d=this.input.evaluate(l),p=this.beginIndex.evaluate(l);if(!Ux(d,["string","array"]))throw new Ya(`Expected first argument to be of type array or string, but found ${Ta(co(d))} instead.`);if(this.endIndex){const y=this.endIndex.evaluate(l);return d.slice(p,y)}return d.slice(p)}eachChild(l){l(this.input),l(this.beginIndex),this.endIndex&&l(this.endIndex)}outputDefined(){return!1}serialize(){if(this.endIndex!=null&&this.endIndex!==void 0){const l=this.endIndex.serialize();return["slice",this.input.serialize(),this.beginIndex.serialize(),l]}return["slice",this.input.serialize(),this.beginIndex.serialize()]}}class MS{constructor(l,d){this.type=tl(fs),this.str=l,this.delimiter=d}static parse(l,d){if(l.length!==3)return d.error(`Expected 2 arguments, but found ${l.length-1} instead.`);const p=d.parse(l[1],1,fs),y=d.parse(l[2],2,fs);return p&&y?new MS(p,y):void 0}evaluate(l){const d=this.str.evaluate(l),p=this.delimiter.evaluate(l);return d.split(p)}eachChild(l){l(this.str),l(this.delimiter)}outputDefined(){return!1}serialize(){return["split",this.str.serialize(),this.delimiter.serialize()]}}function OS(h,l){return h==="=="||h==="!="?l.kind==="boolean"||l.kind==="string"||l.kind==="number"||l.kind==="null"||l.kind==="value":l.kind==="string"||l.kind==="number"||l.kind==="value"}function RS(h,l,d,p){return p.compare(l,d)===0}function Ng(h,l,d){const p=h!=="=="&&h!=="!=";return class qye{constructor(b,w,k){this.type=Zs,this.lhs=b,this.rhs=w,this.collator=k,this.hasUntypedArgument=b.type.kind==="value"||w.type.kind==="value"}static parse(b,w){if(b.length!==3&&b.length!==4)return w.error("Expected two or three arguments.");const k=b[0];let M=w.parse(b[1],1,$s);if(!M)return null;if(!OS(k,M.type))return w.concat(1).error(`"${k}" comparisons are not supported for type '${Ta(M.type)}'.`);let F=w.parse(b[2],2,$s);if(!F)return null;if(!OS(k,F.type))return w.concat(2).error(`"${k}" comparisons are not supported for type '${Ta(F.type)}'.`);if(M.type.kind!==F.type.kind&&M.type.kind!=="value"&&F.type.kind!=="value")return w.error(`Cannot compare types '${Ta(M.type)}' and '${Ta(F.type)}'.`);p&&(M.type.kind==="value"&&F.type.kind!=="value"?M=new Yu(F.type,[M]):M.type.kind!=="value"&&F.type.kind==="value"&&(F=new Yu(M.type,[F])));let $=null;if(b.length===4){if(M.type.kind!=="string"&&F.type.kind!=="string"&&M.type.kind!=="value"&&F.type.kind!=="value")return w.error("Cannot use collator to compare non-string types.");if($=w.parse(b[3],3,j0),!$)return null}return new qye(M,F,$)}evaluate(b){const w=this.lhs.evaluate(b),k=this.rhs.evaluate(b);if(p&&this.hasUntypedArgument){const M=co(w),F=co(k);if(M.kind!==F.kind||M.kind!=="string"&&M.kind!=="number")throw new Ya(`Expected arguments for "${h}" to be (string, string) or (number, number), but found (${M.kind}, ${F.kind}) instead.`)}if(this.collator&&!p&&this.hasUntypedArgument){const M=co(w),F=co(k);if(M.kind!=="string"||F.kind!=="string")return l(b,w,k)}return this.collator?d(b,w,k,this.collator.evaluate(b)):l(b,w,k)}eachChild(b){b(this.lhs),b(this.rhs),this.collator&&b(this.collator)}outputDefined(){return!0}serialize(){const b=[h];return this.eachChild(w=>{b.push(w.serialize())}),b}}}const v4=Ng("==",function(h,l,d){return l===d},RS),_4=Ng("!=",function(h,l,d){return l!==d},function(h,l,d,p){return!RS(0,l,d,p)}),_E=Ng("<",function(h,l,d){return l",function(h,l,d){return l>d},function(h,l,d,p){return p.compare(l,d)>0}),K0=Ng("<=",function(h,l,d){return l<=d},function(h,l,d,p){return p.compare(l,d)<=0}),b4=Ng(">=",function(h,l,d){return l>=d},function(h,l,d,p){return p.compare(l,d)>=0});class Z0{constructor(l,d,p,y,b,w){this.type=fs,this.number=l,this.locale=d,this.currency=p,this.unit=y,this.minFractionDigits=b,this.maxFractionDigits=w}static parse(l,d){if(l.length!==3)return d.error("Expected two arguments.");const p=d.parse(l[1],1,Zr);if(!p)return null;const y=l[2];if(typeof y!="object"||Array.isArray(y))return d.error("NumberFormat options argument must be an object.");let b=null;if(y.locale&&(b=d.parseObjectValue(y.locale,2,"locale",fs),!b))return null;let w=null;if(y.currency&&(w=d.parseObjectValue(y.currency,2,"currency",fs),!w))return null;let k=null;if(y.unit&&(k=d.parseObjectValue(y.unit,2,"unit",fs),!k))return null;let M=null;if(y["min-fraction-digits"]&&(M=d.parseObjectValue(y["min-fraction-digits"],2,"min-fraction-digits",Zr),!M))return null;let F=null;return y["max-fraction-digits"]&&(F=d.parseObjectValue(y["max-fraction-digits"],2,"max-fraction-digits",Zr),!F)?null:new Z0(p,b,w,k,M,F)}evaluate(l){return new Intl.NumberFormat(this.locale?this.locale.evaluate(l):[],{style:(this.currency?"currency":this.unit&&"unit")||"decimal",currency:this.currency?this.currency.evaluate(l):void 0,unit:this.unit?this.unit.evaluate(l):void 0,minimumFractionDigits:this.minFractionDigits?this.minFractionDigits.evaluate(l):void 0,maximumFractionDigits:this.maxFractionDigits?this.maxFractionDigits.evaluate(l):void 0}).format(this.number.evaluate(l))}eachChild(l){l(this.number),this.locale&&l(this.locale),this.currency&&l(this.currency),this.unit&&l(this.unit),this.minFractionDigits&&l(this.minFractionDigits),this.maxFractionDigits&&l(this.maxFractionDigits)}outputDefined(){return!1}serialize(){const l={};return this.locale&&(l.locale=this.locale.serialize()),this.currency&&(l.currency=this.currency.serialize()),this.unit&&(l.unit=this.unit.serialize()),this.minFractionDigits&&(l["min-fraction-digits"]=this.minFractionDigits.serialize()),this.maxFractionDigits&&(l["max-fraction-digits"]=this.maxFractionDigits.serialize()),["number-format",this.number.serialize(),l]}}class DS{constructor(l){this.type=Zr,this.input=l}static parse(l,d){if(l.length!==2)return d.error(`Expected 1 argument, but found ${l.length-1} instead.`);const p=d.parse(l[1],1);return p?p.type.kind!=="array"&&p.type.kind!=="string"&&p.type.kind!=="value"?d.error(`Expected argument of type string or array, but found ${Ta(p.type)} instead.`):new DS(p):null}evaluate(l){const d=this.input.evaluate(l);if(typeof d=="string"||Array.isArray(d))return d.length;throw new Ya(`Expected value to be of type string or array, but found ${Ta(co(d))} instead.`)}eachChild(l){l(this.input)}outputDefined(){return!1}serialize(){const l=["length"];return this.eachChild(d=>{l.push(d.serialize())}),l}}function wE(h){return function(){h=1831565813+(h|=0)|0;let l=Math.imul(h^h>>>15,1|h);return l=l+Math.imul(l^l>>>7,61|l)^l,((l^l>>>14)>>>0)/4294967296}}const Cg={"==":v4,"!=":_4,">":bE,"<":_E,">=":b4,"<=":K0,array:Yu,at:H0,"at-interpolated":W0,boolean:Yu,case:Jx,coalesce:Xx,collator:_o,format:Md,image:En,in:IS,"index-of":Sg,interpolate:Uc,"interpolate-hcl":Uc,"interpolate-lab":Uc,length:DS,let:Th,literal:Ch,match:Qx,number:Yu,"number-format":Z0,object:Yu,slice:G0,step:Zx,string:Yu,"to-boolean":Od,"to-color":Od,"to-number":Od,"to-string":Od,var:z0,within:zf,distance:Kp,config:bg,split:MS};function LS(h,[l,d,p,y]){l=l.evaluate(h),d=d.evaluate(h),p=p.evaluate(h);const b=y?y.evaluate(h):1,w=Hp(l,d,p,b);if(w)throw new Ya(w);return new Us(l/255,d/255,p/255,b)}function FS(h,[l,d,p,y]){l=l.evaluate(h),d=d.evaluate(h),p=p.evaluate(h);const b=y?y.evaluate(h):1,w=function(F,$,U,H){return typeof F=="number"&&F>=0&&F<=360?typeof $=="number"&&$>=0&&$<=100&&typeof U=="number"&&U>=0&&U<=100?H===void 0||typeof H=="number"&&H>=0&&H<=1?null:`Invalid hsla value [${[F,$,U,H].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid hsla value [${(typeof H=="number"?[F,$,U,H]:[F,$,U]).join(", ")}]: 's', and 'l' must be between 0 and 100.`:`Invalid hsla value [${(typeof H=="number"?[F,$,U,H]:[F,$,U]).join(", ")}]: 'h' must be between 0 and 360.`}(l,d,p,b);if(w)throw new Ya(w);const k=`hsla(${l}, ${d}%, ${p}%, ${b})`,M=Us.parse(k);if(!M)throw new Ya(`Failed to parse HSLA color: ${k}`);return M}function jE(h,l){return h in l}function zS(h,l){const d=l[h];return d===void 0?null:d}function Uf(h){return{type:h}}function Zp(h){if(h instanceof bg)return new Set([h.key]);let l=new Set;return h.eachChild(d=>{l=new Set([...l,...Zp(d)])}),l}function Y0(h){if(h instanceof Ol&&h.name==="is-active-floor")return!0;let l=!1;return h.eachChild(d=>{!l&&Y0(d)&&(l=!0)}),l}function SE(h){return{result:"success",value:h}}function Vf(h){return{result:"error",value:h}}function BS(h,l){return!!h&&!!h.parameters&&h.parameters.indexOf(l)>-1}function ev(h){return h["property-type"]==="data-driven"}function NE(h){return BS(h.expression,"measure-light")}function CE(h){return BS(h.expression,"zoom")}function X0(h){return!!h.expression&&h.expression.interpolated}function Q0(h){return typeof h=="object"&&h!==null&&!Array.isArray(h)}function kE(h){return h}function TE(h,l){const d=l.type==="color",p=h.stops&&typeof h.stops[0][0]=="object",y=p||!(p||h.property!==void 0),b=h.type||(X0(l)?"exponential":"interval");if(d&&((h=Object.assign({},h)).stops&&(h.stops=h.stops.map(F=>[F[0],Us.parse(F[1])])),h.default=Us.parse(h.default?h.default:l.default)),h.colorSpace&&h.colorSpace!=="rgb"&&!vE[h.colorSpace])throw new Error(`Unknown color space: ${h.colorSpace}`);let w,k,M;if(b==="exponential")w=EE;else if(b==="interval")w=j4;else if(b==="categorical"){w=w4,k=Object.create(null);for(const F of h.stops)k[F[0]]=F[1];M=typeof h.stops[0][0]}else{if(b!=="identity")throw new Error(`Unknown function type "${b}"`);w=AE}if(p){const F={},$=[];for(let Z=0;ZZ[0]),evaluate:({zoom:Z},Y)=>EE({stops:U,base:h.base},l,Z).evaluate(Z,Y)}}if(y){const F=b==="exponential"?{name:"exponential",base:h.base!==void 0?h.base:1}:null;return{kind:"camera",interpolationType:F,interpolationFactor:Uc.interpolationFactor.bind(void 0,F),zoomStops:h.stops.map($=>$[0]),evaluate:({zoom:$})=>w(h,l,$,k,M)}}return{kind:"source",evaluate(F,$){const U=$&&$.properties?$.properties[h.property]:void 0;return U===void 0?Dd(h.default,l.default):w(h,l,U,k,M)}}}function Dd(h,l,d){return h!==void 0?h:l!==void 0?l:d!==void 0?d:void 0}function w4(h,l,d,p,y){return Dd(typeof d===y?p[d]:void 0,h.default,l.default)}function j4(h,l,d){if(!mg(d))return Dd(h.default,l.default);const p=h.stops.length;if(p===1||d<=h.stops[0][0])return h.stops[0][1];if(d>=h.stops[p-1][0])return h.stops[p-1][1];const y=$0(h.stops.map(b=>b[0]),d);return h.stops[y][1]}function EE(h,l,d){const p=h.base!==void 0?h.base:1;if(!mg(d))return Dd(h.default,l.default);const y=h.stops.length;if(y===1||d<=h.stops[0][0])return h.stops[0][1];if(d>=h.stops[y-1][0])return h.stops[y-1][1];const b=$0(h.stops.map($=>$[0]),d),w=function($,U,H,Z){const Y=Z-H,ne=$-H;return Y===0?0:U===1?ne/Y:(Math.pow(U,ne)-1)/(Math.pow(U,Y)-1)}(d,p,h.stops[b][0],h.stops[b+1][0]),k=h.stops[b][1],M=h.stops[b+1][1];let F=zx[l.type]||kE;if(h.colorSpace&&h.colorSpace!=="rgb"){const $=vE[h.colorSpace];F=(U,H)=>$.reverse($.interpolate($.forward(U),$.forward(H),w))}return typeof k.evaluate=="function"?{evaluate(...$){const U=k.evaluate.apply(void 0,$),H=M.evaluate.apply(void 0,$);if(U!==void 0&&H!==void 0)return F(U,H,w)}}:F(k,M,w)}function AE(h,l,d){return l.type==="color"?d=Us.parse(d):l.type==="formatted"?d=Il.fromString(d.toString()):l.type==="resolvedImage"?d=Ml.build(d.toString()):Wr(d)===l.type||l.type==="enum"&&l.values[d]||(d=void 0),Dd(d,h.default,l.default)}Ol.register(Cg,{error:[{kind:"error"},[fs],(h,[l])=>{throw new Ya(l.evaluate(h))}],typeof:[fs,[$s],(h,[l])=>Ta(co(l.evaluate(h)))],"to-rgba":[tl(Zr,4),[sc],(h,[l])=>l.evaluate(h).toNonPremultipliedRenderColor(null).toArray()],"to-hsla":[tl(Zr,4),[sc],(h,[l])=>l.evaluate(h).toNonPremultipliedRenderColor(null).toHslaArray()],rgb:[sc,[Zr,Zr,Zr],LS],rgba:[sc,[Zr,Zr,Zr,Zr],LS],hsl:[sc,[Zr,Zr,Zr],FS],hsla:[sc,[Zr,Zr,Zr,Zr],FS],has:{type:Zs,overloads:[[[fs],(h,[l])=>jE(l.evaluate(h),h.properties())],[[fs,Id],(h,[l,d])=>jE(l.evaluate(h),d.evaluate(h))]]},get:{type:$s,overloads:[[[fs],(h,[l])=>zS(l.evaluate(h),h.properties())],[[fs,Id],(h,[l,d])=>zS(l.evaluate(h),d.evaluate(h))]]},"feature-state":[$s,[fs],(h,[l])=>zS(l.evaluate(h),h.featureState||{})],properties:[Id,[],h=>h.properties()],"geometry-type":[fs,[],h=>h.geometryType()],worldview:[fs,[],h=>h.globals.worldview||""],"is-active-floor":[Zs,Uf(fs),(h,l)=>{if(!(h.globals.activeFloors&&h.globals.activeFloors.size>0))return!1;const d=h.globals.activeFloors;return l.some(p=>{const y=p.evaluate(h);return d.has(y)})}],id:[$s,[],h=>h.id()],zoom:[Zr,[],h=>h.globals.zoom],pitch:[Zr,[],h=>h.globals.pitch||0],"distance-from-center":[Zr,[],h=>h.distanceFromCenter()],"measure-light":[Zr,[fs],(h,[l])=>h.measureLight(l.evaluate(h))],"heatmap-density":[Zr,[],h=>h.globals.heatmapDensity||0],"line-progress":[Zr,[],h=>h.globals.lineProgress||0],"raster-value":[Zr,[],h=>h.globals.rasterValue||0],"raster-particle-speed":[Zr,[],h=>h.globals.rasterParticleSpeed||0],"sky-radial-progress":[Zr,[],h=>h.globals.skyRadialProgress||0],accumulated:[$s,[],h=>h.globals.accumulated===void 0?null:h.globals.accumulated],"+":[Zr,Uf(Zr),(h,l)=>{let d=0;for(const p of l)d+=p.evaluate(h);return d}],"*":[Zr,Uf(Zr),(h,l)=>{let d=1;for(const p of l)d*=p.evaluate(h);return d}],"-":{type:Zr,overloads:[[[Zr,Zr],(h,[l,d])=>l.evaluate(h)-d.evaluate(h)],[[Zr],(h,[l])=>-l.evaluate(h)]]},"/":[Zr,[Zr,Zr],(h,[l,d])=>l.evaluate(h)/d.evaluate(h)],"%":[Zr,[Zr,Zr],(h,[l,d])=>l.evaluate(h)%d.evaluate(h)],ln2:[Zr,[],()=>Math.LN2],pi:[Zr,[],()=>Math.PI],e:[Zr,[],()=>Math.E],"^":[Zr,[Zr,Zr],(h,[l,d])=>Math.pow(l.evaluate(h),d.evaluate(h))],sqrt:[Zr,[Zr],(h,[l])=>Math.sqrt(l.evaluate(h))],log10:[Zr,[Zr],(h,[l])=>Math.log(l.evaluate(h))/Math.LN10],ln:[Zr,[Zr],(h,[l])=>Math.log(l.evaluate(h))],log2:[Zr,[Zr],(h,[l])=>Math.log2(l.evaluate(h))],sin:[Zr,[Zr],(h,[l])=>Math.sin(l.evaluate(h))],cos:[Zr,[Zr],(h,[l])=>Math.cos(l.evaluate(h))],tan:[Zr,[Zr],(h,[l])=>Math.tan(l.evaluate(h))],asin:[Zr,[Zr],(h,[l])=>Math.asin(l.evaluate(h))],acos:[Zr,[Zr],(h,[l])=>Math.acos(l.evaluate(h))],atan:[Zr,[Zr],(h,[l])=>Math.atan(l.evaluate(h))],min:[Zr,Uf(Zr),(h,l)=>Math.min(...l.map(d=>d.evaluate(h)))],max:[Zr,Uf(Zr),(h,l)=>Math.max(...l.map(d=>d.evaluate(h)))],abs:[Zr,[Zr],(h,[l])=>Math.abs(l.evaluate(h))],round:[Zr,[Zr],(h,[l])=>{const d=l.evaluate(h);return d<0?-Math.round(-d):Math.round(d)}],floor:[Zr,[Zr],(h,[l])=>Math.floor(l.evaluate(h))],ceil:[Zr,[Zr],(h,[l])=>Math.ceil(l.evaluate(h))],"filter-==":[Zs,[fs,$s],(h,[l,d])=>h.properties()[l.value]===d.value],"filter-id-==":[Zs,[$s],(h,[l])=>h.id()===l.value],"filter-type-==":[Zs,[fs],(h,[l])=>h.geometryType()===l.value],"filter-<":[Zs,[fs,$s],(h,[l,d])=>{const p=h.properties()[l.value],y=d.value;return typeof p==typeof y&&p{const d=h.id(),p=l.value;return typeof d==typeof p&&d":[Zs,[fs,$s],(h,[l,d])=>{const p=h.properties()[l.value],y=d.value;return typeof p==typeof y&&p>y}],"filter-id->":[Zs,[$s],(h,[l])=>{const d=h.id(),p=l.value;return typeof d==typeof p&&d>p}],"filter-<=":[Zs,[fs,$s],(h,[l,d])=>{const p=h.properties()[l.value],y=d.value;return typeof p==typeof y&&p<=y}],"filter-id-<=":[Zs,[$s],(h,[l])=>{const d=h.id(),p=l.value;return typeof d==typeof p&&d<=p}],"filter->=":[Zs,[fs,$s],(h,[l,d])=>{const p=h.properties()[l.value],y=d.value;return typeof p==typeof y&&p>=y}],"filter-id->=":[Zs,[$s],(h,[l])=>{const d=h.id(),p=l.value;return typeof d==typeof p&&d>=p}],"filter-has":[Zs,[$s],(h,[l])=>l.value in h.properties()],"filter-has-id":[Zs,[],h=>h.id()!==null&&h.id()!==void 0],"filter-type-in":[Zs,[tl(fs)],(h,[l])=>l.value.indexOf(h.geometryType())>=0],"filter-id-in":[Zs,[tl($s)],(h,[l])=>l.value.indexOf(h.id())>=0],"filter-in-small":[Zs,[fs,tl($s)],(h,[l,d])=>d.value.indexOf(h.properties()[l.value])>=0],"filter-in-large":[Zs,[fs,tl($s)],(h,[l,d])=>function(p,y,b,w){for(;b<=w;){const k=b+w>>1;if(y[k]===p)return!0;y[k]>p?w=k-1:b=k+1}return!1}(h.properties()[l.value],d.value,0,d.value.length-1)],all:{type:Zs,overloads:[[[Zs,Zs],(h,[l,d])=>l.evaluate(h)&&d.evaluate(h)],[Uf(Zs),(h,l)=>{for(const d of l)if(!d.evaluate(h))return!1;return!0}]]},any:{type:Zs,overloads:[[[Zs,Zs],(h,[l,d])=>l.evaluate(h)||d.evaluate(h)],[Uf(Zs),(h,l)=>{for(const d of l)if(d.evaluate(h))return!0;return!1}]]},"!":[Zs,[Zs],(h,[l])=>!l.evaluate(h)],"is-supported-script":[Zs,[fs],(h,[l])=>{const d=h.globals&&h.globals.isSupportedScript;return!d||d(l.evaluate(h))}],upcase:[fs,[fs],(h,[l])=>l.evaluate(h).toUpperCase()],downcase:[fs,[fs],(h,[l])=>l.evaluate(h).toLowerCase()],concat:[fs,Uf($s),(h,l)=>l.map(d=>_u(d.evaluate(h))).join("")],"resolved-locale":[fs,[j0],(h,[l])=>l.evaluate(h).resolvedLocale()],random:[Zr,[Zr,Zr,$s],(h,l)=>{const[d,p,y]=l.map(w=>w.evaluate(h));if(d>p||d===p)return d;let b;if(typeof y=="string")b=function(w){let k=0;if(w.length===0)return k;for(let M=0;MJSON.stringify(U)).join(", ")}, but found ${JSON.stringify($)} instead.`);return $}catch($){const U=$;return this._warningHistory[U.message]||(this._warningHistory[U.message]=!0,typeof console<"u"&&console.warn(`Failed to evaluate expression "${JSON.stringify(this.expression.serialize())}". ${U.message}`)),this._defaultValue}}}function tv(h){return Array.isArray(h)&&h.length>0&&typeof h[0]=="string"&&h[0]in Cg}function qf(h,l,d,p,y){const b=new B0(Cg,[],l?function(k){const M={color:sc,string:fs,number:Zr,enum:fs,boolean:Zs,formatted:Bx,resolvedImage:$x};return k.type==="array"?tl(M[k.value]||$s,k.length):M[k.type]}(l):void 0,void 0,void 0,d,p,y),w=b.parse(h,void 0,void 0,void 0,l&&l.type==="string"?{typeAnnotation:"coerce"}:void 0);return w?SE(new J0(w,l,d,p,y)):Vf(b.errors)}class kg{constructor(l,d,p,y){this.kind=l,this._styleExpression=d,this.isLightConstant=p,this.isLineProgressConstant=y,this.isStateDependent=l!=="constant"&&!Kx(d.expression),this.configDependencies=Zp(d.expression),this.isIndoorDependent=Y0(d.expression)}evaluateWithoutErrorHandling(l,d,p,y,b,w){return this._styleExpression.evaluateWithoutErrorHandling(l,d,p,y,b,w)}evaluate(l,d,p,y,b,w,k){return this._styleExpression.evaluate(l,d,p,y,b,w,void 0,void 0,k)}}class Yp{constructor(l,d,p,y,b,w){this.kind=l,this.zoomStops=p,this._styleExpression=d,this.isStateDependent=l!=="camera"&&!Kx(d.expression),this.isIndoorDependent=Y0(d.expression),this.isLightConstant=b,this.isLineProgressConstant=w,this.configDependencies=Zp(d.expression),this.interpolationType=y}evaluateWithoutErrorHandling(l,d,p,y,b,w){return this._styleExpression.evaluateWithoutErrorHandling(l,d,p,y,b,w)}evaluate(l,d,p,y,b,w){return this._styleExpression.evaluate(l,d,p,y,b,w)}interpolationFactor(l,d,p){return this.interpolationType?Uc.interpolationFactor(this.interpolationType,l,d,p):0}}function $S(h,l,d,p,y){if((h=qf(h,l,d,p,y)).result==="error")return h;const b=h.value.expression,w=vg(b);if(!w&&!ev(l))return Vf([new vu("","data expressions not supported")]);const k=_g(b,["zoom","pitch","distance-from-center"]);if(!k&&!CE(l))return Vf([new vu("","zoom expressions not supported")]);const M=_g(b,["measure-light"]);if(!M&&!NE(l))return Vf([new vu("","measure-light expression not supported")]);const F=_g(b,["line-progress"]);if(!F&&!function(H){return BS(H.expression,"line-progress")}(l))return Vf([new vu("","line-progress expression not supported")]);const $=l.expression&&l.expression.relaxZoomRestriction,U=Qu(b);return U||k||$?U instanceof vu?Vf([U]):U instanceof Uc&&!X0(l)?Vf([new vu("",'"interpolate" expressions cannot be used with this property')]):SE(U?new Yp(w&&F?"camera":"composite",h.value,U.labels,U instanceof Uc?U.interpolation:void 0,M,F):new kg(w&&F?"constant":"source",h.value,M,F)):Vf([new vu("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression, or in the properties of atmosphere.')])}class eb{constructor(l,d){this._parameters=l,this._specification=d,Object.assign(this,TE(this._parameters,this._specification))}static deserialize(l){return new eb(l._parameters,l._specification)}static serialize(l){return{_parameters:l._parameters,_specification:l._specification}}}function Qu(h){let l=null;if(h instanceof Th)l=Qu(h.result);else if(h instanceof Xx){for(const d of h.args)if(l=Qu(d),l)break}else(h instanceof Zx||h instanceof Uc)&&h.input instanceof Ol&&h.input.name==="zoom"&&(l=h);return l instanceof vu||h.eachChild(d=>{const p=Qu(d);p instanceof vu?l=p:l&&p&&l!==p&&(l=new vu("",'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'))}),l}var US,PE,IE=function(){if(PE)return US;PE=1,US=l;var h=3;function l(d,p,y){var b=this.cells=[];if(d instanceof ArrayBuffer){this.arrayBuffer=d;var w=new Int32Array(this.arrayBuffer);d=w[0],this.d=(p=w[1])+2*(y=w[2]);for(var k=0;k=H[ne+0]&&b>=H[ne+1])?(M[Y]=!0,k.push(U[Y])):M[Y]=!1}}},l.prototype._forEachCell=function(d,p,y,b,w,k,M,F){for(var $=this._convertToCellCoord(d),U=this._convertToCellCoord(p),H=this._convertToCellCoord(y),Z=this._convertToCellCoord(b),Y=$;Y<=H;Y++)for(var ne=U;ne<=Z;ne++){var ce=this.d*ne+Y;if((!F||F(this._convertFromCellCoord(Y),this._convertFromCellCoord(ne),this._convertFromCellCoord(Y+1),this._convertFromCellCoord(ne+1)))&&w.call(this,d,p,y,b,ce,k,M,F))return}},l.prototype._convertFromCellCoord=function(d){return(d-this.padding)/this.scale},l.prototype._convertToCellCoord=function(d){return Math.max(0,Math.min(this.d-1,Math.floor(d*this.scale)+this.padding))},l.prototype.toArrayBuffer=function(){if(this.arrayBuffer)return this.arrayBuffer;for(var d=this.cells,p=h+this.cells.length+1+1,y=0,b=0;b=0||(y[b]=Eh(h[b],l)));h instanceof Error&&(y.message=h.message)}if(y.$name)throw new Error("$name property is reserved for worker serialization logic.");return p!=="Object"&&(y.$name=p),y}throw new Error("can't serialize object of type "+typeof h)}function Hf(h){if(h==null||typeof h=="boolean"||typeof h=="number"||typeof h=="string"||h instanceof Boolean||h instanceof Number||h instanceof String||h instanceof Date||h instanceof RegExp||rv(h)||h instanceof ImageBitmap||ArrayBuffer.isView(h)||h instanceof ImageData)return h;if(Array.isArray(h))return h.map(Hf);if(typeof h=="object"){const l=h.$name||"Object";if(l==="Map"){const y=h.entries||[],b=new Map;for(let w=0;wh>=128&&h<=255,Arabic:h=>h>=1536&&h<=1791,"Arabic Supplement":h=>h>=1872&&h<=1919,"Arabic Extended-A":h=>h>=2208&&h<=2303,"Hangul Jamo":h=>h>=4352&&h<=4607,"Unified Canadian Aboriginal Syllabics":h=>h>=5120&&h<=5759,Khmer:h=>h>=6016&&h<=6143,"Unified Canadian Aboriginal Syllabics Extended":h=>h>=6320&&h<=6399,"General Punctuation":h=>h>=8192&&h<=8303,"Letterlike Symbols":h=>h>=8448&&h<=8527,"Number Forms":h=>h>=8528&&h<=8591,"Miscellaneous Technical":h=>h>=8960&&h<=9215,"Control Pictures":h=>h>=9216&&h<=9279,"Optical Character Recognition":h=>h>=9280&&h<=9311,"Enclosed Alphanumerics":h=>h>=9312&&h<=9471,"Geometric Shapes":h=>h>=9632&&h<=9727,"Miscellaneous Symbols":h=>h>=9728&&h<=9983,"Miscellaneous Symbols and Arrows":h=>h>=11008&&h<=11263,"CJK Radicals Supplement":h=>h>=11904&&h<=12031,"Kangxi Radicals":h=>h>=12032&&h<=12255,"Ideographic Description Characters":h=>h>=12272&&h<=12287,"CJK Symbols and Punctuation":h=>h>=12288&&h<=12351,Hiragana:h=>h>=12352&&h<=12447,Katakana:h=>h>=12448&&h<=12543,Bopomofo:h=>h>=12544&&h<=12591,"Hangul Compatibility Jamo":h=>h>=12592&&h<=12687,Kanbun:h=>h>=12688&&h<=12703,"Bopomofo Extended":h=>h>=12704&&h<=12735,"CJK Strokes":h=>h>=12736&&h<=12783,"Katakana Phonetic Extensions":h=>h>=12784&&h<=12799,"Enclosed CJK Letters and Months":h=>h>=12800&&h<=13055,"CJK Compatibility":h=>h>=13056&&h<=13311,"CJK Unified Ideographs Extension A":h=>h>=13312&&h<=19903,"Yijing Hexagram Symbols":h=>h>=19904&&h<=19967,"CJK Unified Ideographs":h=>h>=19968&&h<=40959,"Yi Syllables":h=>h>=40960&&h<=42127,"Yi Radicals":h=>h>=42128&&h<=42191,"Hangul Jamo Extended-A":h=>h>=43360&&h<=43391,"Hangul Syllables":h=>h>=44032&&h<=55215,"Hangul Jamo Extended-B":h=>h>=55216&&h<=55295,"Private Use Area":h=>h>=57344&&h<=63743,"CJK Compatibility Ideographs":h=>h>=63744&&h<=64255,"Arabic Presentation Forms-A":h=>h>=64336&&h<=65023,"Vertical Forms":h=>h>=65040&&h<=65055,"CJK Compatibility Forms":h=>h>=65072&&h<=65103,"Small Form Variants":h=>h>=65104&&h<=65135,"Arabic Presentation Forms-B":h=>h>=65136&&h<=65279,"Halfwidth and Fullwidth Forms":h=>h>=65280&&h<=65519,Osage:h=>h>=66736&&h<=66815,"CJK Unified Ideographs Extension B":h=>h>=131072&&h<=173791};function nv(h){for(const l of h)if(tb(l.charCodeAt(0)))return!0;return!1}function VS(h){for(const l of h)if(!ME(l.charCodeAt(0)))return!1;return!0}function ME(h){return!(an.Arabic(h)||an["Arabic Supplement"](h)||an["Arabic Extended-A"](h)||an["Arabic Presentation Forms-A"](h)||an["Arabic Presentation Forms-B"](h))}function tb(h){return!(h!==746&&h!==747&&(h<4352||!(an["Bopomofo Extended"](h)||an.Bopomofo(h)||an["CJK Compatibility Forms"](h)&&!(h>=65097&&h<=65103)||an["CJK Compatibility Ideographs"](h)||an["CJK Compatibility"](h)||an["CJK Radicals Supplement"](h)||an["CJK Strokes"](h)||!(!an["CJK Symbols and Punctuation"](h)||h>=12296&&h<=12305||h>=12308&&h<=12319||h===12336)||an["CJK Unified Ideographs Extension A"](h)||an["CJK Unified Ideographs"](h)||an["Enclosed CJK Letters and Months"](h)||an["Hangul Compatibility Jamo"](h)||an["Hangul Jamo Extended-A"](h)||an["Hangul Jamo Extended-B"](h)||an["Hangul Jamo"](h)||an["Hangul Syllables"](h)||an.Hiragana(h)||an["Ideographic Description Characters"](h)||an.Kanbun(h)||an["Kangxi Radicals"](h)||an["Katakana Phonetic Extensions"](h)||an.Katakana(h)&&h!==12540||!(!an["Halfwidth and Fullwidth Forms"](h)||h===65288||h===65289||h===65293||h>=65306&&h<=65310||h===65339||h===65341||h===65343||h>=65371&&h<=65503||h===65507||h>=65512&&h<=65519)||!(!an["Small Form Variants"](h)||h>=65112&&h<=65118||h>=65123&&h<=65126)||an["Unified Canadian Aboriginal Syllabics"](h)||an["Unified Canadian Aboriginal Syllabics Extended"](h)||an["Vertical Forms"](h)||an["Yijing Hexagram Symbols"](h)||an["Yi Syllables"](h)||an["Yi Radicals"](h))))}function rb(h){return!(tb(h)||function(l){return!!(an["Latin-1 Supplement"](l)&&(l===167||l===169||l===174||l===177||l===188||l===189||l===190||l===215||l===247)||an["General Punctuation"](l)&&(l===8214||l===8224||l===8225||l===8240||l===8241||l===8251||l===8252||l===8258||l===8263||l===8264||l===8265||l===8273)||an["Letterlike Symbols"](l)||an["Number Forms"](l)||an["Miscellaneous Technical"](l)&&(l>=8960&&l<=8967||l>=8972&&l<=8991||l>=8996&&l<=9e3||l===9003||l>=9085&&l<=9114||l>=9150&&l<=9165||l===9167||l>=9169&&l<=9179||l>=9186&&l<=9215)||an["Control Pictures"](l)&&l!==9251||an["Optical Character Recognition"](l)||an["Enclosed Alphanumerics"](l)||an["Geometric Shapes"](l)||an["Miscellaneous Symbols"](l)&&!(l>=9754&&l<=9759)||an["Miscellaneous Symbols and Arrows"](l)&&(l>=11026&&l<=11055||l>=11088&&l<=11097||l>=11192&&l<=11243)||an["CJK Symbols and Punctuation"](l)||an.Katakana(l)||an["Private Use Area"](l)||an["CJK Compatibility Forms"](l)||an["Small Form Variants"](l)||an["Halfwidth and Fullwidth Forms"](l)||l===8734||l===8756||l===8757||l>=9984&&l<=10087||l>=10102&&l<=10131||l===65532||l===65533)}(h))}function nb(h){return an.Arabic(h)||an["Arabic Supplement"](h)||an["Arabic Extended-A"](h)||an["Arabic Presentation Forms-A"](h)||an["Arabic Presentation Forms-B"](h)}function qS(h){return h>=1424&&h<=2303||an["Arabic Presentation Forms-A"](h)||an["Arabic Presentation Forms-B"](h)}function Ah(h,l){return!(!l&&qS(h)||h>=2304&&h<=3583||h>=3840&&h<=4255||an.Khmer(h))}function S4(h){for(const l of h)if(qS(l.charCodeAt(0)))return!0;return!1}const Sc={unavailable:"unavailable",deferred:"deferred",loading:"loading",parsing:"parsing",parsed:"parsed",loaded:"loaded",error:"error"};let HS=null,Rl=Sc.unavailable,Ph=null;const sv=function(h){h&&typeof h=="string"&&h.indexOf("NetworkError")>-1&&(Rl=Sc.error),HS&&HS(h)};function sb(){ib.fire(new Pd("pluginStateChange",{pluginStatus:Rl,pluginURL:Ph}))}const ib=new qp,iv=function(){return Rl},OE=function(){if(Rl!==Sc.deferred||!Ph)throw new Error("rtl-text-plugin cannot be downloaded unless a pluginURL is specified");Rl=Sc.loading,sb(),Ph&&Sh({url:Ph},h=>{h?sv(h):(Rl=Sc.loaded,sb())})},Ih={applyArabicShaping:null,processBidirectionalText:null,processStyledBidirectionalText:null,isLoaded:()=>Rl===Sc.loaded||Ih.applyArabicShaping!=null,isLoading:()=>Rl===Sc.loading,setState(h){Rl=h.pluginStatus,Ph=h.pluginURL},isParsing:()=>Rl===Sc.parsing,isParsed:()=>Rl===Sc.parsed,getPluginURL:()=>Ph};class wi{constructor(l,d){this.zoom=l,d?(this.now=d.now,this.fadeDuration=d.fadeDuration,this.transition=d.transition,this.pitch=d.pitch,this.brightness=d.brightness,this.worldview=d.worldview,this.activeFloors=d.activeFloors):(this.now=0,this.fadeDuration=0,this.transition={},this.pitch=0,this.brightness=0)}isSupportedScript(l){return function(d,p){for(const y of d)if(!Ah(y.charCodeAt(0),p))return!1;return!0}(l,Ih.isLoaded())}}class ab{constructor(l,d,p,y,b){this.property=l,this.value=d,this.expression=function(w,k,M,F,$){if(Q0(w))return new eb(w,k);if(tv(w)||Array.isArray(w)&&w.length>0){const U=$S(w,k,M,F,$);if(U.result==="error")throw new Error(U.value.map(H=>`${H.key}: ${H.message}`).join(", "));return U.value}{let U=w;return typeof w=="string"&&k.type==="color"&&(U=Us.parse(w)),{kind:"constant",configDependencies:new Set,isIndoorDependent:!1,evaluate:()=>U}}}(d===void 0?l.specification.default:d,l.specification,p,y,b)}isIndoorDependent(){return this.expression.isIndoorDependent}isDataDriven(){return this.expression.kind==="source"||this.expression.kind==="composite"}possiblyEvaluate(l,d,p,y){return this.property.possiblyEvaluate(this,l,d,p,y)}}class WS{constructor(l,d,p,y){this.property=l,this.value=new ab(l,void 0,d,p,y)}transitioned(l,d){return new DE(this.property,this.value,d,Object.assign({},l.transition,this.transition),l.now)}untransitioned(){return new DE(this.property,this.value,null,{},0)}}class RE{constructor(l,d,p,y){this._properties=l,this._values=Object.create(l.defaultTransitionablePropertyValues),this._scope=d,this._options=p,this._iconImageUseTheme=y,this._isIndoorDependent=!1,this.configDependencies=new Set}getValue(l){return Ut(this._values[l].value.value)}setValue(l,d){this._values.hasOwnProperty(l)||(this._values[l]=new WS(this._values[l].property,this._scope,this._options,this._iconImageUseTheme)),this._values[l].value=new ab(this._values[l].property,d===null?void 0:Ut(d),this._scope,this._options,this._iconImageUseTheme),this._values[l].value.expression.configDependencies&&(this.configDependencies=new Set([...this.configDependencies,...this._values[l].value.expression.configDependencies]),this._isIndoorDependent=this._isIndoorDependent||this._values[l].value.isIndoorDependent())}setTransitionOrValue(l,d){d&&(this._options=d);const p=this._properties.properties;if(l)for(const y in l){const b=l[y];if(y.endsWith("-transition")){const w=y.slice(0,-11);p[w]&&this.setTransition(w,b)}else p.hasOwnProperty(y)&&this.setValue(y,b)}}getTransition(l){return Ut(this._values[l].transition)}setTransition(l,d){this._values.hasOwnProperty(l)||(this._values[l]=new WS(this._values[l].property)),this._values[l].transition=Ut(d)||void 0}serialize(){const l={};for(const d of Object.keys(this._values)){const p=this.getValue(d);p!==void 0&&(l[d]=p);const y=this.getTransition(d);y!==void 0&&(l[`${d}-transition`]=y)}return l}transitioned(l,d){const p=new LE(this._properties);for(const y of Object.keys(this._values))p._values[y]=this._values[y].transitioned(l,d._values[y]);return p}untransitioned(){const l=new LE(this._properties);for(const d of Object.keys(this._values))l._values[d]=this._values[d].untransitioned();return l}isIndoorDependent(){return this._isIndoorDependent}}class DE{constructor(l,d,p,y,b){const w=y.delay||0,k=y.duration||0;b=b||0,this.property=l,this.value=d,this.begin=b+w,this.end=this.begin+k,l.specification.transition&&(y.delay||y.duration)&&(this.prior=p)}possiblyEvaluate(l,d,p){const y=l.now||0,b=this.value.possiblyEvaluate(l,d,p),w=this.prior;if(w){if(y>this.end)return this.prior=null,b;if(this.value.isDataDriven())return this.prior=null,b;if(y":1,">=":1,"<":1,"<=":1,"in":1,"!in":1,"all":1,"any":1,"none":1,"has":1,"!has":1}},"geometry_type":{"type":"enum","values":{"Point":1,"LineString":1,"Polygon":1}},"function":{"expression":{"type":"expression"},"stops":{"type":"array","value":"function_stop"},"base":{"type":"number","default":1,"minimum":0},"property":{"type":"string","default":"$zoom"},"type":{"type":"enum","values":{"identity":1,"exponential":1,"interval":1,"categorical":1},"default":"exponential"},"colorSpace":{"type":"enum","values":{"rgb":1,"lab":1,"hcl":1},"default":"rgb"},"default":{"type":"*"}},"function_stop":{"type":"array","minimum":0,"maximum":24,"value":["number","color"],"length":2},"expression":{"type":"array","value":"*","minimum":1},"fog":{"range":{"type":"array","default":[0.5,10],"minimum":-20,"maximum":20,"length":2,"value":"number","transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true}},"color":{"type":"color","default":"#ffffff","expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"use-theme":true,"transition":true},"high-color":{"type":"color","default":"#245cdf","expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"use-theme":true,"transition":true},"space-color":{"type":"color","default":["interpolate",["linear"],["zoom"],4,"#010b19",7,"#367ab9"],"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"use-theme":true,"transition":true},"horizon-blend":{"type":"number","default":["interpolate",["linear"],["zoom"],4,0.2,7,0.1],"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"star-intensity":{"type":"number","default":["interpolate",["linear"],["zoom"],5,0.35,6,0],"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"vertical-range":{"type":"array","default":[0,0],"minimum":0,"length":2,"value":"number","transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true}}},"snow":{"density":{"type":"number","default":["interpolate",["linear"],["zoom"],11,0,13,0.85],"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"intensity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"color":{"type":"color","default":"#ffffff","expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"use-theme":true,"transition":true},"opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"vignette":{"type":"number","default":["interpolate",["linear"],["zoom"],11,0,13,0.3],"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"vignette-color":{"type":"color","default":"#ffffff","expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"use-theme":true,"transition":true},"center-thinning":{"type":"number","default":0.4,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"direction":{"type":"array","default":[0,50],"minimum":0,"maximum":360,"length":2,"value":"number","transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true}},"flake-size":{"type":"number","default":0.71,"minimum":0,"maximum":5,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true}},"rain":{"density":{"type":"number","default":["interpolate",["linear"],["zoom"],11,0,13,0.5],"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"intensity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"color":{"type":"color","default":["interpolate",["linear"],["measure-light","brightness"],0,"#03113d",0.3,"#a8adbc"],"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"use-theme":true,"transition":true},"opacity":{"type":"number","default":["interpolate",["linear"],["measure-light","brightness"],0,0.88,1,0.7],"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"vignette":{"type":"number","default":["interpolate",["linear"],["zoom"],11,0,13,1],"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"vignette-color":{"type":"color","default":["interpolate",["linear"],["measure-light","brightness"],0,"#001736",0.3,"#464646"],"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"use-theme":true,"transition":true},"center-thinning":{"type":"number","default":0.57,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"direction":{"type":"array","default":[0,80],"minimum":0,"maximum":360,"length":2,"value":"number","transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true}},"droplet-size":{"type":"array","default":[2.6,18.2],"minimum":0,"maximum":50,"length":2,"value":"number","transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true}},"distortion-strength":{"type":"number","default":0.7,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true}},"camera":{"camera-projection":{"type":"enum","values":{"perspective":1,"orthographic":1},"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]},"default":"perspective"}},"colorTheme":{"data":{"type":"string","expression":{}}},"indoor_source":{"sourceId":{"type":"string"},"sourceLayers":{"type":"array","value":"string"}},"indoor":{"*":{"type":"indoor_source"}},"light":{"anchor":{"type":"enum","default":"viewport","values":{"map":1,"viewport":1},"expression":{"parameters":["zoom"]}},"position":{"type":"array","default":[1.15,210,30],"length":3,"value":"number","transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"color":{"type":"color","default":"#ffffff","expression":{"interpolated":true,"parameters":["zoom"]},"use-theme":true,"transition":true},"intensity":{"type":"number","default":0.5,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true}},"projection":{"name":{"type":"enum","values":{"albers":1,"equalEarth":1,"equirectangular":1,"lambertConformalConic":1,"mercator":1,"naturalEarth":1,"winkelTripel":1,"globe":1},"default":"mercator"},"center":{"type":"array","length":2,"value":"number","minimum":[-180,-90],"maximum":[180,90]},"parallels":{"type":"array","length":2,"value":"number","minimum":[-90,-90],"maximum":[90,90]}},"terrain":{"source":{"type":"string"},"exaggeration":{"type":"number","default":1,"minimum":0,"maximum":1000,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true}},"paint":["paint_fill","paint_line","paint_circle","paint_heatmap","paint_fill-extrusion","paint_building","paint_symbol","paint_raster","paint_raster-particle","paint_hillshade","paint_background","paint_sky","paint_model"],"paint_fill":{"fill-antialias":{"type":"boolean","default":true,"expression":{"parameters":["zoom"]}},"fill-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"fill-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"fill-outline-color":{"type":"color","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"fill-translate":{"type":"array","value":"number","length":2,"default":[0,0],"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"fill-translate-anchor":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":["zoom"]}},"fill-pattern":{"type":"resolvedImage","expression":{"parameters":["zoom","feature"]},"property-type":"data-driven"},"fill-pattern-cross-fade":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"fill-emissive-strength":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"fill-z-offset":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature"]},"property-type":"data-driven"},"fill-bridge-guard-rail-color":{"type":"color","default":"rgba(241, 236, 225, 255)","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light","feature"]},"property-type":"data-driven"},"fill-tunnel-structure-color":{"type":"color","default":"rgba(241, 236, 225, 255)","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light","feature"]},"property-type":"data-driven"}},"paint_fill-extrusion":{"fill-extrusion-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"fill-extrusion-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"fill-extrusion-translate":{"type":"array","value":"number","length":2,"default":[0,0],"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"fill-extrusion-translate-anchor":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":["zoom"]}},"fill-extrusion-pattern":{"type":"resolvedImage","expression":{"parameters":["zoom","feature"]},"property-type":"data-driven"},"fill-extrusion-pattern-cross-fade":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"fill-extrusion-height":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-base":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-height-alignment":{"type":"enum","values":{"terrain":1,"flat":1},"default":"flat"},"fill-extrusion-base-alignment":{"type":"enum","values":{"terrain":1,"flat":1},"default":"terrain"},"fill-extrusion-vertical-gradient":{"type":"boolean","default":true,"expression":{"parameters":["zoom"]}},"fill-extrusion-ambient-occlusion-intensity":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"fill-extrusion-ambient-occlusion-radius":{"type":"number","default":3,"minimum":0,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"fill-extrusion-ambient-occlusion-wall-radius":{"type":"number","default":3,"minimum":0,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"fill-extrusion-ambient-occlusion-ground-radius":{"type":"number","default":3,"minimum":0,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"fill-extrusion-ambient-occlusion-ground-attenuation":{"type":"number","default":0.69,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"fill-extrusion-flood-light-color":{"type":"color","default":"#ffffff","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"fill-extrusion-flood-light-intensity":{"type":"number","default":0,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"fill-extrusion-flood-light-wall-radius":{"property-type":"data-driven","type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["feature","feature-state"]}},"fill-extrusion-flood-light-ground-radius":{"property-type":"data-driven","type":"number","default":0,"transition":true,"expression":{"interpolated":true,"parameters":["feature","feature-state"]}},"fill-extrusion-flood-light-ground-attenuation":{"type":"number","default":0.69,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"fill-extrusion-vertical-scale":{"type":"number","default":1,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"fill-extrusion-rounded-roof":{"type":"boolean","default":true,"expression":{"parameters":["zoom"]}},"fill-extrusion-cutoff-fade-range":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{}},"fill-extrusion-emissive-strength":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light","feature-state"]},"property-type":"data-driven"},"fill-extrusion-line-width":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"fill-extrusion-cast-shadows":{"type":"boolean","default":true}},"paint_building":{"building-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"building-ambient-occlusion-intensity":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"parameters":[]},"transition":true},"building-ambient-occlusion-ground-intensity":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"building-ambient-occlusion-ground-radius":{"type":"number","default":3,"minimum":0,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"building-ambient-occlusion-ground-attenuation":{"type":"number","default":0.69,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"building-vertical-scale":{"type":"number","default":1,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"building-cast-shadows":{"type":"boolean","default":true},"building-color":{"type":"color","default":"rgba(193, 154, 127, 1)","use-theme":true,"expression":{"interpolated":true,"parameters":["feature","feature-state","measure-light"]},"property-type":"data-driven"},"building-emissive-strength":{"type":"number","default":0,"minimum":0,"maximum":5,"expression":{"interpolated":true,"parameters":["feature","feature-state","measure-light"]},"property-type":"data-driven"},"building-facade-emissive-chance":{"type":"number","default":0.35,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["measure-light","zoom"]}},"building-cutoff-fade-range":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{}},"building-flood-light-color":{"type":"color","default":"#ffffff","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"building-flood-light-intensity":{"type":"number","default":0,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"building-flood-light-ground-attenuation":{"type":"number","default":0.69,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}}},"paint_line":{"line-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"line-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"line-translate":{"type":"array","value":"number","length":2,"default":[0,0],"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"line-translate-anchor":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":["zoom"]}},"line-width":{"type":"number","default":1,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light","line-progress"]},"property-type":"data-driven"},"line-gap-width":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"line-offset":{"type":"number","default":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"line-blur":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"line-dasharray":{"type":"array","value":"number","minimum":0,"expression":{"parameters":["zoom","feature"]},"property-type":"data-driven"},"line-pattern":{"type":"resolvedImage","expression":{"parameters":["zoom","feature"]},"property-type":"data-driven"},"line-pattern-cross-fade":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"line-gradient":{"type":"color","use-theme":true,"expression":{"interpolated":true,"parameters":["line-progress"]}},"line-trim-offset":{"type":"array","value":"number","length":2,"default":[0,0],"minimum":[0,0],"maximum":[1,1]},"line-trim-fade-range":{"type":"array","value":"number","length":2,"default":[0,0],"minimum":[0,0],"maximum":[1,1],"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"line-trim-color":{"type":"color","default":"transparent","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"line-emissive-strength":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]},"property-type":"data-driven"},"line-border-width":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-border-color":{"type":"color","default":"rgba(0, 0, 0, 0)","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-occlusion-opacity":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true}},"paint_circle":{"circle-radius":{"type":"number","default":5,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"circle-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"circle-blur":{"type":"number","default":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"circle-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"circle-translate":{"type":"array","value":"number","length":2,"default":[0,0],"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"circle-translate-anchor":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":["zoom"]}},"circle-pitch-scale":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":["zoom"]}},"circle-pitch-alignment":{"type":"enum","values":{"map":1,"viewport":1},"default":"viewport","expression":{"parameters":["zoom"]}},"circle-stroke-width":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"circle-stroke-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"circle-stroke-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"circle-emissive-strength":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}}},"paint_heatmap":{"heatmap-radius":{"type":"number","default":30,"minimum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"heatmap-weight":{"type":"number","default":1,"minimum":0,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"heatmap-intensity":{"type":"number","default":1,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"heatmap-color":{"type":"color","default":["interpolate",["linear"],["heatmap-density"],0,"rgba(0, 0, 255, 0)",0.1,"royalblue",0.3,"cyan",0.5,"lime",0.7,"yellow",1,"red"],"use-theme":true,"expression":{"interpolated":true,"parameters":["heatmap-density"]}},"heatmap-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}}},"paint_symbol":{"icon-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"icon-occlusion-opacity":{"type":"number","minimum":0,"maximum":1,"default":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"icon-emissive-strength":{"type":"number","default":1,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light","feature-state"]},"property-type":"data-driven"},"text-emissive-strength":{"type":"number","default":1,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light","feature-state"]},"property-type":"data-driven"},"icon-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"icon-halo-color":{"type":"color","default":"rgba(0, 0, 0, 0)","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"icon-halo-width":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"icon-halo-blur":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"icon-translate":{"type":"array","value":"number","length":2,"default":[0,0],"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"icon-translate-anchor":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":["zoom"]}},"icon-image-cross-fade":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"text-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"text-occlusion-opacity":{"type":"number","minimum":0,"maximum":1,"default":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"text-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"overridable":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"text-halo-color":{"type":"color","default":"rgba(0, 0, 0, 0)","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"text-halo-width":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"text-halo-blur":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"text-translate":{"type":"array","value":"number","length":2,"default":[0,0],"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"text-translate-anchor":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":["zoom"]}},"icon-color-saturation":{"type":"number","default":0,"minimum":-1,"maximum":1,"expression":{}},"icon-color-contrast":{"type":"number","default":0,"minimum":-1,"maximum":1,"expression":{}},"icon-color-brightness-min":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{}},"icon-color-brightness-max":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{}},"symbol-z-offset":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature"]},"property-type":"data-driven"}},"paint_raster":{"raster-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-color":{"type":"color","use-theme":true,"expression":{"interpolated":true,"parameters":["raster-value"]}},"raster-color-mix":{"type":"array","default":[0.2126,0.7152,0.0722,0],"length":4,"value":"number","transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-color-range":{"type":"array","length":2,"value":"number","transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-hue-rotate":{"type":"number","default":0,"period":360,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-brightness-min":{"type":"number","default":0,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-brightness-max":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-saturation":{"type":"number","default":0,"minimum":-1,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-contrast":{"type":"number","default":0,"minimum":-1,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-resampling":{"type":"enum","values":{"linear":1,"nearest":1},"default":"linear","expression":{"parameters":["zoom"]}},"raster-fade-duration":{"type":"number","default":300,"minimum":0,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-emissive-strength":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"raster-array-band":{"type":"string"},"raster-elevation":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}}},"paint_raster-particle":{"raster-particle-array-band":{"type":"string"},"raster-particle-count":{"type":"number","default":512,"minimum":1},"raster-particle-color":{"type":"color","use-theme":true,"expression":{"interpolated":true,"parameters":["raster-particle-speed"]}},"raster-particle-max-speed":{"type":"number","default":1,"minimum":1},"raster-particle-speed-factor":{"type":"number","default":0.2,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-particle-fade-opacity-factor":{"type":"number","default":0.98,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-particle-reset-rate-factor":{"type":"number","default":0.8,"minimum":0,"maximum":1},"raster-particle-elevation":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}}},"paint_hillshade":{"hillshade-illumination-direction":{"type":"number","default":335,"minimum":0,"maximum":359,"expression":{"interpolated":true,"parameters":["zoom"]}},"hillshade-illumination-anchor":{"type":"enum","values":{"map":1,"viewport":1},"default":"viewport","expression":{"parameters":["zoom"]}},"hillshade-exaggeration":{"type":"number","default":0.5,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"hillshade-shadow-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"hillshade-highlight-color":{"type":"color","default":"#FFFFFF","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"hillshade-accent-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"hillshade-emissive-strength":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}}},"paint_background":{"background-pitch-alignment":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":[]}},"background-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"background-pattern":{"type":"resolvedImage","expression":{"parameters":["zoom"]}},"background-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"background-emissive-strength":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}}},"paint_sky":{"sky-type":{"type":"enum","values":{"gradient":1,"atmosphere":1},"default":"atmosphere","expression":{"parameters":["zoom"]}},"sky-atmosphere-sun":{"type":"array","value":"number","length":2,"minimum":[0,0],"maximum":[360,180],"expression":{"parameters":["zoom"]}},"sky-atmosphere-sun-intensity":{"type":"number","default":10,"minimum":0,"maximum":100},"sky-gradient-center":{"type":"array","value":"number","default":[0,0],"length":2,"minimum":[0,0],"maximum":[360,180],"expression":{"parameters":["zoom"]}},"sky-gradient-radius":{"type":"number","default":90,"minimum":0,"maximum":180,"expression":{"parameters":["zoom"]}},"sky-gradient":{"type":"color","default":["interpolate",["linear"],["sky-radial-progress"],0.8,"#87ceeb",1,"white"],"use-theme":true,"expression":{"interpolated":true,"parameters":["sky-radial-progress"]}},"sky-atmosphere-halo-color":{"type":"color","default":"white","use-theme":true},"sky-atmosphere-color":{"type":"color","default":"white","use-theme":true},"sky-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}}},"paint_model":{"model-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["feature","feature-state","zoom"]},"property-type":"data-driven"},"model-rotation":{"type":"array","value":"number","length":3,"default":[0,0,0],"period":360,"property-type":"data-driven","expression":{"interpolated":true,"parameters":["feature","feature-state","zoom"]},"transition":true},"model-scale":{"type":"array","value":"number","length":3,"default":[1,1,1],"property-type":"data-driven","expression":{"interpolated":true,"parameters":["feature","feature-state","zoom"]},"transition":true},"model-translation":{"type":"array","value":"number","length":3,"default":[0,0,0],"property-type":"data-driven","expression":{"interpolated":true,"parameters":["feature","feature-state","zoom"]},"transition":true},"model-color":{"type":"color","default":"#ffffff","property-type":"data-driven","expression":{"interpolated":true,"parameters":["feature","feature-state","measure-light","zoom"]},"use-theme":true,"transition":true},"model-color-mix-intensity":{"type":"number","property-type":"data-driven","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["feature","feature-state","measure-light"]},"transition":true},"model-type":{"type":"enum","values":{"common-3d":1,"location-indicator":1},"default":"common-3d"},"model-cast-shadows":{"type":"boolean","default":true},"model-receive-shadows":{"type":"boolean","default":true},"model-ambient-occlusion-intensity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"model-emissive-strength":{"type":"number","property-type":"data-driven","default":0,"minimum":0,"maximum":5,"expression":{"interpolated":true,"parameters":["feature","feature-state","measure-light"]},"transition":true},"model-roughness":{"type":"number","default":1,"minimum":0,"maximum":1,"property-type":"data-driven","expression":{"interpolated":true,"parameters":["feature","feature-state"]},"transition":true},"model-height-based-emissive-strength-multiplier":{"type":"array","default":[1,1,1,1,0],"length":5,"value":"number","property-type":"data-driven","expression":{"interpolated":true,"parameters":["feature","feature-state","measure-light"]},"transition":true},"model-cutoff-fade-range":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{}},"model-front-cutoff":{"type":"array","value":"number","expression":{"interpolated":true,"parameters":["zoom"]},"length":3,"default":[0,0,1],"minimum":[0,0,0],"maximum":[1,1,1]},"model-elevation-reference":{"type":"enum","values":{"sea":1,"ground":1,"hd-road-markup":1},"default":"ground","expression":{}}},"transition":{"duration":{"type":"number","default":300,"minimum":0},"delay":{"type":"number","default":0,"minimum":0}},"promoteId":{"*":{"type":"*"}}}');function zE(h){return h instanceof Number||h instanceof String||h instanceof Boolean?h.valueOf():h}function ob(h){if(Array.isArray(h))return h.map(ob);if(h instanceof Object&&!(h instanceof Number||h instanceof String||h instanceof Boolean)){const l={};for(const d in h)l[d]=ob(h[d]);return l}return zE(h)}function Ld(h){if(h===!0||h===!1)return!0;if(!Array.isArray(h)||h.length===0)return!1;switch(h[0]){case"has":return h.length>=2&&h[1]!=="$id"&&h[1]!=="$type";case"in":return h.length>=3&&(typeof h[1]!="string"||Array.isArray(h[2]));case"!in":case"!has":case"none":return!1;case"==":case"!=":case">":case">=":case"<":case"<=":return h.length!==3||Array.isArray(h[1])||Array.isArray(h[2]);case"any":case"all":for(const l of h.slice(1))if(!Ld(l)&&typeof l!="boolean")return!1;return!0;default:return!0}}function lb(h,l="",d=null,p="fill"){if(h==null)return{filter:()=>!0,needGeometry:!1,needFeature:!1};Ld(h)||(h=cb(h));const y=h;let b=!0;try{b=function($){if(!Eg($))return $;let U=ob($);return BE(U),U=tm(U),U}(y)}catch{console.warn(`Failed to extract static filter. Filter will continue working, but at higher memory usage and slower framerate. This is most likely a bug, please report this via https://github.com/mapbox/mapbox-gl-js/issues/new?assignees=&labels=&template=Bug_report.md and paste the contents of this message in the report. Thank you! Filter Expression: ${JSON.stringify(y,null,2)} `)}let w=null,k=null;if(p!=="background"&&p!=="sky"&&p!=="slot"){k=yt[`filter_${p}`];const $=qf(b,k,l,d);if($.result==="error")throw new Error($.value.map(U=>`${U.key}: ${U.message}`).join(", "));w=(U,H,Z)=>$.value.evaluate(U,H,{},Z)}let M=null,F=null;if(b!==y){const $=qf(y,k,l,d);if($.result==="error")throw new Error($.value.map(U=>`${U.key}: ${U.message}`).join(", "));M=(U,H,Z,Y,ne)=>$.value.evaluate(U,H,{},Z,void 0,void 0,Y,ne),F=!vg($.value.expression)}return{filter:w,dynamicFilter:M||void 0,needGeometry:$E(b),needFeature:!!F}}function tm(h){if(!Array.isArray(h))return h;const l=function(d){if(N4.has(d[0])){for(let p=1;ptm(d))}function BE(h){let l=!1;const d=[];if(h[0]==="case"){for(let p=1;p",">=","<","<=","to-boolean"]);function C4(h,l){return hl?1:0}function $E(h){if(!Array.isArray(h))return!1;if(h[0]==="within"||h[0]==="distance")return!0;for(let l=1;l"||l==="<="||l===">="?ub(h[1],h[2],l):l==="any"?(d=h.slice(1),["any"].concat(d.map(cb))):l==="all"?["all"].concat(h.slice(1).map(cb)):l==="none"?["all"].concat(h.slice(1).map(cb).map(av)):l==="in"?db(h[1],h.slice(2)):l==="!in"?av(db(h[1],h.slice(2))):l==="has"?hb(h[1]):l!=="!has"||av(hb(h[1]));var d}function ub(h,l,d){switch(h){case"$type":return[`filter-type-${d}`,l];case"$id":return[`filter-id-${d}`,l];default:return[`filter-${d}`,h,l]}}function db(h,l){if(l.length===0)return!1;switch(h){case"$type":return["filter-type-in",["literal",l]];case"$id":return["filter-id-in",["literal",l]];default:return l.length>200&&!l.some(d=>typeof d!=typeof l[0])?["filter-in-large",h,["literal",l.sort(C4)]]:["filter-in-small",h,["literal",l]]}}function hb(h){switch(h){case"$type":return!0;case"$id":return["filter-has-id"];default:return["filter-has",h]}}function av(h){return["!",h]}const rm="";function Ju(h,l){return l?`${h}${rm}${l}`:h}let UE;const VE=()=>UE||(UE=new ta({"icon-size":new br(yt.layout_symbol["icon-size"]),"icon-image":new br(yt.layout_symbol["icon-image"]),"icon-rotate":new br(yt.layout_symbol["icon-rotate"]),"icon-offset":new br(yt.layout_symbol["icon-offset"]),"text-size":new br(yt.layout_symbol["text-size"]),"text-rotate":new br(yt.layout_symbol["text-rotate"]),"text-offset":new br(yt.layout_symbol["text-offset"])}));class qE{constructor(l,d,p,y,b,w){const k=qf(l,yt.appearance.condition);if(k.result==="success"&&(this.condition=k.value),this.name=d,p){this.properties=new Jp(VE()),this.unevaluatedLayout=new FE(VE(),y,b,w);for(const M in p)this.unevaluatedLayout.setValue(M,p[M])}}isActive(l){return!(this.condition||!l.isHidden||this.name!=="hidden")||this.condition.evaluate(l.globals,l.feature,l.featureState,l.canonical)}getCondition(){return this.condition}getName(){return this.name}getProperty(l){return this.properties.get(l)}getUnevaluatedProperties(){return this.unevaluatedLayout}getUnevaluatedProperty(l){return this.unevaluatedLayout._values[l]}recalculate(l,d,p){this.unevaluatedLayout&&(this.properties=this.unevaluatedLayout.possiblyEvaluate(l,void 0,d,p))}serialize(){const l={};return l.condition=this.condition.expression.serialize(),this.name&&(l.name=this.name),this.unevaluatedLayout&&(l.properties=this.unevaluatedLayout.serialize()),l}hasIconProperties(){const l=this.hasProperty("icon-image"),d=this.hasProperty("icon-size"),p=this.hasProperty("icon-offset"),y=this.hasProperty("icon-rotate");return l||d||p||y}hasTextProperties(){const l=this.hasProperty("text-size"),d=this.hasProperty("text-offset"),p=this.hasProperty("text-rotate");return l||d||p}hasProperty(l){return this.getUnevaluatedProperty(l).value!==void 0}}const HE="-transition",Fd=new Set(["fill","line","background","hillshade","raster"]);class Dl extends qp{constructor(l,d,p,y,b,w){if(super(),this.id=l.id,this.fqid=Ju(this.id,p),this.type=l.type,this.scope=p,this.lut=y,this.options=b,this.iconImageUseTheme=w,this.appearances=new Array,this._featureFilter={filter:()=>!0,needGeometry:!1,needFeature:!1},this._filterCompiled=!1,this.expressionDependencies={isIndoorDependent:!1,configDependencies:new Set},l.type!=="custom"){if(this.metadata=l.metadata,this.minzoom=l.minzoom,this.maxzoom=l.maxzoom,l.type&&l.type!=="background"&&l.type!=="sky"&&l.type!=="slot"){this.source=l.source,this.sourceLayer=l["source-layer"],this.filter=l.filter;const k=qf(this.filter,yt[`filter_${l.type}`]);k.result!=="error"&&(this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...k.value.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||k.value.isIndoorDependent)}if(l.slot&&(this.slot=l.slot),l.appearances&&this.setAppearances(l.appearances),d.layout&&(this._unevaluatedLayout=new FE(d.layout,this.scope,b,this.iconImageUseTheme),this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...this._unevaluatedLayout.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||this._unevaluatedLayout.isIndoorDependent()),d.paint){this._transitionablePaint=new RE(d.paint,this.scope,b);for(const k in l.paint)this.setPaintProperty(k,l.paint[k]);for(const k in l.layout)this.setLayoutProperty(k,l.layout[k]);this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...this._transitionablePaint.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||this._transitionablePaint.isIndoorDependent(),this._transitioningPaint=this._transitionablePaint.untransitioned(),this.paint=new Jp(d.paint)}}}onAdd(l){}onRemove(l){}isDraped(l){return!this.is3D(!0)&&Fd.has(this.type)}getLayoutProperty(l){return l==="visibility"?this.visibility:this._unevaluatedLayout.getValue(l)}setLayoutProperty(l,d){if(this.type==="custom"&&l==="visibility")return void(this.visibility=d);const p=this._unevaluatedLayout;p._properties.properties[l]&&(p.setValue(l,d),this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...p.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||p.isIndoorDependent(),l==="visibility"&&this.possiblyEvaluateVisibility())}setAppearances(l){this.appearances=[],l.forEach(d=>{this.appearances.push(new qE(d.condition,d.name,d.properties,this.scope,this.options,this.iconImageUseTheme))})}possiblyEvaluateVisibility(){this._unevaluatedLayout._values.visibility&&(this.visibility=this._unevaluatedLayout._values.visibility.possiblyEvaluate({zoom:0}))}getPaintProperty(l){return l.endsWith(HE)?this._transitionablePaint.getTransition(l.slice(0,-11)):this._transitionablePaint.getValue(l)}isPaintProperty(l){return!!this._transitionablePaint._properties.properties[l]}setPaintProperty(l,d){const p=this._transitionablePaint,y=p._properties.properties;if(l.endsWith(HE)){const U=l.slice(0,-11);return y[U]&&p.setTransition(U,d||void 0),!1}if(!y[l])return!1;const b=p._values[l],w=b.value.isDataDriven(),k=b.value;p.setValue(l,d),this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...p.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||p.isIndoorDependent(),this._handleSpecialPaintPropertyUpdate(l);const M=p._values[l].value,F=M.isDataDriven(),$=l.endsWith("pattern")||l==="line-dasharray";return F||w||$||this._handleOverridablePaintPropertyUpdate(l,k,M)}_handleSpecialPaintPropertyUpdate(l){}getProgramIds(){return null}getDefaultProgramParams(l,d,p){return null}_handleOverridablePaintPropertyUpdate(l,d,p){return!1}isHidden(l){return!!(this.minzoom&&l=this.maxzoom)||this.visibility==="none"}updateTransitions(l){this._transitioningPaint=this._transitionablePaint.transitioned(l,this._transitioningPaint)}hasTransition(){return this._transitioningPaint.hasTransition()}recalculate(l,d){this._unevaluatedLayout&&(this.layout=this._unevaluatedLayout.possiblyEvaluate(l,void 0,d,this.iconImageUseTheme)),this.paint=this._transitioningPaint.possiblyEvaluate(l,void 0,d)}serialize(){const l={id:this.id,type:this.type,slot:this.slot,source:this.source,"source-layer":this.sourceLayer,metadata:this.metadata,minzoom:this.minzoom,maxzoom:this.maxzoom,filter:this.filter,layout:this._unevaluatedLayout&&this._unevaluatedLayout.serialize(),paint:this._transitionablePaint&&this._transitionablePaint.serialize()};return this.appearances.length!==0&&(l.appearances=this.appearances.map(d=>d.serialize())),sr(l,(d,p)=>!(d===void 0||p==="layout"&&!Object.keys(d).length||p==="paint"&&!Object.keys(d).length))}is3D(l){return!1}hasElevation(){return!1}isSky(){return!1}isTileClipped(){return!1}hasOffscreenPass(){return!1}hasShadowPass(){return!1}canCastShadows(){return!1}hasLightBeamPass(){return!1}cutoffRange(){return 0}tileCoverLift(){return 0}resize(){}_clear(){}isStateDependent(){for(const l in this.paint._values){const d=this.paint.get(l);if(d instanceof Qp&&ev(d.property.specification)&&(d.value.kind==="source"||d.value.kind==="composite")&&d.value.isStateDependent)return!0}for(const l of this.appearances)if(!Kx(l.condition.expression))return!0;return!1}compileFilter(l){this._filterCompiled||(this._featureFilter=lb(this.filter,this.scope,l),this._filterCompiled=!0)}invalidateCompiledFilter(){this._filterCompiled=!1}dynamicFilter(){return this._featureFilter.dynamicFilter}dynamicFilterNeedsFeature(){return this._featureFilter.needFeature}getLayerRenderingStats(){return this._stats}resetLayerRenderingStats(l){this._stats&&(l.renderPass==="shadow"?this._stats.numRenderedVerticesInShadowPass=0:this._stats.numRenderedVerticesInTransparentPass=0)}getAppearances(){return this.appearances}queryRenderedFeatures(l,d,p){return{}}queryRadius(l){}queryIntersectsFeature(l,d,p,y,b,w,k,M,F){}}const WE={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array};class ov{constructor(l,d){this._structArray=l,this._pos1=d*this.size,this._pos2=this._pos1/2,this._pos4=this._pos1/4,this._pos8=this._pos1/8}}const k4=new ArrayBuffer(0);class Di{constructor(){this._reallocCount=0,this.capacity=0,this.length=0}static serialize(l,d){return l._trim(),d&&l.arrayBuffer&&d.add(l.arrayBuffer),{length:l.length,arrayBuffer:l.arrayBuffer}}static deserialize(l){const d=Object.create(this.prototype);return d.arrayBuffer=l.arrayBuffer,d.length=l.length,l.arrayBuffer?d.capacity=l.arrayBuffer.byteLength/d.bytesPerElement:(d.capacity=0,d.arrayBuffer=k4),d._refreshViews(),d}_trim(){this.length!==this.capacity&&(this.capacity=this.length,this.arrayBuffer=this.arrayBuffer.slice(0,this.length*this.bytesPerElement),this._refreshViews())}clear(){this.length=0}resize(l){this.reserve(l),this.length=l}reserve(l){if(l>this.capacity){this._reallocCount++,this.capacity=Math.max(l,Math.floor(5*this.capacity),128),this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);const d=this.uint8;this._refreshViews(),d&&this.uint8.set(d)}}reserveForAdditional(l){this.reserve(this.length+l)}_refreshViews(){throw new Error("StructArray#_refreshViews() must be implemented by each concrete StructArray layout")}emplace(...l){throw new Error("StructArray#emplace() must be implemented by each concrete StructArray layout")}emplaceBack(...l){throw new Error("StructArray#emplaceBack() must be implemented by each concrete StructArray layout")}destroy(){this.int8=this.uint8=this.int16=this.uint16=this.int32=this.uint32=this.float32=null,this.arrayBuffer=null}}function ts(h,l=1){let d=0,p=0;return{members:h.map(y=>{const b=WE[y.type].BYTES_PER_ELEMENT,w=d=GE(d,Math.max(l,b)),k=y.components||1;return p=Math.max(p,b),d+=b*k,{name:y.name,type:y.type,components:k,offset:w}}),size:GE(d,Math.max(p,l)),alignment:l}}function GE(h,l){return Math.ceil(h/l)*l}class Wf extends Di{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(l,d){const p=this.length;return this.resize(p+1),this.emplace(p,l,d)}emplace(l,d,p){const y=2*l;return this.int16[y+0]=d,this.int16[y+1]=p,l}}Wf.prototype.bytesPerElement=4,Lr(Wf,"StructArrayLayout2i4");class Ag extends Di{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(l,d,p){const y=this.length;return this.resize(y+1),this.emplace(y,l,d,p)}emplace(l,d,p,y){const b=3*l;return this.int16[b+0]=d,this.int16[b+1]=p,this.int16[b+2]=y,l}}Ag.prototype.bytesPerElement=6,Lr(Ag,"StructArrayLayout3i6");class Pg extends Di{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(l,d,p,y){const b=this.length;return this.resize(b+1),this.emplace(b,l,d,p,y)}emplace(l,d,p,y,b){const w=4*l;return this.int16[w+0]=d,this.int16[w+1]=p,this.int16[w+2]=y,this.int16[w+3]=b,l}}Pg.prototype.bytesPerElement=8,Lr(Pg,"StructArrayLayout4i8");class Mh extends Di{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l){const d=this.length;return this.resize(d+1),this.emplace(d,l)}emplace(l,d){return this.float32[1*l+0]=d,l}}Mh.prototype.bytesPerElement=4,Lr(Mh,"StructArrayLayout1f4");class GS extends Di{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,d,p){const y=this.length;return this.resize(y+1),this.emplace(y,l,d,p)}emplace(l,d,p,y){const b=4*l,w=2*l;return this.int16[b+0]=d,this.int16[b+1]=p,this.float32[w+1]=y,l}}GS.prototype.bytesPerElement=8,Lr(GS,"StructArrayLayout2i1f8");class KS extends Di{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(l,d,p){const y=this.length;return this.resize(y+1),this.emplace(y,l,d,p)}emplace(l,d,p,y){const b=4*l;return this.int16[b+0]=d,this.int16[b+1]=p,this.int16[b+2]=y,l}}KS.prototype.bytesPerElement=8,Lr(KS,"StructArrayLayout3i8");class ZS extends Di{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(l,d,p,y,b){const w=this.length;return this.resize(w+1),this.emplace(w,l,d,p,y,b)}emplace(l,d,p,y,b,w){const k=5*l;return this.int16[k+0]=d,this.int16[k+1]=p,this.int16[k+2]=y,this.int16[k+3]=b,this.int16[k+4]=w,l}}ZS.prototype.bytesPerElement=10,Lr(ZS,"StructArrayLayout5i10");class fb extends Di{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,d,p,y,b,w,k){const M=this.length;return this.resize(M+1),this.emplace(M,l,d,p,y,b,w,k)}emplace(l,d,p,y,b,w,k,M){const F=6*l,$=12*l,U=3*l;return this.int16[F+0]=d,this.int16[F+1]=p,this.uint8[$+4]=y,this.uint8[$+5]=b,this.uint8[$+6]=w,this.uint8[$+7]=k,this.float32[U+2]=M,l}}fb.prototype.bytesPerElement=12,Lr(fb,"StructArrayLayout2i4ub1f12");class Vc extends Di{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,d,p){const y=this.length;return this.resize(y+1),this.emplace(y,l,d,p)}emplace(l,d,p,y){const b=3*l;return this.float32[b+0]=d,this.float32[b+1]=p,this.float32[b+2]=y,l}}Vc.prototype.bytesPerElement=12,Lr(Vc,"StructArrayLayout3f12");class ic extends Di{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,d,p,y,b){const w=this.length;return this.resize(w+1),this.emplace(w,l,d,p,y,b)}emplace(l,d,p,y,b,w){const k=6*l,M=3*l;return this.uint16[k+0]=d,this.uint16[k+1]=p,this.uint16[k+2]=y,this.uint16[k+3]=b,this.float32[M+2]=w,l}}ic.prototype.bytesPerElement=12,Lr(ic,"StructArrayLayout4ui1f12");class nm extends Di{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(l,d,p,y){const b=this.length;return this.resize(b+1),this.emplace(b,l,d,p,y)}emplace(l,d,p,y,b){const w=4*l;return this.uint16[w+0]=d,this.uint16[w+1]=p,this.uint16[w+2]=y,this.uint16[w+3]=b,l}}nm.prototype.bytesPerElement=8,Lr(nm,"StructArrayLayout4ui8");class pb extends Di{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(l,d,p,y,b,w){const k=this.length;return this.resize(k+1),this.emplace(k,l,d,p,y,b,w)}emplace(l,d,p,y,b,w,k){const M=6*l;return this.int16[M+0]=d,this.int16[M+1]=p,this.int16[M+2]=y,this.int16[M+3]=b,this.int16[M+4]=w,this.int16[M+5]=k,l}}pb.prototype.bytesPerElement=12,Lr(pb,"StructArrayLayout6i12");class YS extends Di{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(l,d,p,y,b,w,k,M,F,$,U,H){const Z=this.length;return this.resize(Z+1),this.emplace(Z,l,d,p,y,b,w,k,M,F,$,U,H)}emplace(l,d,p,y,b,w,k,M,F,$,U,H,Z){const Y=12*l;return this.int16[Y+0]=d,this.int16[Y+1]=p,this.int16[Y+2]=y,this.int16[Y+3]=b,this.uint16[Y+4]=w,this.uint16[Y+5]=k,this.uint16[Y+6]=M,this.uint16[Y+7]=F,this.int16[Y+8]=$,this.int16[Y+9]=U,this.int16[Y+10]=H,this.int16[Y+11]=Z,l}}YS.prototype.bytesPerElement=24,Lr(YS,"StructArrayLayout4i4ui4i24");class XS extends Di{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,d,p,y,b,w){const k=this.length;return this.resize(k+1),this.emplace(k,l,d,p,y,b,w)}emplace(l,d,p,y,b,w,k){const M=10*l,F=5*l;return this.int16[M+0]=d,this.int16[M+1]=p,this.int16[M+2]=y,this.float32[F+2]=b,this.float32[F+3]=w,this.float32[F+4]=k,l}}XS.prototype.bytesPerElement=20,Lr(XS,"StructArrayLayout3i3f20");class Gf extends Di{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,d,p,y){const b=this.length;return this.resize(b+1),this.emplace(b,l,d,p,y)}emplace(l,d,p,y,b){const w=4*l;return this.float32[w+0]=d,this.float32[w+1]=p,this.float32[w+2]=y,this.float32[w+3]=b,l}}Gf.prototype.bytesPerElement=16,Lr(Gf,"StructArrayLayout4f16");class mb extends Di{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer)}emplaceBack(l){const d=this.length;return this.resize(d+1),this.emplace(d,l)}emplace(l,d){return this.uint32[1*l+0]=d,l}}mb.prototype.bytesPerElement=4,Lr(mb,"StructArrayLayout1ul4");class qc extends Di{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(l,d){const p=this.length;return this.resize(p+1),this.emplace(p,l,d)}emplace(l,d,p){const y=2*l;return this.uint16[y+0]=d,this.uint16[y+1]=p,l}}qc.prototype.bytesPerElement=4,Lr(qc,"StructArrayLayout2ui4");class gb extends Di{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(l,d,p,y,b,w,k,M,F,$,U,H,Z){const Y=this.length;return this.resize(Y+1),this.emplace(Y,l,d,p,y,b,w,k,M,F,$,U,H,Z)}emplace(l,d,p,y,b,w,k,M,F,$,U,H,Z,Y){const ne=20*l,ce=10*l;return this.int16[ne+0]=d,this.int16[ne+1]=p,this.int16[ne+2]=y,this.int16[ne+3]=b,this.int16[ne+4]=w,this.float32[ce+3]=k,this.float32[ce+4]=M,this.float32[ce+5]=F,this.float32[ce+6]=$,this.int16[ne+14]=U,this.uint32[ce+8]=H,this.uint16[ne+18]=Z,this.uint16[ne+19]=Y,l}}gb.prototype.bytesPerElement=40,Lr(gb,"StructArrayLayout5i4f1i1ul2ui40");class yb extends Di{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(l,d,p,y,b,w,k){const M=this.length;return this.resize(M+1),this.emplace(M,l,d,p,y,b,w,k)}emplace(l,d,p,y,b,w,k,M){const F=8*l;return this.int16[F+0]=d,this.int16[F+1]=p,this.int16[F+2]=y,this.int16[F+4]=b,this.int16[F+5]=w,this.int16[F+6]=k,this.int16[F+7]=M,l}}yb.prototype.bytesPerElement=16,Lr(yb,"StructArrayLayout3i2i2i16");class xb extends Di{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(l,d,p,y,b){const w=this.length;return this.resize(w+1),this.emplace(w,l,d,p,y,b)}emplace(l,d,p,y,b,w){const k=4*l,M=8*l;return this.float32[k+0]=d,this.float32[k+1]=p,this.float32[k+2]=y,this.int16[M+6]=b,this.int16[M+7]=w,l}}xb.prototype.bytesPerElement=16,Lr(xb,"StructArrayLayout2f1f2i16");class QS extends Di{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,d,p,y,b,w){const k=this.length;return this.resize(k+1),this.emplace(k,l,d,p,y,b,w)}emplace(l,d,p,y,b,w,k){const M=20*l,F=5*l;return this.uint8[M+0]=d,this.uint8[M+1]=p,this.float32[F+1]=y,this.float32[F+2]=b,this.float32[F+3]=w,this.float32[F+4]=k,l}}QS.prototype.bytesPerElement=20,Lr(QS,"StructArrayLayout2ub4f20");class Fa extends Di{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(l,d,p){const y=this.length;return this.resize(y+1),this.emplace(y,l,d,p)}emplace(l,d,p,y){const b=3*l;return this.uint16[b+0]=d,this.uint16[b+1]=p,this.uint16[b+2]=y,l}}Fa.prototype.bytesPerElement=6,Lr(Fa,"StructArrayLayout3ui6");class Ig extends Di{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer)}emplaceBack(l,d,p,y,b,w,k,M,F,$,U,H,Z,Y,ne,ce,le,ye,we,Ee,Ue){const Le=this.length;return this.resize(Le+1),this.emplace(Le,l,d,p,y,b,w,k,M,F,$,U,H,Z,Y,ne,ce,le,ye,we,Ee,Ue)}emplace(l,d,p,y,b,w,k,M,F,$,U,H,Z,Y,ne,ce,le,ye,we,Ee,Ue,Le){const Ke=30*l,Je=15*l,it=60*l;return this.int16[Ke+0]=d,this.int16[Ke+1]=p,this.int16[Ke+2]=y,this.float32[Je+2]=b,this.float32[Je+3]=w,this.uint16[Ke+8]=k,this.uint16[Ke+9]=M,this.uint32[Je+5]=F,this.uint32[Je+6]=$,this.uint32[Je+7]=U,this.uint16[Ke+16]=H,this.uint16[Ke+17]=Z,this.uint16[Ke+18]=Y,this.float32[Je+10]=ne,this.float32[Je+11]=ce,this.uint8[it+48]=le,this.uint8[it+49]=ye,this.uint8[it+50]=we,this.uint32[Je+13]=Ee,this.int16[Ke+28]=Ue,this.uint8[it+58]=Le,l}}Ig.prototype.bytesPerElement=60,Lr(Ig,"StructArrayLayout3i2f2ui3ul3ui2f3ub1ul1i1ub60");class JS extends Di{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer)}emplaceBack(l,d,p,y,b,w,k,M,F,$,U,H,Z,Y,ne,ce,le,ye,we,Ee,Ue,Le,Ke,Je,it,Pt,ft,Ft,Vt,qt,er,nr,Yt){const Xt=this.length;return this.resize(Xt+1),this.emplace(Xt,l,d,p,y,b,w,k,M,F,$,U,H,Z,Y,ne,ce,le,ye,we,Ee,Ue,Le,Ke,Je,it,Pt,ft,Ft,Vt,qt,er,nr,Yt)}emplace(l,d,p,y,b,w,k,M,F,$,U,H,Z,Y,ne,ce,le,ye,we,Ee,Ue,Le,Ke,Je,it,Pt,ft,Ft,Vt,qt,er,nr,Yt,Xt){const Rt=20*l,It=40*l,Jt=80*l;return this.float32[Rt+0]=d,this.float32[Rt+1]=p,this.int16[It+4]=y,this.int16[It+5]=b,this.int16[It+6]=w,this.int16[It+7]=k,this.int16[It+8]=M,this.int16[It+9]=F,this.int16[It+10]=$,this.int16[It+11]=U,this.int16[It+12]=H,this.uint16[It+13]=Z,this.uint16[It+14]=Y,this.uint16[It+15]=ne,this.uint16[It+16]=ce,this.uint16[It+17]=le,this.uint16[It+18]=ye,this.uint16[It+19]=we,this.uint16[It+20]=Ee,this.uint16[It+21]=Ue,this.uint16[It+22]=Le,this.uint16[It+23]=Ke,this.uint16[It+24]=Je,this.uint16[It+25]=it,this.uint16[It+26]=Pt,this.uint16[It+27]=ft,this.uint32[Rt+14]=Ft,this.float32[Rt+15]=Vt,this.float32[Rt+16]=qt,this.float32[Rt+17]=er,this.float32[Rt+18]=nr,this.uint8[Jt+76]=Yt,this.uint16[It+39]=Xt,l}}JS.prototype.bytesPerElement=80,Lr(JS,"StructArrayLayout2f9i15ui1ul4f1ub1ui80");class eN extends Di{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,d,p,y,b,w){const k=this.length;return this.resize(k+1),this.emplace(k,l,d,p,y,b,w)}emplace(l,d,p,y,b,w,k){const M=6*l;return this.float32[M+0]=d,this.float32[M+1]=p,this.float32[M+2]=y,this.float32[M+3]=b,this.float32[M+4]=w,this.float32[M+5]=k,l}}eN.prototype.bytesPerElement=24,Lr(eN,"StructArrayLayout6f24");class sm extends Di{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,d,p,y,b){const w=this.length;return this.resize(w+1),this.emplace(w,l,d,p,y,b)}emplace(l,d,p,y,b,w){const k=5*l;return this.float32[k+0]=d,this.float32[k+1]=p,this.float32[k+2]=y,this.float32[k+3]=b,this.float32[k+4]=w,l}}sm.prototype.bytesPerElement=20,Lr(sm,"StructArrayLayout5f20");class tN extends Di{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,d,p,y,b,w,k){const M=this.length;return this.resize(M+1),this.emplace(M,l,d,p,y,b,w,k)}emplace(l,d,p,y,b,w,k,M){const F=7*l;return this.float32[F+0]=d,this.float32[F+1]=p,this.float32[F+2]=y,this.float32[F+3]=b,this.float32[F+4]=w,this.float32[F+5]=k,this.float32[F+6]=M,l}}tN.prototype.bytesPerElement=28,Lr(tN,"StructArrayLayout7f28");class rN extends Di{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,d,p,y,b,w,k,M,F,$,U){const H=this.length;return this.resize(H+1),this.emplace(H,l,d,p,y,b,w,k,M,F,$,U)}emplace(l,d,p,y,b,w,k,M,F,$,U,H){const Z=11*l;return this.float32[Z+0]=d,this.float32[Z+1]=p,this.float32[Z+2]=y,this.float32[Z+3]=b,this.float32[Z+4]=w,this.float32[Z+5]=k,this.float32[Z+6]=M,this.float32[Z+7]=F,this.float32[Z+8]=$,this.float32[Z+9]=U,this.float32[Z+10]=H,l}}rN.prototype.bytesPerElement=44,Lr(rN,"StructArrayLayout11f44");class Mg extends Di{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,d,p,y,b,w,k,M,F){const $=this.length;return this.resize($+1),this.emplace($,l,d,p,y,b,w,k,M,F)}emplace(l,d,p,y,b,w,k,M,F,$){const U=9*l;return this.float32[U+0]=d,this.float32[U+1]=p,this.float32[U+2]=y,this.float32[U+3]=b,this.float32[U+4]=w,this.float32[U+5]=k,this.float32[U+6]=M,this.float32[U+7]=F,this.float32[U+8]=$,l}}Mg.prototype.bytesPerElement=36,Lr(Mg,"StructArrayLayout9f36");class zd extends Di{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,d){const p=this.length;return this.resize(p+1),this.emplace(p,l,d)}emplace(l,d,p){const y=2*l;return this.float32[y+0]=d,this.float32[y+1]=p,l}}zd.prototype.bytesPerElement=8,Lr(zd,"StructArrayLayout2f8");class ac extends Di{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(l,d,p,y){const b=this.length;return this.resize(b+1),this.emplace(b,l,d,p,y)}emplace(l,d,p,y,b){const w=6*l;return this.uint32[3*l+0]=d,this.uint16[w+2]=p,this.uint16[w+3]=y,this.uint16[w+4]=b,l}}ac.prototype.bytesPerElement=12,Lr(ac,"StructArrayLayout1ul3ui12");class Kf extends Di{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(l){const d=this.length;return this.resize(d+1),this.emplace(d,l)}emplace(l,d){return this.uint16[1*l+0]=d,l}}Kf.prototype.bytesPerElement=2,Lr(Kf,"StructArrayLayout1ui2");class nN extends Di{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,d,p,y,b,w,k,M,F,$,U,H,Z,Y,ne,ce){const le=this.length;return this.resize(le+1),this.emplace(le,l,d,p,y,b,w,k,M,F,$,U,H,Z,Y,ne,ce)}emplace(l,d,p,y,b,w,k,M,F,$,U,H,Z,Y,ne,ce,le){const ye=16*l;return this.float32[ye+0]=d,this.float32[ye+1]=p,this.float32[ye+2]=y,this.float32[ye+3]=b,this.float32[ye+4]=w,this.float32[ye+5]=k,this.float32[ye+6]=M,this.float32[ye+7]=F,this.float32[ye+8]=$,this.float32[ye+9]=U,this.float32[ye+10]=H,this.float32[ye+11]=Z,this.float32[ye+12]=Y,this.float32[ye+13]=ne,this.float32[ye+14]=ce,this.float32[ye+15]=le,l}}nN.prototype.bytesPerElement=64,Lr(nN,"StructArrayLayout16f64");class vb extends Di{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,d,p,y,b,w,k){const M=this.length;return this.resize(M+1),this.emplace(M,l,d,p,y,b,w,k)}emplace(l,d,p,y,b,w,k,M){const F=10*l,$=5*l;return this.uint16[F+0]=d,this.uint16[F+1]=p,this.uint16[F+2]=y,this.uint16[F+3]=b,this.float32[$+2]=w,this.float32[$+3]=k,this.float32[$+4]=M,l}}vb.prototype.bytesPerElement=20,Lr(vb,"StructArrayLayout4ui3f20");class sN extends Di{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(l){const d=this.length;return this.resize(d+1),this.emplace(d,l)}emplace(l,d){return this.int16[1*l+0]=d,l}}sN.prototype.bytesPerElement=2,Lr(sN,"StructArrayLayout1i2");class _b extends Di{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer)}emplaceBack(l){const d=this.length;return this.resize(d+1),this.emplace(d,l)}emplace(l,d){return this.uint8[1*l+0]=d,l}}_b.prototype.bytesPerElement=1,Lr(_b,"StructArrayLayout1ub1");class bb extends ov{get projectedAnchorX(){return this._structArray.int16[this._pos2+0]}get projectedAnchorY(){return this._structArray.int16[this._pos2+1]}get projectedAnchorZ(){return this._structArray.int16[this._pos2+2]}get tileAnchorX(){return this._structArray.int16[this._pos2+3]}get tileAnchorY(){return this._structArray.int16[this._pos2+4]}get x1(){return this._structArray.float32[this._pos4+3]}get y1(){return this._structArray.float32[this._pos4+4]}get x2(){return this._structArray.float32[this._pos4+5]}get y2(){return this._structArray.float32[this._pos4+6]}get padding(){return this._structArray.int16[this._pos2+14]}get featureIndex(){return this._structArray.uint32[this._pos4+8]}get sourceLayerIndex(){return this._structArray.uint16[this._pos2+18]}get bucketIndex(){return this._structArray.uint16[this._pos2+19]}}bb.prototype.size=40;class KE extends gb{get(l){return new bb(this,l)}}Lr(KE,"CollisionBoxArray");class wb extends ov{get projectedAnchorX(){return this._structArray.int16[this._pos2+0]}get projectedAnchorY(){return this._structArray.int16[this._pos2+1]}get projectedAnchorZ(){return this._structArray.int16[this._pos2+2]}get tileAnchorX(){return this._structArray.float32[this._pos4+2]}get tileAnchorY(){return this._structArray.float32[this._pos4+3]}get glyphStartIndex(){return this._structArray.uint16[this._pos2+8]}get numGlyphs(){return this._structArray.uint16[this._pos2+9]}get vertexStartIndex(){return this._structArray.uint32[this._pos4+5]}get lineStartIndex(){return this._structArray.uint32[this._pos4+6]}get lineLength(){return this._structArray.uint32[this._pos4+7]}get segment(){return this._structArray.uint16[this._pos2+16]}get lowerSize(){return this._structArray.uint16[this._pos2+17]}get upperSize(){return this._structArray.uint16[this._pos2+18]}get lineOffsetX(){return this._structArray.float32[this._pos4+10]}get lineOffsetY(){return this._structArray.float32[this._pos4+11]}get writingMode(){return this._structArray.uint8[this._pos1+48]}get placedOrientation(){return this._structArray.uint8[this._pos1+49]}set placedOrientation(l){this._structArray.uint8[this._pos1+49]=l}get hidden(){return this._structArray.uint8[this._pos1+50]}set hidden(l){this._structArray.uint8[this._pos1+50]=l}get crossTileID(){return this._structArray.uint32[this._pos4+13]}set crossTileID(l){this._structArray.uint32[this._pos4+13]=l}get associatedIconIndex(){return this._structArray.int16[this._pos2+28]}get flipState(){return this._structArray.uint8[this._pos1+58]}set flipState(l){this._structArray.uint8[this._pos1+58]=l}}wb.prototype.size=60;class ZE extends Ig{get(l){return new wb(this,l)}}Lr(ZE,"PlacedSymbolArray");class YE extends ov{get tileAnchorX(){return this._structArray.float32[this._pos4+0]}get tileAnchorY(){return this._structArray.float32[this._pos4+1]}get projectedAnchorX(){return this._structArray.int16[this._pos2+4]}get projectedAnchorY(){return this._structArray.int16[this._pos2+5]}get projectedAnchorZ(){return this._structArray.int16[this._pos2+6]}get rightJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+7]}get centerJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+8]}get leftJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+9]}get verticalPlacedTextSymbolIndex(){return this._structArray.int16[this._pos2+10]}get placedIconSymbolIndex(){return this._structArray.int16[this._pos2+11]}get verticalPlacedIconSymbolIndex(){return this._structArray.int16[this._pos2+12]}get key(){return this._structArray.uint16[this._pos2+13]}get textBoxStartIndex(){return this._structArray.uint16[this._pos2+14]}get textBoxEndIndex(){return this._structArray.uint16[this._pos2+15]}get verticalTextBoxStartIndex(){return this._structArray.uint16[this._pos2+16]}get verticalTextBoxEndIndex(){return this._structArray.uint16[this._pos2+17]}get iconBoxStartIndex(){return this._structArray.uint16[this._pos2+18]}get iconBoxEndIndex(){return this._structArray.uint16[this._pos2+19]}get verticalIconBoxStartIndex(){return this._structArray.uint16[this._pos2+20]}get verticalIconBoxEndIndex(){return this._structArray.uint16[this._pos2+21]}get featureIndex(){return this._structArray.uint16[this._pos2+22]}get numHorizontalGlyphVertices(){return this._structArray.uint16[this._pos2+23]}get numVerticalGlyphVertices(){return this._structArray.uint16[this._pos2+24]}get numIconVertices(){return this._structArray.uint16[this._pos2+25]}get numVerticalIconVertices(){return this._structArray.uint16[this._pos2+26]}get useRuntimeCollisionCircles(){return this._structArray.uint16[this._pos2+27]}get crossTileID(){return this._structArray.uint32[this._pos4+14]}set crossTileID(l){this._structArray.uint32[this._pos4+14]=l}get textOffset0(){return this._structArray.float32[this._pos4+15]}get textOffset1(){return this._structArray.float32[this._pos4+16]}get collisionCircleDiameter(){return this._structArray.float32[this._pos4+17]}get zOffset(){return this._structArray.float32[this._pos4+18]}set zOffset(l){this._structArray.float32[this._pos4+18]=l}get hasIconTextFit(){return this._structArray.uint8[this._pos1+76]}get elevationFeatureIndex(){return this._structArray.uint16[this._pos2+39]}}YE.prototype.size=80;class iN extends JS{get(l){return new YE(this,l)}}Lr(iN,"SymbolInstanceArray");class jb extends Mh{getoffsetX(l){return this.float32[1*l+0]}}Lr(jb,"GlyphOffsetArray");class XE extends Wf{getx(l){return this.int16[2*l+0]}gety(l){return this.int16[2*l+1]}}Lr(XE,"SymbolLineVertexArray");class aN extends ov{get featureIndex(){return this._structArray.uint32[this._pos4+0]}get sourceLayerIndex(){return this._structArray.uint16[this._pos2+2]}get bucketIndex(){return this._structArray.uint16[this._pos2+3]}get layoutVertexArrayOffset(){return this._structArray.uint16[this._pos2+4]}}aN.prototype.size=12;class oN extends ac{get(l){return new aN(this,l)}}Lr(oN,"FeatureIndexArray");class QE extends qc{geta_centroid_pos0(l){return this.uint16[2*l+0]}geta_centroid_pos1(l){return this.uint16[2*l+1]}}Lr(QE,"FillExtrusionCentroidArray");class Sb extends ov{get a_join_normal_inside0(){return this._structArray.int16[this._pos2+0]}get a_join_normal_inside1(){return this._structArray.int16[this._pos2+1]}get a_join_normal_inside2(){return this._structArray.int16[this._pos2+2]}}Sb.prototype.size=6;class lv extends Ag{get(l){return new Sb(this,l)}}Lr(lv,"FillExtrusionWallArray");const JE=ts([{name:"a_pos",components:2,type:"Int16"}],4),T4=ts([{name:"a_circle_z_offset",components:1,type:"Float32"}],4),eA=ts([{name:"a_pos_3",components:3,type:"Int16"},{name:"a_pos_normal_3",components:3,type:"Int16"}]);class Hi{constructor(l=[]){this.segments=l}_prepareSegment(l,d,p,y){let b=this.segments[this.segments.length-1];return l>Hi.MAX_VERTEX_ARRAY_LENGTH&&Ge(`Max vertices per segment is ${Hi.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${l}`),(!b||b.vertexLength+l>Hi.MAX_VERTEX_ARRAY_LENGTH||b.sortKey!==y)&&(b={vertexOffset:d,primitiveOffset:p,vertexLength:0,primitiveLength:0},y!==void 0&&(b.sortKey=y),this.segments.push(b)),b}prepareSegment(l,d,p,y){return this._prepareSegment(l,d.length,p.length,y)}get(){return this.segments}destroy(){for(const l of this.segments)for(const d in l.vaos)l.vaos[d].destroy()}static simpleSegment(l,d,p,y){return new Hi([{vertexOffset:l,primitiveOffset:d,vertexLength:p,primitiveLength:y,vaos:{},sortKey:0}])}}function Nb(h,l){return 256*(h=ue(Math.floor(h),0,255))+ue(Math.floor(l),0,255)}Hi.MAX_VERTEX_ARRAY_LENGTH=Math.pow(2,16)-1,Lr(Hi,"SegmentVector");const E4=ts([{name:"a_pattern",components:4,type:"Uint16"},{name:"a_pixel_ratio",components:1,type:"Float32"}]),A4=ts([{name:"a_pattern_b",components:4,type:"Uint16"}]),P4=ts([{name:"a_dash",components:4,type:"Uint16"}]);class cv{constructor(){this.ids=[],this.uniqueIds=[],this.positions=[],this.indexed=!1}add(l,d,p,y){this.ids.push(lN(l)),this.positions.push(d,p,y)}eachPosition(l,d){const p=lN(l);let y=0,b=this.ids.length-1;for(;y>1;this.ids[w]>=p?b=w:y=w+1}for(;this.ids[y]===p;)d(this.positions[3*y],this.positions[3*y+1],this.positions[3*y+2]),y++}static serialize(l,d){const p=new Float64Array(l.ids),y=new Uint32Array(l.positions);return cN(p,y,0,p.length-1),d&&(d.add(p.buffer),d.add(y.buffer)),{ids:p,positions:y}}static deserialize(l){const d=new cv;let p;d.ids=l.ids,d.positions=l.positions;for(const y of d.ids)y!==p&&d.uniqueIds.push(y),p=y;return d.indexed=!0,d}}function lN(h){const l=+h;return Number.isSafeInteger(l)?l:b0(String(h))}function cN(h,l,d,p){for(;d>1];let b=d-1,w=p+1;for(;;){do b++;while(h[b]y);if(b>=w)break;Cb(h,b,w),Cb(l,3*b,3*w),Cb(l,3*b+1,3*w+1),Cb(l,3*b+2,3*w+2)}w-d`u_${b}`),this.type=p,this.context=y}setUniform(l,d,p,y,b){const w=y.constantOr(this.value);d.set(l,b,w instanceof Us?w.toPremultipliedRenderColor(this.lutExpression&&this.lutExpression.kind==="constant"&&this.lutExpression.value==="none"?null:this.context.lut):w)}getBinding(l,d){return this.type==="color"?new dv(l):new za(l)}}class Og{constructor(l,d){this.uniformNames=d.map(p=>`u_${p}`),this.pattern=null,this.patternTransition=null,this.pixelRatio=1}setConstantPatternPositions(l,d){this.pixelRatio=l.pixelRatio||1,this.pattern=l.tl.concat(l.br),this.patternTransition=d?d.tl.concat(d.br):this.pattern}setUniform(l,d,p,y,b){let w=null;b!=="u_pattern"&&b!=="u_dash"||(w=this.pattern),b==="u_pattern_b"&&(w=this.patternTransition),b==="u_pixel_ratio"&&(w=this.pixelRatio),w&&d.set(l,b,w)}getBinding(l,d){return d==="u_pattern"||d==="u_pattern_b"||d==="u_dash"?new Tb(l):new za(l)}}class Rh{constructor(l,d,p,y){this.expression=l,this.type=p,this.maxValue=0,this.paintVertexAttributes=d.map(b=>({name:`a_${b}`,type:"Float32",components:p==="color"?2:1,offset:0})),this.paintVertexArray=new y}populatePaintArray(l,d,p,y,b,w,k,M){const F=this.paintVertexArray.length,$=this.expression.kind==="composite"||this.expression.kind==="source"?this.expression.evaluate(new wi(0,{brightness:w,worldview:M}),d,{},b,y,k):this.expression.kind==="constant"&&this.expression.value,U=fv(this.lutExpression,d,{},y,b,w,k,M);this.paintVertexArray.resize(l),this._setPaintValue(F,l,$,U?null:this.context.lut)}updatePaintArray(l,d,p,y,b,w,k,M){const F=this.expression.kind==="composite"||this.expression.kind==="source"?this.expression.evaluate({zoom:0,brightness:k,worldview:M},p,y,void 0,b):this.expression.kind==="constant"&&this.expression.value,$=fv(this.lutExpression,p,y,b,void 0,k,void 0,M);this._setPaintValue(l,d,F,$?null:this.context.lut)}_setPaintValue(l,d,p,y){if(this.type==="color"){const b=uN(p.toPremultipliedRenderColor(y));for(let w=l;w`u_${k}_t`),this.type=p,this.useIntegerZoom=y,this.context=b,this.maxValue=0,this.paintVertexAttributes=d.map(k=>({name:`a_${k}`,type:"Float32",components:p==="color"?4:2,offset:0})),this.paintVertexArray=new w}populatePaintArray(l,d,p,y,b,w,k,M){const F=this.expression.evaluate(new wi(this.context.zoom,{brightness:w,worldview:M}),d,{},b,y,k),$=this.expression.evaluate(new wi(this.context.zoom+1,{brightness:w,worldview:M}),d,{},b,y,k),U=fv(this.lutExpression,d,{},y,b,w,k,M),H=this.paintVertexArray.length;this.paintVertexArray.resize(l),this._setPaintValue(H,l,F,$,U?null:this.context.lut)}updatePaintArray(l,d,p,y,b,w,k,M){const F=this.expression.evaluate({zoom:this.context.zoom,brightness:k,worldview:M},p,y,void 0,b),$=this.expression.evaluate({zoom:this.context.zoom+1,brightness:k,worldview:M},p,y,void 0,b),U=fv(this.lutExpression,p,y,b,void 0,k,void 0,M);this._setPaintValue(l,d,F,$,U?null:this.context.lut)}_setPaintValue(l,d,p,y,b){if(this.type==="color"){const w=uN(p.toPremultipliedRenderColor(b)),k=uN(p.toPremultipliedRenderColor(b));for(let M=l;M!0){this.binders={},this._buffers=[],this.context=d;const y=[];for(const b in l.paint._values){const w=l.paint.get(b);if(b.endsWith("-use-theme")||!p(b)||!(w instanceof Qp&&ev(w.property.specification)))continue;const k=R4(b,l.type),M=w.value,F=w.property.specification.type,$=!!w.property.useIntegerZoom,U=b==="line-dasharray"||b.endsWith("pattern"),H=l.paint.get(`${b}-use-theme`),Z=b==="line-dasharray"&&l.layout.get("line-cap").value.kind!=="constant"||H&&H.value.kind!=="constant";if(M.kind!=="constant"||Z)if(M.kind==="source"||Z||U){const Y=dN(b,F,"source");this.binders[b]=U?new Lh(M,k,F,Y,l.id):new Rh(M,k,F,Y),y.push(`/a_${b}`)}else{const Y=dN(b,F,"composite");this.binders[b]=new Dh(M,k,F,$,d,Y),y.push(`/z_${b}`)}else this.binders[b]=U?new Og(M.value,k):new pv(M.value,k,F,d),y.push(`/u_${b}`);H&&(this.binders[b].lutExpression=H.value)}this.cacheKey=y.sort().join("")}getMaxValue(l){const d=this.binders[l];return d instanceof Rh||d instanceof Dh?d.maxValue:0}populatePaintArrays(l,d,p,y,b,w,k,M){for(const F in this.binders){const $=this.binders[F];$.context=this.context,($ instanceof Rh||$ instanceof Dh||$ instanceof Lh)&&$.populatePaintArray(l,d,p,y,b,w,k,M)}}setConstantPatternPositions(l,d){for(const p in this.binders){const y=this.binders[p];y instanceof Og&&y.setConstantPatternPositions(l,d)}}getPatternTransitionVertexBuffer(l){const d=this.binders[l];return d instanceof Lh?d.paintTransitionVertexBuffer:null}updatePaintArrays(l,d,p,y,b,w,k,M,F,$){let U=!1;const H=Object.keys(l),Z=H.length!==0&&!M,Y=Z?H:d.uniqueIds;this.context.lut=b.lut;for(const ne in this.binders){const ce=this.binders[ne];if(ce.context=this.context,(ce instanceof Rh||ce instanceof Dh||ce instanceof Lh)&&ce.expression&&ce.expression.kind&&ce.expression.kind!=="constant"&&(ce.expression.isStateDependent===!0||ce.expression.isLightConstant===!1)){const le=b.paint.get(ne);ce.expression=le.value;for(const ye of Y){const we=l[ye.toString()];d.eachPosition(ye,(Ee,Ue,Le)=>{const Ke=y.feature(Ee);ce.updatePaintArray(Ue,Le,Ke,we,w,k,F,$)})}if(!Z)for(const ye of p.uniqueIds){const we=l[ye.toString()];p.eachPosition(ye,(Ee,Ue,Le)=>{const Ke=y.feature(Ee);ce.updatePaintArray(Ue,Le,Ke,we,w,k,F,$)})}U=!0}}return U}defines(){const l=[];for(const d in this.binders){const p=this.binders[d];(p instanceof pv||p instanceof Og)&&l.push(...p.uniformNames.map(y=>`#define HAS_UNIFORM_${y}`))}return l}getPaintVertexBuffers(){return this._buffers}getUniforms(l){const d=[];for(const p in this.binders){const y=this.binders[p];if(y instanceof pv||y instanceof Og||y instanceof Dh)for(const b of y.uniformNames)d.push({name:b,property:p,binding:y.getBinding(l,b)})}return d}setUniforms(l,d,p,y,b){for(const{name:w,property:k,binding:M}of p)this.binders[k].setUniform(l,M,b,y.get(k),w)}updatePaintBuffers(){this._buffers=[];for(const l in this.binders){const d=this.binders[l];(d instanceof Rh||d instanceof Dh||d instanceof Lh)&&d.paintVertexBuffer&&this._buffers.push(d.paintVertexBuffer),d instanceof Lh&&d.paintTransitionVertexBuffer&&this._buffers.push(d.paintTransitionVertexBuffer)}}upload(l){for(const d in this.binders){const p=this.binders[d];(p instanceof Rh||p instanceof Dh||p instanceof Lh)&&p.upload(l)}this.updatePaintBuffers()}destroy(){for(const l in this.binders){const d=this.binders[l];(d instanceof Rh||d instanceof Dh||d instanceof Lh)&&d.destroy()}}}class ed{constructor(l,d,p=()=>!0){this.programConfigurations={};for(const y of l)this.programConfigurations[y.id]=new Zf(y,d,p);this.needsUpload=!1,this._featureMap=new cv,this._featureMapWithoutIds=new cv,this._bufferOffset=0,this._idlessCounter=0}populatePaintArrays(l,d,p,y,b,w,k,M,F){for(const $ in this.programConfigurations)this.programConfigurations[$].populatePaintArrays(l,d,y,b,w,k,M,F);d.id!==void 0?this._featureMap.add(d.id,p,this._bufferOffset,l):(this._featureMapWithoutIds.add(this._idlessCounter,p,this._bufferOffset,l),this._idlessCounter+=1),this._bufferOffset=l,this.needsUpload=!0}updatePaintArrays(l,d,p,y,b,w,k,M){for(const F of p)this.needsUpload=this.programConfigurations[F.id].updatePaintArrays(l,this._featureMap,this._featureMapWithoutIds,d,F,y,b,w,k||0,M)||this.needsUpload}get(l){return this.programConfigurations[l]}upload(l){if(this.needsUpload){for(const d in this.programConfigurations)this.programConfigurations[d].upload(l);this.needsUpload=!1}}destroy(){for(const l in this.programConfigurations)this.programConfigurations[l].destroy()}}const O4={"text-opacity":["opacity"],"icon-opacity":["opacity"],"text-occlusion-opacity":["occlusion_opacity"],"icon-occlusion-opacity":["occlusion_opacity"],"text-color":["fill_color"],"icon-color":["fill_color"],"text-emissive-strength":["emissive_strength"],"icon-emissive-strength":["emissive_strength"],"text-halo-color":["halo_color"],"icon-halo-color":["halo_color"],"text-halo-blur":["halo_blur"],"icon-halo-blur":["halo_blur"],"text-halo-width":["halo_width"],"icon-halo-width":["halo_width"],"symbol-z-offset":["z_offset"],"line-gap-width":["gapwidth"],"line-pattern":["pattern","pixel_ratio","pattern_b"],"fill-pattern":["pattern","pixel_ratio","pattern_b"],"fill-extrusion-pattern":["pattern","pixel_ratio","pattern_b"],"line-dasharray":["dash"],"fill-bridge-guard-rail-color":["structure_color"],"fill-tunnel-structure-color":["structure_color"]};function R4(h,l){return O4[h]||[h.replace(`${l}-`,"").replace(/-/g,"_")]}const D4={"line-pattern":{source:ic,composite:ic},"fill-pattern":{source:ic,composite:ic},"fill-extrusion-pattern":{source:ic,composite:ic},"line-dasharray":{source:nm,composite:nm}},L4={color:{source:zd,composite:Gf},number:{source:Mh,composite:zd}};function dN(h,l,d){const p=D4[h];return p&&p[d]||L4[l][d]}Lr(pv,"ConstantBinder"),Lr(Og,"PatternConstantBinder"),Lr(Rh,"SourceExpressionBinder"),Lr(Lh,"PatternCompositeBinder"),Lr(Dh,"CompositeExpressionBinder"),Lr(Zf,"ProgramConfiguration",{omit:["_buffers"]}),Lr(ed,"ProgramConfigurationSet");const rl=mr/Math.PI/2,ju=5,Pb=6,F4=16383,Rg=64,hN=[Rg,32,16],Su=-rl,Nu=rl;function im(h,l,d,p=rl){return d=Xn(d),[h*Math.sin(d)*p,-l*p,h*Math.cos(d)*p]}function Dg(h,l,d){return im(Math.cos(Xn(h)),Math.sin(Xn(h)),l,d)}const x=63710088e-1,u=2*Math.PI*x;class f{constructor(l,d){if(isNaN(l)||isNaN(d))throw new Error(`Invalid LngLat object: (${l}, ${d})`);if(this.lng=+l,this.lat=+d,this.lat>90||this.lat<-90)throw new Error("Invalid LngLat latitude value: must be between -90 and 90")}wrap(){return new f(Re(this.lng,-180,180),this.lat)}toArray(){return[this.lng,this.lat]}toString(){return`LngLat(${this.lng}, ${this.lat})`}distanceTo(l){const d=Math.PI/180,p=this.lat*d,y=l.lat*d,b=Math.sin(p)*Math.sin(y)+Math.cos(p)*Math.cos(y)*Math.cos((l.lng-this.lng)*d);return x*Math.acos(Math.min(b,1))}toBounds(l=0){const d=360*l/40075017,p=d/Math.cos(Math.PI/180*this.lat);return new v({lng:this.lng-p,lat:this.lat-d},{lng:this.lng+p,lat:this.lat+d})}toEcef(l){return Dg(this.lat,this.lng,rl+l*rl/x)}static convert(l){if(l instanceof f)return l;if(Array.isArray(l)&&(l.length===2||l.length===3))return new f(Number(l[0]),Number(l[1]));if(!Array.isArray(l)&&typeof l=="object"&&l!==null)return new f(Number("lng"in l?l.lng:l.lon),Number(l.lat));throw new Error("`LngLatLike` argument must be specified as a LngLat instance, an object {lng: , lat: }, an object {lon: , lat: }, or an array of [, ]")}}class v{constructor(l,d){l&&(d?this.setSouthWest(l).setNorthEast(d):Array.isArray(l)&&l.length===4?this.setSouthWest([l[0],l[1]]).setNorthEast([l[2],l[3]]):this.setSouthWest(l[0]).setNorthEast(l[1]))}setNorthEast(l){return this._ne=l instanceof f?new f(l.lng,l.lat):f.convert(l),this}setSouthWest(l){return this._sw=l instanceof f?new f(l.lng,l.lat):f.convert(l),this}extend(l){const d=this._sw,p=this._ne;let y,b;if(l instanceof f)y=l,b=l;else{if(!(l instanceof v))return Array.isArray(l)?l.length===4||l.every(Array.isArray)?this.extend(v.convert(l)):this.extend(f.convert(l)):typeof l=="object"&&l!==null&&l.hasOwnProperty("lat")&&(l.hasOwnProperty("lon")||l.hasOwnProperty("lng"))?this.extend(f.convert(l)):this;if(y=l._sw,b=l._ne,!y||!b)return this}return d||p?(d.lng=Math.min(y.lng,d.lng),d.lat=Math.min(y.lat,d.lat),p.lng=Math.max(b.lng,p.lng),p.lat=Math.max(b.lat,p.lat)):(this._sw=new f(y.lng,y.lat),this._ne=new f(b.lng,b.lat)),this}getCenter(){return new f((this._sw.lng+this._ne.lng)/2,(this._sw.lat+this._ne.lat)/2)}getSouthWest(){return this._sw}getNorthEast(){return this._ne}getNorthWest(){return new f(this.getWest(),this.getNorth())}getSouthEast(){return new f(this.getEast(),this.getSouth())}getWest(){return this._sw.lng}getSouth(){return this._sw.lat}getEast(){return this._ne.lng}getNorth(){return this._ne.lat}toArray(){return[this._sw.toArray(),this._ne.toArray()]}toString(){return`LngLatBounds(${this._sw.toString()}, ${this._ne.toString()})`}isEmpty(){return!(this._sw&&this._ne)}contains(l){const{lng:d,lat:p}=f.convert(l);let y=this._sw.lng<=d&&d<=this._ne.lng;return this._sw.lng>this._ne.lng&&(y=this._sw.lng>=d&&d>=this._ne.lng),this._sw.lat<=p&&p<=this._ne.lat&&y}static convert(l){if(l)return l instanceof v?l:new v(l)}}const S=0,T=25.5;function E(h){return u*Math.cos(h*Math.PI/180)}function L(h){return(180+h)/360}function B(h){return(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+h*Math.PI/360)))/360}function q(h,l){return h/E(l)}function G(h){return 360*h-180}function ee(h){return 360/Math.PI*Math.atan(Math.exp((180-360*h)*Math.PI/180))-90}function J(h,l){return h*E(ee(l))}const re=85.051129;function oe(h){return Math.cos(Xn(ue(h,-re,re)))}function se(h,l){const d=ue(l,S,T),p=Math.pow(2,d);return oe(h)*u/(512*p)}function me(h){return 1/Math.cos(h*Math.PI/180)}function fe(h,l=0){const d=Math.exp(Math.PI*(1-(h.y+l/mr)/(1<=M?(Ae(h,l,d,F,$,b,U,k,M),Ae(h,F,$,p,y,U,w,k,M)):h.push(w)}function Te(h,l,d){let p=h[0],y=p.x,b=p.y;l(p);const w=[p];for(let k=1;kh.x+1||ph.y+1)&&Ge("Geometry exceeds allowed extent, reduce your vector tile buffer size"),h}function Qe(h,l,d){const p=h.loadGeometry(),y=h.extent,b=mr/y;if(l&&d&&d.projection.isReprojectedInTileSpace){const w=1<{const Z=G((l.x+H.x/y)/w),Y=ee((l.y+H.y/y)/w),ne=$.project(Z,Y);H.x=(ne.x*k-M)*y,H.y=(ne.y*k-F)*y};for(let H=0;H=y||Y.y<0||Y.y>=y||(U(Y),Z.push(Y));p[H]=Z}}for(const w of p)for(const k of w)De(k,b);return p}function ht(h,l){return{type:h.type,id:h.id,properties:h.properties,geometry:l?Qe(h):[]}}class ot{constructor(l,d,p,y,b){this.properties={},this.extent=p,this.type=0,this.id=void 0,this._pbf=l,this._geometry=-1,this._keys=y,this._values=b,l.readFields(Tt,this,d)}loadGeometry(){const l=this._pbf;l.pos=this._geometry;const d=l.readVarint()+l.pos,p=[];let y,b=1,w=0,k=0,M=0;for(;l.pos>3}if(w--,b===1||b===2)k+=l.readSVarint(),M+=l.readSVarint(),b===1&&(y&&p.push(y),y=[]),y&&y.push(new Wt(k,M));else{if(b!==7)throw new Error(`unknown command ${b}`);y&&y.push(y[0].clone())}}return y&&p.push(y),p}bbox(){const l=this._pbf;l.pos=this._geometry;const d=l.readVarint()+l.pos;let p=1,y=0,b=0,w=0,k=1/0,M=-1/0,F=1/0,$=-1/0;for(;l.pos>3}if(y--,p===1||p===2)b+=l.readSVarint(),w+=l.readSVarint(),bM&&(M=b),w$&&($=w);else if(p!==7)throw new Error(`unknown command ${p}`)}return[k,F,M,$]}toGeoJSON(l,d,p){const y=this.extent*Math.pow(2,p),b=this.extent*l,w=this.extent*d,k=this.loadGeometry();function M(H){return[360*(H.x+b)/y-180,360/Math.PI*Math.atan(Math.exp((1-2*(H.y+w)/y)*Math.PI))-90]}function F(H){return H.map(M)}let $;if(this.type===1){const H=[];for(const Y of k)H.push(Y[0]);const Z=F(H);$=H.length===1?{type:"Point",coordinates:Z[0]}:{type:"MultiPoint",coordinates:Z}}else if(this.type===2){const H=k.map(F);$=H.length===1?{type:"LineString",coordinates:H[0]}:{type:"MultiLineString",coordinates:H}}else{if(this.type!==3)throw new Error("unknown feature type");{const H=function(Y){const ne=Y.length;if(ne<=1)return[Y];const ce=[];let le,ye;for(let we=0;we=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[l];const d=this._pbf.readVarint()+this._pbf.pos;return new ot(this._pbf,d,this.extent,this._keys,this._values)}}function or(h,l,d){h===15?l.version=d.readVarint():h===1?l.name=d.readString():h===5?l.extent=d.readVarint():h===2?l._features.push(d.pos):h===3?l._keys.push(d.readString()):h===4&&l._values.push(function(p){let y=null;const b=p.readVarint()+p.pos;for(;p.pos>3;y=w===1?p.readString():w===2?p.readFloat():w===3?p.readDouble():w===4?p.readVarint64():w===5?p.readVarint():w===6?p.readSVarint():w===7?p.readBoolean():null}if(y==null)throw new Error("unknown feature value");return y}(d))}class wt{constructor(l,d){this.layers=l.readFields(st,{},d)}}function st(h,l,d){if(h===3){const p=new Bt(d,d.readVarint()+d.pos);p.length&&(l[p.name]=p)}}const Mt="3d_elevation_id",kt="level";class Zt{constructor(){this._valid=!1}reset(l){return this.feature=l,this._valid=!0,this._geometry=l.loadGeometry(),this._geometry.length!==0&&this._geometry[0].length!==0||(this._valid=!1),this}geometry(l,d){return this._valid&&l(d(this._geometry)),this}require(l,d,p){return this.get(l,!0,d,p)}optional(l,d,p){return this.get(l,!1,d,p)}success(){return this._valid}get(l,d,p,y){const b=this.feature.properties.hasOwnProperty(l)?+this.feature.properties[l]:void 0;return this._valid&&b!==void 0&&!Number.isNaN(b)?p(y?y(b):b):d&&(this._valid=!1),this}}class yr{constructor(l,d){this.featureFunc=l,this.vertexFunc=d}parseFeature(l,d,p){return this.featureFunc(l,d,p)}parseVertex(l,d,p){return this.vertexFunc(l,d,p)}}const Pr=new yr((h,l,d)=>h.reset(l).require(Mt,p=>{d.id=p}).optional("fixed_height_relative",p=>{d.constantHeight=p},lr.decodeRelativeHeight).geometry(p=>{d.bounds=p},kh).success(),(h,l,d)=>h.reset(l).require(Mt,p=>{d.id=p}).require("elevation_idx",p=>{d.idx=p}).require("extent",p=>{d.extent=p}).require("height_relative",p=>{d.height=p},lr.decodeRelativeHeight).geometry(p=>{d.position=p},lr.getPoint).success()),fr=new yr((h,l,d)=>h.reset(l).require(Mt,p=>{d.id=p}).optional("fixed_height",p=>{d.constantHeight=p},lr.decodeMetricHeight).geometry(p=>{d.bounds=p},kh).success(),(h,l,d)=>h.reset(l).require(Mt,p=>{d.id=p}).require("elevation_idx",p=>{d.idx=p}).require("extent",p=>{d.extent=p}).require("height",p=>{d.height=p},lr.decodeMetricHeight).geometry(p=>{d.position=p},lr.getPoint).success());class lr{static getPoint(l){return Ma(l[0][0].x,l[0][0].y)}static decodeRelativeHeight(l){return 1e-4*l*5}static decodeMetricHeight(l){return 1e-4*l}static getVersionSchema(l){return l?l==="1.0.1"?fr:void 0:Pr}static parse(l){const d=[],p=[],y=l.length,b=new Zt;for(let w=0;w=0);if(b===0)return 0;b!==l.length&&(d=!1)}return d?2:1}function Cn(h,l){for(const d of h.projections){const p=Mr(l,h.points[0],d.axis);if(d.projection[1]p[1])return 0}return 1}function as(h,l){let d=0;const p=[0,0,0,0];for(let w=0;w=0&&d++;var y,b;return d}class Is{constructor(l,d){this.points=l||new Array(8).fill([0,0,0]),this.planes=d||new Array(6).fill([0,0,0,0]),this.bounds=qr.fromPoints(this.points),this.projections=[],this.frustumEdges=[Kt([],this.points[2],this.points[3]),Kt([],this.points[0],this.points[3]),Kt([],this.points[4],this.points[0]),Kt([],this.points[5],this.points[1]),Kt([],this.points[6],this.points[2]),Kt([],this.points[7],this.points[3])];for(const p of this.frustumEdges){const y=[0,-p[2],p[1]],b=[p[2],0,-p[0]];this.projections.push({axis:y,projection:Mr(this.points,this.points[0],y)}),this.projections.push({axis:b,projection:Mr(this.points,this.points[0],b)})}}static fromInvProjectionMatrix(l,d,p,y){const b=Math.pow(2,p),w=[[-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]].map(F=>{const $=rr([],F,l),U=1/$[3]/d*b;return(H=$)[0]=(Z=$)[0]*(Y=[U,U,y?1/$[3]:U,U])[0],H[1]=Z[1]*Y[1],H[2]=Z[2]*Y[2],H[3]=Z[3]*Y[3],H;var H,Z,Y}),k=[[0,1,2],[6,5,4],[0,3,7],[2,1,5],[3,2,6],[0,4,5]].map(F=>{const $=Oe([],Be([],Kt([],w[F[0]],w[F[1]]),Kt([],w[F[2]],w[F[1]]))),U=-Ie($,w[F[1]]);return $.concat(U)}),M=[];for(let F=0;FF[1]||F[0]>M[1])return 0}return 1}containsPoint(l){for(const d of this.planes){const p=d[3];if(Ie([d[0],d[1],d[2]],l)+p<0)return!1}return!0}}class qr{static fromPoints(l){const d=[1/0,1/0,1/0],p=[-1/0,-1/0,-1/0];for(const y of l)bt(d,d,y),_e(p,p,y);return new qr(d,p)}static fromTileIdAndHeight(l,d,p){const y=1<l.max[d]||l.min[d]>this.max[d])return!1;return!0}intersectsAabbXY(l){return!(this.min[0]>l.max[0]||l.min[0]>this.max[0]||this.min[1]>l.max[1]||l.min[1]>this.max[1])}encapsulate(l){for(let d=0;d<3;d++)this.min[d]=Math.min(this.min[d],l.min[d]),this.max[d]=Math.max(this.max[d],l.max[d])}encapsulatePoint(l){for(let d=0;d<3;d++)this.min[d]=Math.min(this.min[d],l[d]),this.max[d]=Math.max(this.max[d],l[d])}closestPoint(l){return[Math.max(Math.min(this.max[0],l[0]),this.min[0]),Math.max(Math.min(this.max[1],l[1]),this.min[1]),Math.max(Math.min(this.max[2],l[2]),this.min[2])]}}Lr(qr,"Aabb");class Cs{constructor(l,d){this.feature=l,this.metersToTile=d,this.index=0}get(){const l=this.feature.vertices[this.index],d=this.feature.vertexProps[this.index].dir,p=d[1],y=-d[0],b=(l.extent+1)*this.metersToTile;return[new Wt(Math.trunc(l.position[0]+p*b),Math.trunc(l.position[1]+y*b)),new Wt(Math.trunc(l.position[0]-p*b),Math.trunc(l.position[1]-y*b))]}next(){this.index++}valid(){return this.index{return k.a0?Ye(M,M,1/F):Ce(M,0,0,1)}getSafeArea(){return this.safeArea}isTunnel(){return this.heightRange.max<=-5}getClosestEdge(l){if(this.edges.length===0)return;let d=0,p=Number.POSITIVE_INFINITY,y=0;const[b,w,k,M,F,$,U]=this._tmpVec2;Qo(U,l.x,l.y);const H=new Ur(U,null);for(let Z=0;Z0?xa(M,k)/Ee:0,Le=ue(Ue,0,1),Ke=Math.abs((Ue-Le)*this.edgeProps[Z].len);yl(F,U,ce),Qo($,ne[1],-ne[0]);const Je=Ke+Math.abs(xa(F,$));Je=0;--w){const k=this.edges[w].a,M=this.edges[w].b,{position:F,height:$,extent:U}=this.vertices[k],{position:H,height:Z,extent:Y}=this.vertices[M],ne=this.vertexProps[k].dir,ce=this.vertexProps[M].dir;if(Ce(d,F[0]/l,F[1]/l,$),Ce(p,H[0]/l,H[1]/l,Z),Ce(y,ne[1],-ne[0],0),Ye(y,y,U),Ce(b,ce[1],-ce[0],0),Ye(b,b,Y),this.distSqLines(ke(d[0]+.5*y[0],d[1]+.5*y[1],d[2]+.5*y[2]),ke(p[0]-.5*b[0],p[1]-.5*b[1],p[2]-.5*b[2]),ke(d[0]-.5*y[0],d[1]-.5*y[1],d[2]-.5*y[2]),ke(p[0]+.5*b[0],p[1]+.5*b[1],p[2]+.5*b[2]))<=.0025000000000000005)continue;const le=this.vertices.length,ye=ec(Xs(),F,H);this.vertices.push({position:tc(ye,ye,.5),height:.5*($+Z),extent:.5*(U+Y)});const we=ec(Xs(),ne,ce);this.vertexProps.push({dir:wh(we,we)}),this.edges.splice(w,1),this.edgeProps.splice(w,1),this.edges.push({a:k,b:le}),this.edges.push({a:le,b:M});const Ee=yl(Xs(),this.vertices[le].position,F),Ue=Jo(Ee),Le={vec:Ee,dir:tc(Xs(),Ee,1/Ue),len:Ue};this.edgeProps.push(Le),this.edgeProps.push(Le)}}distSqLines(l,d,p,y){const b=je(pe(),d,l),w=je(pe(),y,p),k=je(pe(),l,p),M=Ie(b,b),F=Ie(b,w),$=Ie(b,k),U=Ie(w,w),H=Ie(w,k),Z=M*U-F*F;if(Z===0)return Qt(Pe(b,p,y,Ie(k,w)/Ie(w,w)),l);const Y=(M*H-F*$)/Z;return Qt(Pe(b,l,d,(F*H-$*U)/Z),Pe(w,p,y,Y))}}class Ds{static parseFrom(l,d){const p=lr.parse(l);if(!p)return[];let{vertices:y,features:b}=p;const w=1/fe(d);b.sort(($,U)=>$.id-U.id),y.sort(($,U)=>$.id-U.id||$.idx-U.idx),y=y.filter(($,U,H)=>U===H.findIndex(Z=>Z.id===$.id&&Z.idx===$.idx));const k=new Array;let M=0;const F=y.length;for(const $ of b){if($.constantHeight){k.push(new Sn($.id,$.bounds,$.constantHeight));continue}for(;M!==F&&y[M].id<$.id;)M++;if(M===F||y[M].id!==$.id)continue;const U=new Array,H=new Array,Z=M;for(;M!==F&&y[M].id===$.id;){const Y=y[M];if(U.push({position:Y.position,height:Y.height,extent:Y.extent}),M!==Z&&y[M-1].idx===Y.idx-1){const ne=M-Z;H.push({a:ne-1,b:ne})}M++}k.push(new Sn($.id,$.bounds,void 0,U,H,w))}return k}static getElevationFeature(l,d){if(!d)return;const p=+l.properties[Mt];return Number.isNaN(p)?void 0:d.find(y=>y.id===p)}}class Ys{constructor(l,d){this.zScale=1,this.xOffset=0,this.yOffset=0,l.equals(d)||(this.zScale=Math.pow(2,d.z-l.z),this.xOffset=(l.x*this.zScale-d.x)*mr,this.yOffset=(l.y*this.zScale-d.y)*mr)}constantElevation(l,d){if(l.constantHeight!=null)return this.computeBiasedHeight(l.constantHeight,d)}pointElevation(l,d,p){const y=this.constantElevation(d,p);return y??(l.x=l.x*this.zScale+this.xOffset,l.y=l.y*this.zScale+this.yOffset,this.computeBiasedHeight(d.pointElevation(l),p))}computeBiasedHeight(l,d){return d<=0?l:l+d*be(0,d,l>=0?l:Math.abs(.5*l))}}Lr(Sn,"ElevationFeature");class Vs{constructor(l){this.zoom=l.zoom,this.overscaling=l.overscaling,this.layers=l.layers,this.layerIds=this.layers.map(d=>d.fqid),this.index=l.index,this.hasPattern=!1,this.projection=l.projection,this.layoutVertexArray=new Wf,this.indexArray=new Fa,this.segments=new Hi,this.programConfigurations=new ed(l.layers,{zoom:l.zoom,lut:l.lut}),this.stateDependentLayerIds=this.layers.filter(d=>d.isStateDependent()).map(d=>d.id),this.elevationMode=this.layers[0].layout.get("circle-elevation-reference"),this.hasElevation=!1,this.elevationMode!=="none"&&(this.elevatedLayoutVertexArray=new Mh),this.worldview=l.worldview,this.hasAppearances=null}updateFootprints(l,d){}updateAppearances(l,d,p,y){}populate(l,d,p,y){const b=this.layers[0],w=[];let k=null;b.type==="circle"&&(k=b.layout.get("circle-sort-key"));for(const{feature:F,id:$,index:U,sourceLayerIndex:H}of l){const Z=this.layers[0]._featureFilter.needGeometry,Y=ht(F,Z);if(!this.layers[0]._featureFilter.filter(new wi(this.zoom,{worldview:this.worldview,activeFloors:d.activeFloors}),Y,p))continue;const ne=k?k.evaluate(Y,{},p):void 0,ce={id:$,properties:F.properties,type:F.type,sourceLayerIndex:H,index:U,geometry:Z?Y.geometry:Qe(F,p,y),patterns:{},sortKey:ne};w.push(ce)}k&&w.sort((F,$)=>F.sortKey-$.sortKey);let M=null;y.projection.name==="globe"&&(this.globeExtVertexArray=new pb,M=y.projection);for(const F of w){const{geometry:$,index:U,sourceLayerIndex:H}=F,Z=l[U].feature;this.addFeature(F,$,U,d.availableImages,p,M,d.brightness,d.elevationFeatures),d.featureIndex.insert(Z,$,U,H,this.index)}this.hasElevation||(this.elevatedLayoutVertexArray=void 0)}update(l,d,p,y,b,w,k){this.programConfigurations.updatePaintArrays(l,d,b,p,y,w,k,this.worldview)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(l){this.uploaded||(this.layoutVertexBuffer=l.createVertexBuffer(this.layoutVertexArray,JE.members),this.indexBuffer=l.createIndexBuffer(this.indexArray),this.globeExtVertexArray&&(this.globeExtVertexBuffer=l.createVertexBuffer(this.globeExtVertexArray,eA.members)),this.elevatedLayoutVertexArray&&(this.elevatedLayoutVertexBuffer=l.createVertexBuffer(this.elevatedLayoutVertexArray,T4.members))),this.programConfigurations.upload(l),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.globeExtVertexBuffer&&this.globeExtVertexBuffer.destroy(),this.elevatedLayoutVertexBuffer&&this.elevatedLayoutVertexBuffer.destroy())}addFeature(l,d,p,y,b,w,k,M){let F;this.elevationMode!=="none"&&(F=Ds.getElevationFeature(l,M));for(const $ of d)for(const U of $){const H=U.x,Z=U.y;if(H<0||H>=mr||Z<0||Z>=mr)continue;if(w){const ce=w.projectTilePoint(H,Z,b),le=w.upVector(b,H,Z);this.addGlobeExtVertex(ce,le),this.addGlobeExtVertex(ce,le),this.addGlobeExtVertex(ce,le),this.addGlobeExtVertex(ce,le)}const Y=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray,l.sortKey),ne=Y.vertexLength;if(this.addCircleVertex(H,Z,-1,-1),this.addCircleVertex(H,Z,1,-1),this.addCircleVertex(H,Z,1,1),this.addCircleVertex(H,Z,-1,1),this.elevationMode!=="none"){const ce=F?F.pointElevation(new Wt(H,Z)):0;this.hasElevation=this.hasElevation||ce!==0;for(let le=0;le<4;le++)this.elevatedLayoutVertexArray.emplaceBack(ce)}this.indexArray.emplaceBack(ne,ne+1,ne+2),this.indexArray.emplaceBack(ne,ne+2,ne+3),Y.vertexLength+=4,Y.primitiveLength+=2}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,l,p,{},y,b,k,void 0,this.worldview)}addCircleVertex(l,d,p,y){this.layoutVertexArray.emplaceBack(2*l+(p+1)/2,2*d+(y+1)/2)}addGlobeExtVertex(l,d){this.globeExtVertexArray.emplaceBack(l.x,l.y,l.z,d[0]*16384,d[1]*16384,d[2]*16384)}}function ws(h,l){for(let d=0;d1){if(Li(h,l))return!0;for(let p=0;p1?d:d.sub(l)._mult(y)._add(l))}function Wi(h,l){let d,p,y,b=!1;for(let w=0;wl.y!=y.y>l.y&&l.x<(y.x-p.x)*(l.y-p.y)/(y.y-p.y)+p.x&&(b=!b)}return b}function ci(h,l){let d=!1;for(let p=0,y=h.length-1;pl.y!=w.y>l.y&&l.x<(w.x-b.x)*(l.y-b.y)/(w.y-b.y)+b.x&&(d=!d)}return d}function Ll(h,l,d,p,y){for(const w of h)if(l<=w.x&&d<=w.y&&p>=w.x&&y>=w.y)return!0;const b=[new Wt(l,d),new Wt(l,y),new Wt(p,y),new Wt(p,d)];if(h.length>2){for(const w of b)if(ci(h,w))return!0}for(let w=0;wy.x&&l.x>y.x||h.yy.y&&l.y>y.y)return!1;const b=ur(h,l,d[0]);return b!==ur(h,l,d[1])||b!==ur(h,l,d[2])||b!==ur(h,l,d[3])}function Ba(h,l,d,p,y,b){let w=l.y-h.y,k=h.x-l.x;if(b=b||0){const M=w*w+k*k;if(M===0)return!0;const F=Math.sqrt(M);w/=F,k/=F}return!((d.x-h.x)*w+(d.y-h.y)*k-b<0||(p.x-h.x)*w+(p.y-h.y)*k-b<0||(y.x-h.x)*w+(y.y-h.y)*k-b<0)}function nl(h,l,d,p,y,b,w){return!(Ba(h,l,p,y,b,w)||Ba(l,d,p,y,b,w)||Ba(d,h,p,y,b,w)||Ba(p,y,h,l,d,w)||Ba(y,b,h,l,d,w)||Ba(b,p,h,l,d,w))}function sl(h,l,d){const p=l.paint.get(h).value;return p.kind==="constant"?p.value:d.programConfigurations.get(l.id).getMaxValue(h)}function To(h){return Math.sqrt(h[0]*h[0]+h[1]*h[1])}function Hc(h,l,d,p,y){if(!l[0]&&!l[1])return h;const b=Wt.convert(l)._mult(y);d==="viewport"&&b._rotate(-p);const w=[];for(let k=0;k>d&&l.y===this.y>>d}url(l,d){const p=function(b,w,k){var M=ma(256*b,256*(w=Math.pow(2,k)-w-1),k),F=ma(256*(b+1),256*(w+1),k);return M[0]+","+M[1]+","+F[0]+","+F[1]}(this.x,this.y,this.z),y=function(b,w,k){let M,F="";for(let $=b;$>0;$--)M=1<<$-1,F+=(w&M?1:0)+(k&M?2:0);return F}(this.z,this.x,this.y);return l[(this.x+this.y)%l.length].replace("{prefix}",(this.x%16).toString(16)+(this.y%16).toString(16)).replace(/{z}/g,String(this.z)).replace(/{x}/g,String(this.x)).replace(/{y}/g,String(d==="tms"?Math.pow(2,this.z)-this.y-1:this.y)).replace("{quadkey}",y).replace("{bbox-epsg-3857}",p)}toString(){return`${this.z}/${this.x}/${this.y}`}}class wa{constructor(l,d){this.wrap=l,this.canonical=d,this.key=Gi(l,d.z,d.z,d.x,d.y)}}class Ji{constructor(l,d,p,y,b){this.overscaledZ=l,this.wrap=d,this.canonical=new ui(p,+y,+b),this.key=d===0&&l===p?this.canonical.key:Gi(d,l,p,y,b)}equals(l){return this.overscaledZ===l.overscaledZ&&this.wrap===l.wrap&&this.canonical.equals(l.canonical)}scaledTo(l){const d=this.canonical.z-l;return l>this.canonical.z?new Ji(l,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new Ji(l,this.wrap,l,this.canonical.x>>d,this.canonical.y>>d)}calculateScaledKey(l,d=!0){if(this.overscaledZ===l&&d)return this.key;if(l>this.canonical.z)return Gi(this.wrap*+d,l,this.canonical.z,this.canonical.x,this.canonical.y);{const p=this.canonical.z-l;return Gi(this.wrap*+d,l,l,this.canonical.x>>p,this.canonical.y>>p)}}isChildOf(l){if(l.wrap!==this.wrap)return!1;const d=this.canonical.z-l.canonical.z;return l.overscaledZ===0||l.overscaledZ>d&&l.canonical.y===this.canonical.y>>d}children(l){if(this.overscaledZ>=l)return[new Ji(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];const d=this.canonical.z+1,p=2*this.canonical.x,y=2*this.canonical.y;return[new Ji(d,this.wrap,d,p,y),new Ji(d,this.wrap,d,p+1,y),new Ji(d,this.wrap,d,p,y+1),new Ji(d,this.wrap,d,p+1,y+1)]}isLessThan(l){return this.wrapl.wrap)&&(this.overscaledZl.overscaledZ)&&(this.canonical.xl.canonical.x)&&this.canonical.y{let l=h.canonical.x-1,d=h.wrap;return l<0&&(l=(1<{let l=h.canonical.x+1,d=h.wrap;return l===1<new Ji(h.overscaledZ,h.wrap,h.canonical.z,h.canonical.x,(h.canonical.y===0?1<new Ji(h.overscaledZ,h.wrap,h.canonical.z,h.canonical.x,h.canonical.y===(1<1?null:function(p,y,b,w){const k=Math.sin(b);return p*(Math.sin((1-w)*b)/k)+y*(Math.sin(w*b)/k)}(h.a[l],h.b[l],h.angle,ue(d,0,1))+h.center[l]}function rd(h){if(h.z<=1)return Fh[h.z+2*h.y+h.x];const l=z4(tA(h));return qr.fromPoints(l)}function Bh(h,l,d){return Ye(h,h,1-d),pt(h,h,l,d)}function PW(h,l,d){for(const p of h)ut(p,p,l),Ye(p,p,d)}function IW(h,l,d,p){const y=l/h.worldSize,b=h.globeMatrix;if(d.z<=1){const it=rd(d).getCorners();return PW(it,b,y),qr.fromPoints(it)}const w=tA(d,p),k=z4(w,rl+$d(h._tileCoverLift));PW(k,b,y);const M=Number.MAX_VALUE,F=[-M,-M,-M],$=[M,M,M];if(w.contains(h.center)){for(const ft of k)bt($,$,ft),_e(F,F,ft);F[2]=0;const it=h.point,Pt=[it.x*y,it.y*y,0];return bt($,$,Pt),_e(F,F,Pt),new qr($,F)}if(h._tileCoverLift>0){for(const it of k)bt($,$,it),_e(F,F,it);return new qr($,F)}const U=[b[12]*y,b[13]*y,b[14]*y],H=w.getCenter(),Z=ue(h.center.lat,-re,re),Y=ue(H.lat,-re,re),ne=L(h.center.lng),ce=B(Z);let le=ne-L(H.lng);const ye=ce-B(Y);le>.5?le-=1:le<-.5&&(le+=1);let we=0;Math.abs(le)>Math.abs(ye)?we=le>=0?1:3:(we=ye>=0?0:2,pt(U,U,[b[4]*y,b[5]*y,b[6]*y],-Math.sin(Xn(ye>=0?w.getSouth():w.getNorth()))*rl));const Ee=k[we],Ue=k[(we+1)%4],Le=new Yf(Ee,Ue,U),Ke=[zh(Le,0)||Ee[0],zh(Le,1)||Ee[1],zh(Le,2)||Ee[2]],Je=zg(h.zoom);if(Je>0){const it=function({x:ft,y:Ft,z:Vt},qt,er,nr,Yt){const Xt=1/(1<.5?cr=-1:Gr<-.5&&(cr=1),Rt=((Rt+cr)*qt-(nr*=qt))*er+nr,It=((It+cr)*qt-nr)*er+nr,Jt=(Jt*qt-(Yt*=qt))*er+Yt,gr=(gr*qt-Yt)*er+Yt,[[Rt,gr,0],[It,gr,0],[It,Jt,0],[Rt,Jt,0]]}(d,l,h._pixelsPerMercatorPixel,ne,ce);for(let ft=0;ftMath.PI/2*1.01}const LW=Xn(85),mbe=Math.cos(LW),gbe=Math.sin(LW),ybe=P(),FW=h=>{const l=[];return h.paint.get("circle-pitch-alignment")==="map"&&l.push("PITCH_WITH_MAP"),h.paint.get("circle-pitch-scale")==="map"&&l.push("SCALE_WITH_MAP"),l};function zW(h,l,d,p,y,b,w,k,M){if(b&&h.queryGeometry.isAboveHorizon)return!1;b&&(M*=h.pixelToTileUnitsFactor);const F=h.tileID.canonical,$=d.projection.upVectorScale(F,d.center.lat,d.worldSize).metersToTile;for(const U of l)for(const H of U){const Z=H.add(k),Y=y&&d.elevation?d.elevation.exaggeration()*y.getElevationAt(Z.x,Z.y,!0):0,ne=d.projection.projectTilePoint(Z.x,Z.y,F);if(Y>0){const we=d.projection.upVector(F,Z.x,Z.y);ne.x+=we[0]*$*Y,ne.y+=we[1]*$*Y,ne.z+=we[2]*$*Y}const ce=b?Z:xbe(ne.x,ne.y,ne.z,p),le=b?h.tilespaceRays.map(we=>_be(we,Y)):h.queryGeometry.screenGeometry,ye=rr([],[ne.x,ne.y,ne.z,1],p);if(!w&&b?M*=ye[3]/d.cameraToCenterDistance:w&&!b&&(M*=d.cameraToCenterDistance/ye[3]),b){const we=ee((H.y/mr+F.y)/(1<h.width||y.height>h.height||d.x>h.width-y.width||d.y>h.height-y.height)throw new RangeError("out of range source coordinates for image copy");if(y.width>l.width||y.height>l.height||p.x>l.width-y.width||p.y>l.height-y.height)throw new RangeError("out of range destination coordinates for image copy");const M=h.data,F=l.data,$=b===4&&k;for(let U=0;U{l[h.evaluationKey]=M;const F=h.expression.evaluate(l),$=F?F.toNonPremultipliedRenderColor(null):null;$&&(y.data[w+k+0]=Math.floor(255*$.r),y.data[w+k+1]=Math.floor(255*$.g),y.data[w+k+2]=Math.floor(255*$.b),y.data[w+k+3]=Math.floor(255*$.a))};if(h.clips)for(let w=0,k=0;w80*d){k=h[0],M=h[1];let $=k,U=M;for(let H=d;H$&&($=Z),Y>U&&(U=Y)}F=Math.max($-k,U-M),F=F!==0?32767/F:0}return mN(b,w,d,k,M,F,0),w}function ZW(h,l,d,p,y){let b;if(y===function(w,k,M,F){let $=0;for(let U=k,H=M-F;U0)for(let w=l;w=l;w-=p)b=JW(w/p|0,h[w],h[w+1],b);return b&&Mb(b,b.next)&&(xN(b),b=b.next),b}function yv(h,l){if(!h)return h;l||(l=h);let d,p=h;do if(d=!1,p.steiner||!Mb(p,p.next)&&bo(p.prev,p,p.next)!==0)p=p.next;else{if(xN(p),p=l=p.prev,p===p.next)break;d=!0}while(d||p!==l);return l}function mN(h,l,d,p,y,b,w){if(!h)return;!w&&b&&function(M,F,$,U){let H=M;do H.z===0&&(H.z=q4(H.x,H.y,F,$,U)),H.prevZ=H.prev,H.nextZ=H.next,H=H.next;while(H!==M);H.prevZ.nextZ=null,H.prevZ=null,function(Z){let Y,ne=1;do{let ce,le=Z;Z=null;let ye=null;for(Y=0;le;){Y++;let we=le,Ee=0;for(let Le=0;Le0||Ue>0&&we;)Ee!==0&&(Ue===0||!we||le.z<=we.z)?(ce=le,le=le.nextZ,Ee--):(ce=we,we=we.nextZ,Ue--),ye?ye.nextZ=ce:Z=ce,ce.prevZ=ye,ye=ce;le=we}ye.nextZ=null,ne*=2}while(Y>1)}(H)}(h,p,y,b);let k=h;for(;h.prev!==h.next;){const M=h.prev,F=h.next;if(b?Cbe(h,p,y,b):Nbe(h))l.push(M.i,h.i,F.i),xN(h),h=F.next,k=F.next;else if((h=F)===k){w?w===1?mN(h=kbe(yv(h),l),l,d,p,y,b,2):w===2&&Tbe(h,l,d,p,y,b):mN(yv(h),l,d,p,y,b,1);break}}}function Nbe(h){const l=h.prev,d=h,p=h.next;if(bo(l,d,p)>=0)return!1;const y=l.x,b=d.x,w=p.x,k=l.y,M=d.y,F=p.y,$=Math.min(y,b,w),U=Math.min(k,M,F),H=Math.max(y,b,w),Z=Math.max(k,M,F);let Y=p.next;for(;Y!==l;){if(Y.x>=$&&Y.x<=H&&Y.y>=U&&Y.y<=Z&&gN(y,k,b,M,w,F,Y.x,Y.y)&&bo(Y.prev,Y,Y.next)>=0)return!1;Y=Y.next}return!0}function Cbe(h,l,d,p){const y=h.prev,b=h,w=h.next;if(bo(y,b,w)>=0)return!1;const k=y.x,M=b.x,F=w.x,$=y.y,U=b.y,H=w.y,Z=Math.min(k,M,F),Y=Math.min($,U,H),ne=Math.max(k,M,F),ce=Math.max($,U,H),le=q4(Z,Y,l,d,p),ye=q4(ne,ce,l,d,p);let we=h.prevZ,Ee=h.nextZ;for(;we&&we.z>=le&&Ee&&Ee.z<=ye;){if(we.x>=Z&&we.x<=ne&&we.y>=Y&&we.y<=ce&&we!==y&&we!==w&&gN(k,$,M,U,F,H,we.x,we.y)&&bo(we.prev,we,we.next)>=0||(we=we.prevZ,Ee.x>=Z&&Ee.x<=ne&&Ee.y>=Y&&Ee.y<=ce&&Ee!==y&&Ee!==w&&gN(k,$,M,U,F,H,Ee.x,Ee.y)&&bo(Ee.prev,Ee,Ee.next)>=0))return!1;Ee=Ee.nextZ}for(;we&&we.z>=le;){if(we.x>=Z&&we.x<=ne&&we.y>=Y&&we.y<=ce&&we!==y&&we!==w&&gN(k,$,M,U,F,H,we.x,we.y)&&bo(we.prev,we,we.next)>=0)return!1;we=we.prevZ}for(;Ee&&Ee.z<=ye;){if(Ee.x>=Z&&Ee.x<=ne&&Ee.y>=Y&&Ee.y<=ce&&Ee!==y&&Ee!==w&&gN(k,$,M,U,F,H,Ee.x,Ee.y)&&bo(Ee.prev,Ee,Ee.next)>=0)return!1;Ee=Ee.nextZ}return!0}function kbe(h,l){let d=h;do{const p=d.prev,y=d.next.next;!Mb(p,y)&&XW(p,d,d.next,y)&&yN(p,y)&&yN(y,p)&&(l.push(p.i,d.i,y.i),xN(d),xN(d.next),d=h=y),d=d.next}while(d!==h);return yv(d)}function Tbe(h,l,d,p,y,b){let w=h;do{let k=w.next.next;for(;k!==w.prev;){if(w.i!==k.i&&Mbe(w,k)){let M=QW(w,k);return w=yv(w,w.next),M=yv(M,M.next),mN(w,l,d,p,y,b,0),void mN(M,l,d,p,y,b,0)}k=k.next}w=w.next}while(w!==h)}function Ebe(h,l){let d=h.x-l.x;return d===0&&(d=h.y-l.y,d===0)&&(d=(h.next.y-h.y)/(h.next.x-h.x)-(l.next.y-l.y)/(l.next.x-l.x)),d}function Abe(h,l){const d=function(y,b){let w=b;const k=y.x,M=y.y;let F,$=-1/0;if(Mb(y,w))return w;do{if(Mb(y,w.next))return w.next;if(M<=w.y&&M>=w.next.y&&w.next.y!==w.y){const ne=w.x+(M-w.y)*(w.next.x-w.x)/(w.next.y-w.y);if(ne<=k&&ne>$&&($=ne,F=w.x=w.x&&w.x>=H&&k!==w.x&&YW(MF.x||w.x===F.x&&Pbe(F,w)))&&(F=w,Y=ne)}w=w.next}while(w!==U);return F}(h,l);if(!d)return l;const p=QW(d,h);return yv(p,p.next),yv(d,d.next)}function Pbe(h,l){return bo(h.prev,h,l.prev)<0&&bo(l.next,h,h.next)<0}function q4(h,l,d,p,y){return(h=1431655765&((h=858993459&((h=252645135&((h=16711935&((h=(h-d)*y|0)|h<<8))|h<<4))|h<<2))|h<<1))|(l=1431655765&((l=858993459&((l=252645135&((l=16711935&((l=(l-p)*y|0)|l<<8))|l<<4))|l<<2))|l<<1))<<1}function Ibe(h){let l=h,d=h;do(l.x=(h-w)*(b-k)&&(h-w)*(p-k)>=(d-w)*(l-k)&&(d-w)*(b-k)>=(y-w)*(p-k)}function gN(h,l,d,p,y,b,w,k){return!(h===w&&l===k)&&YW(h,l,d,p,y,b,w,k)}function Mbe(h,l){return h.next.i!==l.i&&h.prev.i!==l.i&&!function(d,p){let y=d;do{if(y.i!==d.i&&y.next.i!==d.i&&y.i!==p.i&&y.next.i!==p.i&&XW(y,y.next,d,p))return!0;y=y.next}while(y!==d);return!1}(h,l)&&(yN(h,l)&&yN(l,h)&&function(d,p){let y=d,b=!1;const w=(d.x+p.x)/2,k=(d.y+p.y)/2;do y.y>k!=y.next.y>k&&y.next.y!==y.y&&w<(y.next.x-y.x)*(k-y.y)/(y.next.y-y.y)+y.x&&(b=!b),y=y.next;while(y!==d);return b}(h,l)&&(bo(h.prev,h,l.prev)||bo(h,l.prev,l))||Mb(h,l)&&bo(h.prev,h,h.next)>0&&bo(l.prev,l,l.next)>0)}function bo(h,l,d){return(l.y-h.y)*(d.x-l.x)-(l.x-h.x)*(d.y-l.y)}function Mb(h,l){return h.x===l.x&&h.y===l.y}function XW(h,l,d,p){const y=iA(bo(h,l,d)),b=iA(bo(h,l,p)),w=iA(bo(d,p,h)),k=iA(bo(d,p,l));return y!==b&&w!==k||!(y!==0||!sA(h,d,l))||!(b!==0||!sA(h,p,l))||!(w!==0||!sA(d,h,p))||!(k!==0||!sA(d,l,p))}function sA(h,l,d){return l.x<=Math.max(h.x,d.x)&&l.x>=Math.min(h.x,d.x)&&l.y<=Math.max(h.y,d.y)&&l.y>=Math.min(h.y,d.y)}function iA(h){return h>0?1:h<0?-1:0}function yN(h,l){return bo(h.prev,h,h.next)<0?bo(h,l,h.next)>=0&&bo(h,h.prev,l)>=0:bo(h,l,h.prev)<0||bo(h,h.next,l)<0}function QW(h,l){const d=H4(h.i,h.x,h.y),p=H4(l.i,l.x,l.y),y=h.next,b=l.prev;return h.next=l,l.prev=h,d.next=y,y.prev=d,p.next=d,d.prev=p,b.next=p,p.prev=b,p}function JW(h,l,d,p){const y=H4(h,l,d);return p?(y.next=p.next,y.prev=p,p.next.prev=y,p.next=y):(y.prev=y,y.next=y),y}function xN(h){h.next.prev=h.prev,h.prev.next=h.next,h.prevZ&&(h.prevZ.nextZ=h.nextZ),h.nextZ&&(h.nextZ.prevZ=h.prevZ)}function H4(h,l,d){return{i:h,x:l,y:d,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function vN(h,l){const d=h.length;if(d<=1)return[h];const p=[];let y,b;for(let w=0;w1)for(let w=0;w=mr&&d>=mr}static evaluate(l){if(l.length===0)return new am;let d=[];for(const M of l)d.push(...M.portals);if(d.length===0)return new am;for(const M of d){const F=M.va,$=M.vb;(am.isOnBorder(F.x,$.x)||am.isOnBorder(F.y,$.y))&&(M.type="border")}const p=d.filter(M=>M.type!=="unevaluated"),y=d.filter(M=>M.type==="unevaluated");if(y.length===0)return new am;y.sort((M,F)=>M.hash===F.hash?M.isTunnel===F.isTunnel?0:M.isTunnel?-1:1:M.hashM.hashb!=="fill-tunnel-structure-color"),this.tunnelProgramConfigurations=new ed(d,{zoom:p,lut:y},b=>b!=="fill-bridge-guard-rail-color")}addVertices(l,d){const p=this.unevalVertices.length;for(let y=0;y=b.min.x&&U.x<=b.max.x&&U.y>=b.min.y&&U.y<=b.max.y||H.x>=b.min.x&&H.x<=b.max.x&&H.y>=b.min.y&&H.y<=b.max.y||Uo(U,H,k))||this.isOnBorder(U.x,H.x)||this.isOnBorder(U.y,H.y))continue;const Z=Wc.computeEdgeHash(this.unevalVertices[F],this.unevalVertices[$]);let Y,ne=this.vertexHashLookup.get(Wc.computePosHash(U));ne!=null?Y=ne.next:(ne=this.vertexHashLookup.get(Wc.computePosHash(H)),Y=ne!=null?ne.prev:Z),this.unevalEdges.push({polygonIdx:l,a:F,b:$,hash:Z,portalHash:Y,isTunnel:y,type:"unevaluated",featureInfo:w})}}addPortalCandidates(l,d,p,y,b){if(d.length===0)return;this.portalPolygons.add(l,{geometry:d,zLevel:b});const w=d[0];this.vertexHashLookup.clear();let k=Wc.computeEdgeHash(w[w.length-2],w[w.length-1]);for(let M=0;M({vertexOffset:0,primitiveOffset:this.indexArray.length}),p=H=>{H.primitiveLength=this.indexArray.length-H.primitiveOffset},y=new Rbe(this.vertexPositions,this.vertexNormals,this.indexArray);this.prepareEdges(l.portals,this.unevalEdges);const b=d(),w=d(),k=d(),M=(H,Z)=>{H.sort((ne,ce)=>ne.type===Z&&ce.type!==Z?-1:ne.type!==Z&&ce.type===Z?1:0);const Y=H.findIndex(ne=>ne.type!==Z);return Y>=0?Y:H.length};let F=0;this.unevalEdges.length>0&&(F=M(this.unevalEdges,"none"),this.constructBridgeStructures(y,this.unevalVertices,this.unevalHeights,this.unevalEdges,{min:0,max:F},this.tileToMeters)),p(k);const $=d(),U=d();if(this.unevalEdges.length>0){const H=this.unevalEdges.splice(F),Z=M(H,"tunnel")+F;this.unevalEdges.push(...H),this.constructTunnelStructures(y,this.unevalVertices,this.unevalHeights,this.unevalEdges,{min:0,max:F},{min:F,max:Z})}p($),y.addTriangles(this.unevalTriangles,this.unevalVertices,this.unevalHeights),p(U),y.addTriangles(this.unevalTunnelTriangles,this.unevalVertices,this.unevalHeights),p(w),y.addTriangles(this.unevalTunnelTriangles,this.unevalVertices,[-.1]),p(b),this.maskSegments=Hi.simpleSegment(0,U.primitiveOffset,0,U.primitiveLength),this.depthSegments=Hi.simpleSegment(0,w.primitiveOffset,0,w.primitiveLength),this.renderableBridgeSegments=Hi.simpleSegment(0,k.primitiveOffset,0,k.primitiveLength),this.renderableTunnelSegments=Hi.simpleSegment(0,$.primitiveOffset,0,$.primitiveLength),this.shadowCasterSegments=Hi.simpleSegment(0,b.primitiveOffset,0,b.primitiveLength)}update(l,d,p,y,b,w,k,M){this.bridgeProgramConfigurations.updatePaintArrays(l,d,b,p,y,w,k,M),this.tunnelProgramConfigurations.updatePaintArrays(l,d,b,p,y,w,k,M)}upload(l){this.vertexBuffer||this.vertexPositions.length===0||this.vertexNormals.length===0||this.indexArray.length===0||(this.vertexBuffer=l.createVertexBuffer(this.vertexPositions,jbe.members),this.vertexBufferNormal=l.createVertexBuffer(this.vertexNormals,Sbe.members),this.indexBuffer=l.createIndexBuffer(this.indexArray),this.bridgeProgramConfigurations.upload(l),this.tunnelProgramConfigurations.upload(l))}destroy(){this.vertexBuffer&&(this.vertexBuffer.destroy(),this.vertexBufferNormal.destroy(),this.indexBuffer.destroy()),this.maskSegments&&(this.maskSegments.destroy(),this.depthSegments.destroy(),this.renderableBridgeSegments.destroy(),this.renderableTunnelSegments.destroy(),this.shadowCasterSegments.destroy()),this.bridgeProgramConfigurations.destroy(),this.tunnelProgramConfigurations.destroy()}populatePaintArrays(l,d,p,y,b){const w=(k,M)=>{for(let F=0;FCe(er,d[nr].x,d[nr].y,p[nr]*M),U=pe(),H=pe(),Z=pe(),Y=pe(),ne=pe(),ce=(er,nr)=>{const Yt=k.get(Wc.computePosHash(d[nr])),Xt=Yt.from,Rt=Yt.to;if(!Xt||!Rt)return;$(U,Xt),$(H,nr),$(Z,Rt),Ht(Y),Lt(U,H)||(Kt(ne,H,U),Oe(Y,ne)),Lt(Z,H)||(Kt(ne,Z,H),Se(Y,Y,Oe(ne,ne)));const It=rt(Y);return It>0?Ye(er,Y,1/It):void 0};let le=Number.POSITIVE_INFINITY;this.sortSubarray(y,b.min,b.max,(er,nr)=>er.featureInfo.featureIndex-nr.featureInfo.featureIndex);const ye=pe(),we=pe(),Ee=pe(),Ue=pe(),Le=pe(),Ke=pe(),Je=pe(),it=pe(),Pt=pe(),ft=[pe(),pe(),pe(),pe()],Ft=[pe(),pe(),pe(),pe()],Vt=[{coord:new Wt(0,0),height:0},{coord:new Wt(0,0),height:0}],qt=(er,nr)=>er>nr;for(let er=b.min;erle.featureInfo.featureIndex-ye.featureInfo.featureIndex;this.sortSubarray(y,b.min,b.max,M),this.sortSubarray(y,w.min,w.max,M);const F=le=>Oe(le,le),$=[{coord:new Wt(0,0),height:0},{coord:new Wt(0,0),height:0}],U=(le,ye)=>lek.hash===M.hash?M.polygonIdx-k.polygonIdx:M.hash>k.hash?1:-1);let p=0,y=0,b=0,w=d[p].polygonIdx;do y++,(y===d.length||d[p].hash!==d[y].hash)&&((y-p==1||d[y-1].polygonIdx!==w)&&(bF.portalHash<$.portalHash?1:-1);let k=0,M=0;for(;k!==d.length&&M!==l.length;){const F=d[k],$=l[M];F.portalHash>$.hash?k++:$.hash>F.portalHash?M++:(F.type=$.type,k++)}}}isOnBorder(l,d){return l<=0&&d<=0||l>=mr&&d>=mr}addFeatureSection(l,d,p,y){return l!==d&&(d=l,p.push({featureIndex:l,vertexStart:y.getVertexCount()}),y.clearVertexLookup()),d}sortSubarray(l,d,p,y){const b=l.slice(d,p);b.sort(y),l.splice(d,b.length,...b)}static computeEdgeHash(l,d){return(l.y===d.y&&l.x>d.x||l.y>d.y)&&([l,d]=[d,l]),BigInt(Wc.computePosHash(l))<<32n|BigInt(Wc.computePosHash(d))}static computePosHash(l){return((65535&l.x)<<16|65535&l.y)>>>0}}var rG,nG={exports:{}},sG=(rG||(rG=1,function(h){function l(Fe,qe){return Fe>qe?1:Fe0){var Kr=tr+Math.floor(Cr/2),Xr={key:qe[Kr],data:zt[Kr],parent:Fe};return Xr.left=y(Xr,qe,zt,tr,Kr),Xr.right=y(Xr,qe,zt,Kr+1,Nr),Xr}return null}function b(Fe,qe,zt,tr,Nr){if(!(zt>=tr)){for(var Cr=Fe[zt+tr>>1],Kr=zt-1,Xr=tr+1;;){do Kr++;while(Nr(Fe[Kr],Cr)<0);do Xr--;while(Nr(Fe[Xr],Cr)>0);if(Kr>=Xr)break;var kn=Fe[Kr];Fe[Kr]=Fe[Xr],Fe[Xr]=kn,kn=qe[Kr],qe[Kr]=qe[Xr],qe[Xr]=kn}b(Fe,qe,zt,Xr,Nr),b(Fe,qe,Xr+1,tr,Nr)}}d.prototype.rotateLeft=function(Fe){var qe=Fe.right;qe&&(Fe.right=qe.left,qe.left&&(qe.left.parent=Fe),qe.parent=Fe.parent),Fe.parent?Fe===Fe.parent.left?Fe.parent.left=qe:Fe.parent.right=qe:this._root=qe,qe&&(qe.left=Fe),Fe.parent=qe},d.prototype.rotateRight=function(Fe){var qe=Fe.left;qe&&(Fe.left=qe.right,qe.right&&(qe.right.parent=Fe),qe.parent=Fe.parent),Fe.parent?Fe===Fe.parent.left?Fe.parent.left=qe:Fe.parent.right=qe:this._root=qe,qe&&(qe.right=Fe),Fe.parent=qe},d.prototype._splay=function(Fe){for(;Fe.parent;){var qe=Fe.parent;qe.parent?qe.left===Fe&&qe.parent.left===qe?(this.rotateRight(qe.parent),this.rotateRight(qe)):qe.right===Fe&&qe.parent.right===qe?(this.rotateLeft(qe.parent),this.rotateLeft(qe)):qe.left===Fe&&qe.parent.right===qe?(this.rotateRight(qe),this.rotateLeft(qe)):(this.rotateLeft(qe),this.rotateRight(qe)):qe.left===Fe?this.rotateRight(qe):this.rotateLeft(qe)}},d.prototype.splay=function(Fe){for(var qe,zt,tr,Nr,Cr;Fe.parent;)(zt=(qe=Fe.parent).parent)&&zt.parent?((tr=zt.parent).left===zt?tr.left=Fe:tr.right=Fe,Fe.parent=tr):(Fe.parent=null,this._root=Fe),Nr=Fe.left,Cr=Fe.right,Fe===qe.left?(zt&&(zt.left===qe?(qe.right?(zt.left=qe.right,zt.left.parent=zt):zt.left=null,qe.right=zt,zt.parent=qe):(Nr?(zt.right=Nr,Nr.parent=zt):zt.right=null,Fe.left=zt,zt.parent=Fe)),Cr?(qe.left=Cr,Cr.parent=qe):qe.left=null,Fe.right=qe,qe.parent=Fe):(zt&&(zt.right===qe?(qe.left?(zt.right=qe.left,zt.right.parent=zt):zt.right=null,qe.left=zt,zt.parent=qe):(Cr?(zt.left=Cr,Cr.parent=zt):zt.left=null,Fe.right=zt,zt.parent=Fe)),Nr?(qe.right=Nr,Nr.parent=qe):qe.right=null,Fe.left=qe,qe.parent=Fe)},d.prototype.replace=function(Fe,qe){Fe.parent?Fe===Fe.parent.left?Fe.parent.left=qe:Fe.parent.right=qe:this._root=qe,qe&&(qe.parent=Fe.parent)},d.prototype.minNode=function(Fe){if(Fe===void 0&&(Fe=this._root),Fe)for(;Fe.left;)Fe=Fe.left;return Fe},d.prototype.maxNode=function(Fe){if(Fe===void 0&&(Fe=this._root),Fe)for(;Fe.right;)Fe=Fe.right;return Fe},d.prototype.insert=function(Fe,qe){var zt=this._root,tr=null,Nr=this._compare;if(this._noDuplicates)for(;zt;){if(tr=zt,Nr(zt.key,Fe)===0)return;zt=Nr(zt.key,Fe)<0?zt.right:zt.left}else for(;zt;)tr=zt,zt=Nr(zt.key,Fe)<0?zt.right:zt.left;return zt={key:Fe,data:qe,left:null,right:null,parent:tr},tr?Nr(tr.key,zt.key)<0?tr.right=zt:tr.left=zt:this._root=zt,this.splay(zt),this._size++,zt},d.prototype.find=function(Fe){for(var qe=this._root,zt=this._compare;qe;){var tr=zt(qe.key,Fe);if(tr<0)qe=qe.right;else{if(!(tr>0))return qe;qe=qe.left}}return null},d.prototype.contains=function(Fe){for(var qe=this._root,zt=this._compare;qe;){var tr=zt(Fe,qe.key);if(tr===0)return!0;qe=tr<0?qe.left:qe.right}return!1},d.prototype.remove=function(Fe){var qe=this.find(Fe);if(!qe)return!1;if(this.splay(qe),qe.left)if(qe.right){var zt=this.minNode(qe.right);zt.parent!==qe&&(this.replace(zt,zt.right),zt.right=qe.right,zt.right.parent=zt),this.replace(qe,zt),zt.left=qe.left,zt.left.parent=zt}else this.replace(qe,qe.left);else this.replace(qe,qe.right);return this._size--,!0},d.prototype.removeNode=function(Fe){if(!Fe)return!1;if(this.splay(Fe),Fe.left)if(Fe.right){var qe=this.minNode(Fe.right);qe.parent!==Fe&&(this.replace(qe,qe.right),qe.right=Fe.right,qe.right.parent=qe),this.replace(Fe,qe),qe.left=Fe.left,qe.left.parent=qe}else this.replace(Fe,Fe.left);else this.replace(Fe,Fe.right);return this._size--,!0},d.prototype.erase=function(Fe){var qe=this.find(Fe);if(qe){this.splay(qe);var zt=qe.left,tr=qe.right,Nr=null;zt&&(zt.parent=null,Nr=this.maxNode(zt),this.splay(Nr),this._root=Nr),tr&&(zt?Nr.right=tr:this._root=tr,tr.parent=Nr),this._size--}},d.prototype.pop=function(){var Fe=this._root,qe=null;if(Fe){for(;Fe.left;)Fe=Fe.left;qe={key:Fe.key,data:Fe.data},this.remove(Fe.key)}return qe},d.prototype.next=function(Fe){var qe=Fe;if(qe)if(qe.right)for(qe=qe.right;qe&&qe.left;)qe=qe.left;else for(qe=Fe.parent;qe&&qe.right===Fe;)Fe=qe,qe=qe.parent;return qe},d.prototype.prev=function(Fe){var qe=Fe;if(qe)if(qe.left)for(qe=qe.left;qe&&qe.right;)qe=qe.right;else for(qe=Fe.parent;qe&&qe.left===Fe;)Fe=qe,qe=qe.parent;return qe},d.prototype.forEach=function(Fe){for(var qe=this._root,zt=[],tr=!1,Nr=0;!tr;)qe?(zt.push(qe),qe=qe.left):zt.length>0?(Fe(qe=zt.pop(),Nr++),qe=qe.right):tr=!0;return this},d.prototype.range=function(Fe,qe,zt,tr){for(var Nr=[],Cr=this._compare,Kr=this._root;Nr.length!==0||Kr;)if(Kr)Nr.push(Kr),Kr=Kr.left;else{if(Cr((Kr=Nr.pop()).key,qe)>0)break;if(Cr(Kr.key,Fe)>=0&&zt.call(tr,Kr))return this;Kr=Kr.right}return this},d.prototype.keys=function(){for(var Fe=this._root,qe=[],zt=[],tr=!1;!tr;)Fe?(qe.push(Fe),Fe=Fe.left):qe.length>0?(Fe=qe.pop(),zt.push(Fe.key),Fe=Fe.right):tr=!0;return zt},d.prototype.values=function(){for(var Fe=this._root,qe=[],zt=[],tr=!1;!tr;)Fe?(qe.push(Fe),Fe=Fe.left):qe.length>0?(Fe=qe.pop(),zt.push(Fe.data),Fe=Fe.right):tr=!0;return zt},d.prototype.at=function(Fe){for(var qe=this._root,zt=[],tr=!1,Nr=0;!tr;)if(qe)zt.push(qe),qe=qe.left;else if(zt.length>0){if(qe=zt.pop(),Nr===Fe)return qe;Nr++,qe=qe.right}else tr=!0;return null},d.prototype.load=function(Fe,qe,zt){if(Fe===void 0&&(Fe=[]),qe===void 0&&(qe=[]),zt===void 0&&(zt=!1),this._size!==0)throw new Error("bulk-load: tree is not empty");var tr=Fe.length;return zt&&b(Fe,qe,0,tr-1,this._compare),this._root=y(null,Fe,qe,0,tr),this._size=tr,this},d.prototype.min=function(){var Fe=this.minNode(this._root);return Fe?Fe.key:null},d.prototype.max=function(){var Fe=this.maxNode(this._root);return Fe?Fe.key:null},d.prototype.isEmpty=function(){return this._root===null},p.size.get=function(){return this._size},d.createTree=function(Fe,qe,zt,tr,Nr){return new d(zt,Nr).load(Fe,qe,tr)},Object.defineProperties(d.prototype,p);var w=0,k=1,M=2,F=3,$=0,U=1,H=2,Z=3;function Y(Fe,qe,zt){qe===null?(Fe.inOut=!1,Fe.otherInOut=!0):(Fe.isSubject===qe.isSubject?(Fe.inOut=!qe.inOut,Fe.otherInOut=qe.otherInOut):(Fe.inOut=!qe.otherInOut,Fe.otherInOut=qe.isVertical()?!qe.inOut:qe.inOut),qe&&(Fe.prevInResult=!ne(qe,zt)||qe.isVertical()?qe.prevInResult:qe));var tr=ne(Fe,zt);Fe.resultTransition=tr?function(Nr,Cr){var Kr,Xr=!Nr.inOut,kn=!Nr.otherInOut;switch(Cr){case $:Kr=Xr&&kn;break;case U:Kr=Xr||kn;break;case Z:Kr=Xr^kn;break;case H:Kr=Nr.isSubject?Xr&&!kn:kn&&!Xr}return Kr?1:-1}(Fe,zt):0}function ne(Fe,qe){switch(Fe.type){case w:switch(qe){case $:return!Fe.otherInOut;case U:return Fe.otherInOut;case H:return Fe.isSubject&&Fe.otherInOut||!Fe.isSubject&&!Fe.otherInOut;case Z:return!0}break;case M:return qe===$||qe===U;case F:return qe===H;case k:return!1}return!1}var ce=function(Fe,qe,zt,tr,Nr){this.left=qe,this.point=Fe,this.otherEvent=zt,this.isSubject=tr,this.type=Nr||w,this.inOut=!1,this.otherInOut=!1,this.prevInResult=null,this.resultTransition=0,this.otherPos=-1,this.outputContourId=-1,this.isExteriorRing=!0},le={inResult:{configurable:!0}};function ye(Fe,qe){return Fe[0]===qe[0]&&Fe[1]===qe[1]}ce.prototype.isBelow=function(Fe){var qe=this.point,zt=this.otherEvent.point;return this.left?(qe[0]-Fe[0])*(zt[1]-Fe[1])-(zt[0]-Fe[0])*(qe[1]-Fe[1])>0:(zt[0]-Fe[0])*(qe[1]-Fe[1])-(qe[0]-Fe[0])*(zt[1]-Fe[1])>0},ce.prototype.isAbove=function(Fe){return!this.isBelow(Fe)},ce.prototype.isVertical=function(){return this.point[0]===this.otherEvent.point[0]},le.inResult.get=function(){return this.resultTransition!==0},ce.prototype.clone=function(){var Fe=new ce(this.point,this.left,this.otherEvent,this.isSubject,this.type);return Fe.contourId=this.contourId,Fe.resultTransition=this.resultTransition,Fe.prevInResult=this.prevInResult,Fe.isExteriorRing=this.isExteriorRing,Fe.inOut=this.inOut,Fe.otherInOut=this.otherInOut,Fe},Object.defineProperties(ce.prototype,le);var we=11102230246251565e-32,Ee=134217729,Ue=(3+8*we)*we;function Le(Fe,qe,zt,tr,Nr){var Cr,Kr,Xr,kn,In=qe[0],zn=tr[0],rs=0,un=0;zn>In==zn>-In?(Cr=In,In=qe[++rs]):(Cr=zn,zn=tr[++un]);var bn=0;if(rsIn==zn>-In?(Xr=Cr-((Kr=In+Cr)-In),In=qe[++rs]):(Xr=Cr-((Kr=zn+Cr)-zn),zn=tr[++un]),Cr=Kr,Xr!==0&&(Nr[bn++]=Xr);rsIn==zn>-In?(Xr=Cr-((Kr=Cr+In)-(kn=Kr-Cr))+(In-kn),In=qe[++rs]):(Xr=Cr-((Kr=Cr+zn)-(kn=Kr-Cr))+(zn-kn),zn=tr[++un]),Cr=Kr,Xr!==0&&(Nr[bn++]=Xr);for(;rs0!=rs>0)return un;var bn=Math.abs(zn+rs);return Math.abs(un)>=Je*bn?un:-function(ys,ks,Ts,qs,di,ei,Ms){var Fs,Mn,ds,Vi,on,ns,ai,yi,ji,ga,xi,ln,Ki,Hs,Fi,$a,ho,Ea,Aa=ys-di,Qa=Ts-di,lc=ks-ei,vi=qs-ei;ft[0]=(Fi=(yi=Aa-(ai=(ns=Ee*Aa)-(ns-Aa)))*(ga=vi-(ji=(ns=Ee*vi)-(ns-vi)))-((Hs=Aa*vi)-ai*ji-yi*ji-ai*ga))-((xi=Fi-(ho=(yi=lc-(ai=(ns=Ee*lc)-(ns-lc)))*(ga=Qa-(ji=(ns=Ee*Qa)-(ns-Qa)))-(($a=lc*Qa)-ai*ji-yi*ji-ai*ga)))+(on=Fi-xi))+(on-ho),ft[1]=(Ki=Hs-((ln=Hs+xi)-(on=ln-Hs))+(xi-on))-((xi=Ki-$a)+(on=Ki-xi))+(on-$a),ft[2]=ln-((Ea=ln+xi)-(on=Ea-ln))+(xi-on),ft[3]=Ea;var da=function(Jf,Vo){for(var Fl=Vo[0],Kc=1;Kc<4;Kc++)Fl+=Vo[Kc];return Fl}(0,ft),ya=it*Ms;if(da>=ya||-da>=ya||(Fs=ys-(Aa+(on=ys-Aa))+(on-di),ds=Ts-(Qa+(on=Ts-Qa))+(on-di),Mn=ks-(lc+(on=ks-lc))+(on-ei),Vi=qs-(vi+(on=qs-vi))+(on-ei),Fs===0&&Mn===0&&ds===0&&Vi===0)||(ya=Pt*Ms+Ue*Math.abs(da),(da+=Aa*Vi+vi*Fs-(lc*ds+Qa*Mn))>=ya||-da>=ya))return da;er[0]=(Fi=(yi=Fs-(ai=(ns=Ee*Fs)-(ns-Fs)))*(ga=vi-(ji=(ns=Ee*vi)-(ns-vi)))-((Hs=Fs*vi)-ai*ji-yi*ji-ai*ga))-((xi=Fi-(ho=(yi=Mn-(ai=(ns=Ee*Mn)-(ns-Mn)))*(ga=Qa-(ji=(ns=Ee*Qa)-(ns-Qa)))-(($a=Mn*Qa)-ai*ji-yi*ji-ai*ga)))+(on=Fi-xi))+(on-ho),er[1]=(Ki=Hs-((ln=Hs+xi)-(on=ln-Hs))+(xi-on))-((xi=Ki-$a)+(on=Ki-xi))+(on-$a),er[2]=ln-((Ea=ln+xi)-(on=Ea-ln))+(xi-on),er[3]=Ea;var Nc=Le(4,ft,4,er,Ft);er[0]=(Fi=(yi=Aa-(ai=(ns=Ee*Aa)-(ns-Aa)))*(ga=Vi-(ji=(ns=Ee*Vi)-(ns-Vi)))-((Hs=Aa*Vi)-ai*ji-yi*ji-ai*ga))-((xi=Fi-(ho=(yi=lc-(ai=(ns=Ee*lc)-(ns-lc)))*(ga=ds-(ji=(ns=Ee*ds)-(ns-ds)))-(($a=lc*ds)-ai*ji-yi*ji-ai*ga)))+(on=Fi-xi))+(on-ho),er[1]=(Ki=Hs-((ln=Hs+xi)-(on=ln-Hs))+(xi-on))-((xi=Ki-$a)+(on=Ki-xi))+(on-$a),er[2]=ln-((Ea=ln+xi)-(on=Ea-ln))+(xi-on),er[3]=Ea;var Ua=Le(Nc,Ft,4,er,Vt);er[0]=(Fi=(yi=Fs-(ai=(ns=Ee*Fs)-(ns-Fs)))*(ga=Vi-(ji=(ns=Ee*Vi)-(ns-Vi)))-((Hs=Fs*Vi)-ai*ji-yi*ji-ai*ga))-((xi=Fi-(ho=(yi=Mn-(ai=(ns=Ee*Mn)-(ns-Mn)))*(ga=ds-(ji=(ns=Ee*ds)-(ns-ds)))-(($a=Mn*ds)-ai*ji-yi*ji-ai*ga)))+(on=Fi-xi))+(on-ho),er[1]=(Ki=Hs-((ln=Hs+xi)-(on=ln-Hs))+(xi-on))-((xi=Ki-$a)+(on=Ki-xi))+(on-$a),er[2]=ln-((Ea=ln+xi)-(on=Ea-ln))+(xi-on),er[3]=Ea;var Vd=Le(Ua,Vt,4,er,qt);return qt[Vd-1]}(Nr,Cr,Kr,Xr,kn,In,bn)}(Fe[0],Fe[1],qe[0],qe[1],zt[0],zt[1]);return tr>0?-1:tr<0?1:0}function Yt(Fe,qe){var zt=Fe.point,tr=qe.point;return zt[0]>tr[0]?1:zt[0]tr[1]?1:-1:function(Nr,Cr,Kr,Xr){return Nr.left!==Cr.left?Nr.left?1:-1:nr(Kr,Nr.otherEvent.point,Cr.otherEvent.point)!==0?Nr.isBelow(Cr.otherEvent.point)?-1:1:!Nr.isSubject&&Cr.isSubject?1:-1}(Fe,qe,zt)}function Xt(Fe,qe,zt){var tr=new ce(qe,!1,Fe,Fe.isSubject),Nr=new ce(qe,!0,Fe.otherEvent,Fe.isSubject);return ye(Fe.point,Fe.otherEvent.point)&&console.warn("what is that, a collapsed segment?",Fe),tr.contourId=Nr.contourId=Fe.contourId,Yt(Nr,Fe.otherEvent)>0&&(Fe.otherEvent.left=!0,Nr.left=!1),Fe.otherEvent.otherEvent=Nr,Fe.otherEvent=tr,zt.push(Nr),zt.push(tr),zt}function Rt(Fe,qe){return Fe[0]*qe[1]-Fe[1]*qe[0]}function It(Fe,qe){return Fe[0]*qe[0]+Fe[1]*qe[1]}function Jt(Fe,qe,zt){var tr=function(kn,In,zn,rs,un){var bn=[In[0]-kn[0],In[1]-kn[1]],ys=[rs[0]-zn[0],rs[1]-zn[1]];function ks(ns,ai,yi){return[ns[0]+ai*yi[0],ns[1]+ai*yi[1]]}var Ts=[zn[0]-kn[0],zn[1]-kn[1]],qs=Rt(bn,ys),di=qs*qs,ei=It(bn,bn);if(di>0){var Ms=Rt(Ts,ys)/qs;if(Ms<0||Ms>1)return null;var Fs=Rt(Ts,bn)/qs;return Fs<0||Fs>1?null:Ms===0||Ms===1?[ks(kn,Ms,bn)]:Fs===0||Fs===1?[ks(zn,Fs,ys)]:[ks(kn,Ms,bn)]}if((di=(qs=Rt(Ts,bn))*qs)>0)return null;var Mn=It(bn,Ts)/ei,ds=Mn+It(bn,ys)/ei,Vi=Math.min(Mn,ds),on=Math.max(Mn,ds);return Vi<=1&&on>=0?Vi===1?[ks(kn,Vi>0?Vi:0,bn)]:on===0?[ks(kn,on<1?on:1,bn)]:[ks(kn,Vi>0?Vi:0,bn),ks(kn,on<1?on:1,bn)]:null}(Fe.point,Fe.otherEvent.point,qe.point,qe.otherEvent.point),Nr=tr?tr.length:0;if(Nr===0||Nr===1&&(ye(Fe.point,qe.point)||ye(Fe.otherEvent.point,qe.otherEvent.point))||Nr===2&&Fe.isSubject===qe.isSubject)return 0;if(Nr===1)return ye(Fe.point,tr[0])||ye(Fe.otherEvent.point,tr[0])||Xt(Fe,tr[0],zt),ye(qe.point,tr[0])||ye(qe.otherEvent.point,tr[0])||Xt(qe,tr[0],zt),1;var Cr=[],Kr=!1,Xr=!1;return ye(Fe.point,qe.point)?Kr=!0:Yt(Fe,qe)===1?Cr.push(qe,Fe):Cr.push(Fe,qe),ye(Fe.otherEvent.point,qe.otherEvent.point)?Xr=!0:Yt(Fe.otherEvent,qe.otherEvent)===1?Cr.push(qe.otherEvent,Fe.otherEvent):Cr.push(Fe.otherEvent,qe.otherEvent),Kr&&Xr||Kr?(qe.type=k,Fe.type=qe.inOut===Fe.inOut?M:F,Kr&&!Xr&&Xt(Cr[1].otherEvent,Cr[0].point,zt),2):Xr?(Xt(Cr[0],Cr[1].point,zt),3):Cr[0]!==Cr[3].otherEvent?(Xt(Cr[0],Cr[1].point,zt),Xt(Cr[1],Cr[2].point,zt),3):(Xt(Cr[0],Cr[1].point,zt),Xt(Cr[3].otherEvent,Cr[2].point,zt),3)}function gr(Fe,qe){if(Fe===qe)return 0;if(nr(Fe.point,Fe.otherEvent.point,qe.point)!==0||nr(Fe.point,Fe.otherEvent.point,qe.otherEvent.point)!==0)return ye(Fe.point,qe.point)?Fe.isBelow(qe.otherEvent.point)?-1:1:Fe.point[0]===qe.point[0]?Fe.point[1]qe.contourId?1:-1:Yt(Fe,qe)===1?1:-1}var cr=function(){this.points=[],this.holeIds=[],this.holeOf=null,this.depth=null};function Gr(Fe,qe,zt,tr){var Nr,Cr=Fe+1,Kr=qe[Fe].point,Xr=qe.length;for(Crtr;)Cr--;return Cr}cr.prototype.isExterior=function(){return this.holeOf==null};var Er=Br,Or=Br;function Br(Fe,qe){if(!(this instanceof Br))return new Br(Fe,qe);if(this.data=Fe||[],this.length=this.data.length,this.compare=qe||$n,this.length>0)for(var zt=(this.length>>1)-1;zt>=0;zt--)this._down(zt)}function $n(Fe,qe){return Feqe?1:0}Br.prototype={push:function(Fe){this.data.push(Fe),this.length++,this._up(this.length-1)},pop:function(){if(this.length!==0){var Fe=this.data[0];return this.length--,this.length>0&&(this.data[0]=this.data[this.length],this._down(0)),this.data.pop(),Fe}},peek:function(){return this.data[0]},_up:function(Fe){for(var qe=this.data,zt=this.compare,tr=qe[Fe];Fe>0;){var Nr=Fe-1>>1,Cr=qe[Nr];if(zt(tr,Cr)>=0)break;qe[Fe]=Cr,Fe=Nr}qe[Fe]=tr},_down:function(Fe){for(var qe=this.data,zt=this.compare,tr=this.length>>1,Nr=qe[Fe];Fe=0)break;qe[Fe]=Xr,Fe=Cr}qe[Fe]=Nr}},Er.default=Or;var dr=Math.max,$r=Math.min,wn=0;function ls(Fe,qe,zt,tr,Nr,Cr){var Kr,Xr,kn,In,zn,rs;for(Kr=0,Xr=Fe.length-1;Kr0?rs.left=!0:zn.left=!0;var un=kn[0],bn=kn[1];Nr[0]=$r(Nr[0],un),Nr[1]=$r(Nr[1],bn),Nr[2]=dr(Nr[2],un),Nr[3]=dr(Nr[3],bn),tr.push(zn),tr.push(rs)}}var hs=[];function Tn(Fe,qe,zt){typeof Fe[0][0][0]=="number"&&(Fe=[Fe]),typeof qe[0][0][0]=="number"&&(qe=[qe]);var tr=function(bn,ys,ks){var Ts=null;return bn.length*ys.length==0&&(ks===$?Ts=hs:ks===H?Ts=bn:ks!==U&&ks!==Z||(Ts=bn.length===0?ys:bn)),Ts}(Fe,qe,zt);if(tr)return tr===hs?null:tr;var Nr=[1/0,1/0,-1/0,-1/0],Cr=[1/0,1/0,-1/0,-1/0],Kr=function(bn,ys,ks,Ts,qs){var di,ei,Ms,Fs,Mn,ds,Vi=new Er(null,Yt);for(Ms=0,Fs=bn.length;MsTs[2]||Ts[0]>ks[2]||ks[1]>Ts[3]||Ts[1]>ks[3])&&(qs===$?di=hs:qs===H?di=bn:qs!==U&&qs!==Z||(di=bn.concat(ys))),di}(Fe,qe,Nr,Cr,zt))return tr===hs?null:tr;for(var Xr=function(bn){var ys,ks,Ts=function(Ms){var Fs,Mn,ds,Vi,on=[];for(Mn=0,ds=Ms.length;Mn0){var xi=ns[ga];if(xi.holeOf!=null){var ln=xi.holeOf;ns[ln].holeIds.push(ai),yi.holeOf=ln,yi.depth=ns[ga].depth}else ns[ga].holeIds.push(ai),yi.holeOf=ga,yi.depth=ns[ga].depth+1}else yi.holeOf=null,yi.depth=ns[ga].depth}else yi.holeOf=null,yi.depth=0;return yi}(Ts[ys],di,Ms),Mn=function(on){qs[on]=!0,on=Ts.length)&&Ts[ds];);di.push(Fs)}};for(ys=0,ks=Ts.length;ysVi||di===H&&on.point[0]>Ts[2])break;if(on.left){Ms=ei=Mn.insert(on),ei=ei!==(Fs=Mn.minNode())?Mn.prev(ei):null,Ms=Mn.next(Ms);var ns=ei?ei.key:null;if(Y(on,ns,di),Ms&&Jt(on,Ms.key,bn)===2&&(Y(on,ns,di),Y(Ms.key,on,di)),ei&&Jt(ei.key,on,bn)===2){var ai=ei;Y(ns,(ai=ai!==Fs?Mn.prev(ai):null)?ai.key:null,di),Y(on,ns,di)}}else Ms=ei=Mn.find(on=on.otherEvent),ei&&Ms&&(ei=ei!==Fs?Mn.prev(ei):null,Ms=Mn.next(Ms),Mn.remove(on),Ms&&ei&&Jt(ei.key,Ms.key,bn))}return ds}(Kr,0,0,Nr,Cr,zt)),kn=[],In=0;In * @license MIT * @preserve */function aA(h,l,d,p){const y=[],b=p===0?(w,k,M,F,$,U)=>{w.push(new Wt(U,M+(U-k)/(F-k)*($-M)))}:(w,k,M,F,$,U)=>{w.push(new Wt(k+(U-M)/($-M)*(F-k),U))};for(const w of h){const k=[];for(const M of w){if(M.length<=2)continue;const F=[];for(let H=0;Hl&&b(F,Z,Y,ne,ce,l):le>d?ye=l&&b(F,Z,Y,ne,ce,l),ye>d&&le<=d&&b(F,Z,Y,ne,ce,d)}let $=M[M.length-1];const U=p===0?$.x:$.y;U>=l&&U<=d&&F.push($),F.length&&($=F[F.length-1],F[0].x===$.x&&F[0].y===$.y||F.push(F[0]),k.push(F))}k.length&&y.push(k)}return y}function Dbe(h,l){const d=K4(h),p=K4([l]),y=sG.intersection(d,p);return y==null?[]:iG(y)}function Lbe(h,l){let p=K4(h,65536);const y=[];for(;l.valid();l.next()){const[b,w]=l.get(),k=b.x*65536,M=b.y*65536,F=w.x*65536,$=w.y*65536,U=F-k,H=$-M,Z=Math.hypot(U,H);if(Z===0)continue;const Y=Math.trunc(H/Z*3),ne=-Math.trunc(U/Z*3);y.push([[[k,M],[F,$],[F+Y,$+ne],[k+Y,M+ne],[k,M]]])}return y.length>0&&(p=sG.diff(p,y)),iG(p,1/65536)}function K4(h,l=1){return[h.map(d=>d.map(p=>[p.x*l,p.y*l]))]}function iG(h,l=1){return h.map(d=>d.map((p,y)=>{const b=p.map(w=>new Wt(w[0]*l,w[1]*l).round());return y>0&&b.reverse(),b}))}class Z4{constructor(l,d){this.layoutVertexArray=new Wf,this.indexArray=new Fa,this.lineIndexArray=new qc,this.triangleSegments=new Hi,this.lineSegments=new Hi,this.programConfigurations=new ed(l.layers,{zoom:l.zoom,lut:l.lut}),this.uploaded=!1,d&&(this.elevatedLayoutVertexArray=new Mh)}update(l,d,p,y,b,w,k,M){this.programConfigurations.updatePaintArrays(l,d,b,p,y,w,k,M)}isEmpty(){return this.layoutVertexArray.length===0}needsUpload(){return this.programConfigurations.needsUpload}upload(l){this.uploaded||(this.layoutVertexBuffer=l.createVertexBuffer(this.layoutVertexArray,bbe.members),this.indexBuffer=l.createIndexBuffer(this.indexArray),this.lineIndexBuffer=l.createIndexBuffer(this.lineIndexArray),this.elevatedLayoutVertexArray&&this.elevatedLayoutVertexArray.length>0&&(this.elevatedLayoutVertexBuffer=l.createVertexBuffer(this.elevatedLayoutVertexArray,wbe.members))),this.programConfigurations.upload(l),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.elevatedLayoutVertexBuffer&&this.elevatedLayoutVertexBuffer.destroy(),this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.lineIndexBuffer.destroy(),this.programConfigurations.destroy(),this.triangleSegments.destroy(),this.lineSegments.destroy())}populatePaintArrays(l,d,p,y,b,w,k){this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,l,d,p,y,b,w,void 0,k)}}class Y4{constructor(l){this.zoom=l.zoom,this.pixelRatio=l.pixelRatio,this.overscaling=l.overscaling,this.layers=l.layers,this.layerIds=this.layers.map(d=>d.fqid),this.index=l.index,this.hasPattern=!1,this.patternFeatures=[],this.lut=l.lut,this.bufferData=new Z4(l,!1),this.elevationBufferData=new Z4(l,!0),this.stateDependentLayerIds=this.layers.filter(d=>d.isStateDependent()).map(d=>d.id),this.projection=l.projection,this.elevationMode=this.layers[0].layout.get("fill-elevation-reference"),this.sourceLayerIndex=l.sourceLayerIndex,this.worldview=l.worldview,this.hasAppearances=null}updateFootprints(l,d){}updateAppearances(l,d,p,y){}populate(l,d,p,y){this.hasPattern=W4("fill",this.layers,this.pixelRatio,d);const b=this.layers[0].layout.get("fill-sort-key"),w=[];for(const{feature:k,id:M,index:F,sourceLayerIndex:$}of l){const U=this.layers[0]._featureFilter.needGeometry,H=ht(k,U);if(!this.layers[0]._featureFilter.filter(new wi(this.zoom,{worldview:this.worldview,activeFloors:d.activeFloors}),H,p))continue;const Z=b?b.evaluate(H,{},p,d.availableImages):void 0,Y={id:M,properties:k.properties,type:k.type,sourceLayerIndex:$,index:F,geometry:U?H.geometry:Qe(k,p,y),patterns:{},sortKey:Z};w.push(Y)}b&&w.sort((k,M)=>k.sortKey-M.sortKey);for(const k of w){const{geometry:M,index:F,sourceLayerIndex:$}=k;if(this.hasPattern){const U=G4("fill",this.layers,k,this.zoom,this.pixelRatio,d);this.patternFeatures.push(U)}else this.addFeature(k,M,F,p,{},d.availableImages,d.brightness,d.elevationFeatures);d.featureIndex.insert(l[F].feature,M,F,$,this.index)}}update(l,d,p,y,b,w,k){this.bufferData.update(l,d,p,y,b,w,k,this.worldview),this.elevationBufferData.update(l,d,p,y,b,w,k,this.worldview),this.elevatedStructures&&this.elevatedStructures.update(l,d,p,y,b,w,k,this.worldview)}addFeatures(l,d,p,y,b,w){for(const k of this.patternFeatures)this.addFeature(k,k.geometry,k.index,d,p,y,w,l.elevationFeatures)}isEmpty(){return this.bufferData.isEmpty()&&this.elevationBufferData.isEmpty()}uploadPending(){return!this.uploaded||this.bufferData.needsUpload()||this.elevationBufferData.needsUpload()}upload(l){this.bufferData.upload(l),this.elevationBufferData.upload(l),this.elevatedStructures&&this.elevatedStructures.upload(l)}destroy(){this.bufferData.destroy(),this.elevationBufferData.destroy(),this.elevatedStructures&&this.elevatedStructures.destroy()}addFeature(l,d,p,y,b,w=[],k,M){const F=vN(d,500);this.elevationMode!=="none"?this.addElevatedRoadFeature(l,F,y,p,M):this.addGeometry(F,this.bufferData),this.bufferData.populatePaintArrays(l,p,b,w,y,k,this.worldview),this.elevationBufferData.populatePaintArrays(l,p,b,w,y,k,this.worldview)}getUnevaluatedPortalGraph(){return this.elevatedStructures?this.elevatedStructures.unevaluatedPortals:void 0}getElevationPolygons(){return this.elevatedStructures?this.elevatedStructures.portalPolygons:void 0}setEvaluatedPortalGraph(l,d,p,y,b){this.elevatedStructures&&(this.elevatedStructures.construct(l),this.elevatedStructures.populatePaintArrays(d,p,y,b,this.worldview))}addElevatedRoadFeature(l,d,p,y,b){const w=new Array,k=Ds.getElevationFeature(l,b);if(!k)return void this.addGeometry(d,this.bufferData);{const F=this.clipPolygonsToTile(d,1);F.length>0&&w.push({polygons:F,elevationFeature:k,elevationTileID:p})}const M={guardRailEnabled:this.layers[0].layout.get("fill-construct-bridge-guard-rail").evaluate(l,{},p),featureIndex:y};for(const F of w)if(F.elevationFeature){if(this.elevationMode==="hd-road-base"){this.elevatedStructures||(this.elevatedStructures=new Wc(F.elevationTileID,this.layers,this.zoom,this.lut));const U=F.elevationFeature.isTunnel();let H=0;l.properties.hasOwnProperty(kt)&&(H=+l.properties[kt]);for(const Z of F.polygons)this.elevatedStructures.addPortalCandidates(F.elevationFeature.id,Z,U,F.elevationFeature,H)}F.elevationFeature.constantHeight==null&&(F.polygons=this.prepareElevatedPolygons(F.polygons,F.elevationFeature,F.elevationTileID));const $=new Ys(p,F.elevationTileID);this.addElevatedGeometry(F.polygons,$,F.elevationFeature,this.elevationMode==="hd-road-base"?0:.05,y,M)}}addElevatedGeometry(l,d,p,y,b,w){const k={elevation:p,elevationSampler:d,bias:y,index:b,featureInfo:w},[M,F]=this.addGeometry(l,this.elevationBufferData,k);this.elevationBufferData.heightRange==null?this.elevationBufferData.heightRange={min:M,max:F}:(this.elevationBufferData.heightRange.min=Math.min(this.elevationBufferData.heightRange.min,M),this.elevationBufferData.heightRange.max=Math.max(this.elevationBufferData.heightRange.max,F))}addGeometry(l,d,p){let y=Number.POSITIVE_INFINITY,b=Number.NEGATIVE_INFINITY,w=null;p&&(w=p.elevationSampler.constantElevation(p.elevation,p.bias),w!=null&&(y=w,b=w));const k=(M,F,$)=>{if(p!=null)if(F.push(M),w!=null)d.elevatedLayoutVertexArray.emplaceBack(w),$.push(w);else{const U=p.elevationSampler.pointElevation(M,p.elevation,p.bias);d.elevatedLayoutVertexArray.emplaceBack(U),$.push(U),y=Math.min(y,U),b=Math.max(b,U)}};for(const M of l){let F=0;for(const we of M)F+=we.length;const $=d.triangleSegments.prepareSegment(F,d.layoutVertexArray,d.indexArray),U=$.vertexLength,H=[],Z=[],Y=[],ne=[],ce=[],le=d.layoutVertexArray.length;for(const we of M){if(we.length===0)continue;we!==M[0]&&Z.push(H.length/2);const Ee=d.lineSegments.prepareSegment(we.length,d.layoutVertexArray,d.lineIndexArray),Ue=Ee.vertexLength;p&&ce.push(d.layoutVertexArray.length-le),k(we[0],Y,ne),d.layoutVertexArray.emplaceBack(we[0].x,we[0].y),d.lineIndexArray.emplaceBack(Ue+we.length-1,Ue),H.push(we[0].x),H.push(we[0].y);for(let Le=1;Le0&&p&&this.elevationMode==="hd-road-base"){const we=p.elevation.isTunnel(),Ee=p.elevation.safeArea,Ue=this.elevatedStructures.addVertices(Y,ne);this.elevatedStructures.addTriangles(ye,Ue,we);const Le=ce.length;if(Le>0){for(let Ke=0;Ke=p&&Z.max.x<=b&&Z.min.y>=y&&Z.max.y<=w?M:F).push(H)}if(M.length===l.length)return l;const $=[new Wt(p,y),new Wt(b,y),new Wt(b,w),new Wt(p,w),new Wt(p,y)],U=M;for(const H of F)U.push(...Dbe(H,$));return U}}let aG,oG,lG,cG;Lr(Y4,"FillBucket",{omit:["layers","patternFeatures"]}),Lr(Z4,"FillBufferData"),Lr(Wc,"ElevatedStructures");class oA{constructor(l,d,p,y){if(this.triangleCount=d.length/3,this.min=new Wt(0,0),this.max=new Wt(0,0),this.xScale=0,this.yScale=0,this.cellsX=0,this.cellsY=0,this.cells=[],this.payload=[],this.triangleCount===0||l.length===0)return;const[b,w]=[l[0].clone(),l[0].clone()];for(let U=1;UU.cellIdx-H.cellIdx||U.triIdx-H.triIdx);let $=0;for(;$this.max.x||this.min.x>l.x||l.y>this.max.y||this.min.y>l.y)return;const p=Xf(l.x-this.min.x,this.xScale,this.cellsX),y=Xf(l.y-this.min.y,this.yScale,this.cellsY),b=this.cells[y*this.cellsX+p];if(b){this._lazyInitLookup();for(let w=0;wthis.max.x||this.min.x>d.x||l.y>this.max.y||this.min.y>d.y)return;this._lazyInitLookup();const y=Xf(l.x-this.min.x,this.xScale,this.cellsX),b=Xf(d.x-this.min.x,this.xScale,this.cellsX),w=Xf(l.y-this.min.y,this.yScale,this.cellsY),k=Xf(d.y-this.min.y,this.yScale,this.cellsY);for(let M=w;M<=k;M++)for(let F=y;F<=b;F++){const $=this.cells[M*this.cellsX+F];if($)for(let U=0;U<$.len;U++){const H=this.payload[$.start+U],Z=Math.floor(H/8),Y=1<d.fqid),this.index=l.index,this.hasPattern=!1,this.stateDependentLayerIds=this.layers.filter(d=>d.isStateDependent()).map(d=>d.id),this.footprints=[],this.worldview=l.worldview,this.hasAppearances=null}updateFootprints(l,d){for(const p of this.footprints)d.push({footprint:p,id:l})}updateAppearances(l,d,p,y){}populate(l,d,p,y){const b=[];for(const{feature:w,id:k,index:M,sourceLayerIndex:F}of l){const $=this.layers[0]._featureFilter.needGeometry,U=ht(w,$);if(!this.layers[0]._featureFilter.filter(new wi(this.zoom,{worldview:this.worldview,activeFloors:d.activeFloors}),U,p))continue;const H={id:k,properties:w.properties,type:w.type,sourceLayerIndex:F,index:M,geometry:$?U.geometry:Qe(w,p,y),patterns:{}};b.push(H)}for(const w of b){const{geometry:k,index:M,sourceLayerIndex:F}=w;this.addFeature(w,k,M,p,{},d.availableImages,d.brightness),d.featureIndex.insert(l[M].feature,k,M,F,this.index)}}isEmpty(){return this.footprints.length===0}uploadPending(){return!1}upload(l){}update(l,d,p,y,b,w,k){}destroy(){}addFeature(l,d,p,y,b,w=[],k){for(const M of vN(d,2)){const F=[],$=[],U=[],H=new Wt(1/0,1/0),Z=new Wt(-1/0,-1/0);for(const ce of M)if(ce.length!==0){ce!==M[0]&&U.push($.length/2);for(let le=0;lew===y)===void 0}(p,h.clipScope)}function lA(h,l){return h.x-l.x||h.y-l.y}function fG(h,l){return lA(h.min,l.min)===0&&lA(h.max,l.max)===0}function X4(h,l){return!(h.min.x>l.max.x||h.max.xl.max.y||h.max.ynew Wt((M.x+b.x*mr)*k-w.x*mr,(M.y+b.y*mr)*k-w.y*mr))}return Q4(d,y,h.indices,0,h.indices.length,0,0)}function gG(h,l,d,p){const y=Math.pow(2,p.z-d.z);return new Wt((h+d.x*mr)*y-p.x*mr,(l+d.y*mr)*y-p.y*mr)}function yG(h,l){const d=[];l.grid.queryPoint(h,d);const p=l.indices,y=l.vertices;for(let b=0;b0&&(p.length>1&&d.push(p),p=[])}return p.length>1&&d.push(p),d}const e3=ot.types,Gbe=["fill-extrusion-base","fill-extrusion-height","fill-extrusion-color","fill-extrusion-pattern","fill-extrusion-flood-light-wall-radius","fill-extrusion-line-width","fill-extrusion-emissive-strength"],Kbe=["fill-extrusion-flood-light-ground-radius"],Zbe=Math.pow(2,13),Ybe=Math.pow(2,15)-1,vG=new Wt(0,1),om=2147483648,_G=7,bG=450;function bN(h,l,d,p,y,b,w,k){h.emplaceBack((l<<1)+w,(d<<1)+b,(Math.floor(p*Zbe)<<1)+y,Math.round(k))}function wN(h,l,d){h.emplaceBack(l.x*mr,l.y*mr,d?1:0)}function uA(h,l,d,p,y,b){h.emplaceBack(l.x,l.y,(d.x<<1)+p,(d.y<<1)+y,b)}function jN(h,l,d){h.emplaceBack(l.x,l.y,l.z,d[0]*16384,d[1]*16384,d[2]*16384)}class wG{constructor(){this.vertexOffset=0,this.vertexCount=0,this.indexOffset=0,this.indexCount=0}}class jG{constructor(){this.centroidXY=new Wt(0,0),this.vertexArrayOffset=0,this.vertexCount=0,this.groundVertexArrayOffset=0,this.groundVertexCount=0,this.flags=0,this.footprintSegIdx=-1,this.footprintSegLen=0,this.polygonSegIdx=-1,this.polygonSegLen=0,this.min=new Wt(Number.MAX_VALUE,Number.MAX_VALUE),this.max=new Wt(-Number.MAX_VALUE,-Number.MAX_VALUE),this.height=0,this.buildingId=0}span(){return new Wt(this.max.x-this.min.x,this.max.y-this.min.y)}}class SG{constructor(){this.acc=new Wt(0,0),this.accCount=0,this.centroidDataIndex=0}startRing(l,d){l.min.x===Number.MAX_VALUE&&(l.min.x=l.max.x=d.x,l.min.y=l.max.y=d.y)}appendEdge(l,d,p){this.accCount++,this.acc._add(d);let y=!!this.borders;d.xl.max.x&&(l.max.x=d.x,y=!0),d.yl.max.y&&(l.max.y=d.y,y=!0),((d.x===0||d.x===mr)&&d.x===p.x)!=((d.y===0||d.y===mr)&&d.y===p.y)&&this.processBorderOverlap(d,p),y&&this.checkBorderIntersection(d,p)}checkBorderIntersection(l,d){d.x<0!=l.x<0&&this.addBorderIntersection(0,fn(d.y,l.y,(0-d.x)/(l.x-d.x))),d.x>mr!=l.x>mr&&this.addBorderIntersection(1,fn(d.y,l.y,(mr-d.x)/(l.x-d.x))),d.y<0!=l.y<0&&this.addBorderIntersection(2,fn(d.x,l.x,(0-d.y)/(l.y-d.y))),d.y>mr!=l.y>mr&&this.addBorderIntersection(3,fn(d.x,l.x,(mr-d.y)/(l.y-d.y)))}addBorderIntersection(l,d){this.borders||(this.borders=[[Number.MAX_VALUE,-Number.MAX_VALUE],[Number.MAX_VALUE,-Number.MAX_VALUE],[Number.MAX_VALUE,-Number.MAX_VALUE],[Number.MAX_VALUE,-Number.MAX_VALUE]]);const p=this.borders[l];dp[1]&&(p[1]=d)}processBorderOverlap(l,d){if(l.x===d.x){if(l.y===d.y)return;const p=l.x===0?0:1;this.addBorderIntersection(p,d.y),this.addBorderIntersection(p,l.y)}else{const p=l.y===0?2:3;this.addBorderIntersection(p,d.x),this.addBorderIntersection(p,l.x)}}centroid(){return this.accCount===0?new Wt(0,0):new Wt(Math.floor(Math.max(0,this.acc.x)/this.accCount),Math.floor(Math.max(0,this.acc.y)/this.accCount))}intersectsCount(){return this.borders?this.borders.reduce((l,d)=>l+ +(d[0]!==Number.MAX_VALUE),0):0}}function NG(h,l){const d=h.add(l)._unit(),p=ue(h.x*d.x+h.y*d.y,-1,1);var y,b,w;return y=Math.acos(p),Math.min(4,Math.max(-4,Math.tan(y)))/4*Ybe*((b=h).x*(w=l).y-b.y*w.x<0?-1:1)}const Xbe=[h=>h.x<0,h=>h.x>mr,h=>h.y<0,h=>h.y>mr];function Qbe(h,l,d,p){const y=[4];if(p===0)return y;d._mult(p);const b=h.sub(d),w=l.sub(d),k=[h,l,b,w];for(let M=0;M<4;M++)for(const F of k)if(Xbe[M](F)){y.push(M);break}return y}class t3{constructor(l){this.groundRadiusArray=null,this.groundRadiusBuffer=null,this.vertexArray=new ZS,this.indexArray=new Fa,this.programConfigurations=new ed(l.layers,{zoom:l.zoom,lut:l.lut},d=>Kbe.includes(d)),this._segments=new Hi,this.hiddenByLandmarkVertexArray=new _b,this._segmentToGroundQuads={},this._segmentToGroundQuads[0]=[],this._segmentToRegionTriCounts={},this._segmentToRegionTriCounts[0]=[0,0,0,0,0],this.regionSegments={},this.regionSegments[4]=new Hi}getDefaultSegment(){return this.regionSegments[4]}hasData(){return this.vertexArray.length!==0}addData(l,d,p,y=!1){const b=l.length;if(b>2){let w=Math.max(0,this._segments.get().length-1);const k=this._segments._prepareSegment(4*b,this.vertexArray.length,2*this._segmentToGroundQuads[w].length);let M;w!==this._segments.get().length-1&&(w++,this._segmentToGroundQuads[w]=[],this._segmentToRegionTriCounts[w]=[0,0,0,0,0]);{const F=l[0],$=l[1];M=NG(F.sub(l[b-1])._perp()._unit(),$.sub(F)._perp()._unit())}for(let F=0;Fy.region-b.region);for(let p=0;pM+F,0);let k=0;for(let M=0;M<=4;M++){const F=w[M];if(F!==0){let $=this.regionSegments[M];$||($=this.regionSegments[M]=new Hi);const U={vertexOffset:b.vertexOffset,primitiveOffset:b.primitiveOffset+k,vertexLength:b.vertexLength,primitiveLength:F};$.get().push(U)}k+=F}for(let M=0;M0?this.hiddenByLandmarkVertexBuffer=l.createVertexBuffer(this.hiddenByLandmarkVertexArray,Vbe.members,!0):this.hiddenByLandmarkVertexBuffer&&this.hiddenByLandmarkVertexBuffer.updateData(this.hiddenByLandmarkVertexArray),this._needsHiddenByLandmarkUpdate=!1)}destroy(){if(this.vertexBuffer){this.vertexBuffer.destroy(),this.indexBuffer.destroy(),this.hiddenByLandmarkVertexBuffer&&this.hiddenByLandmarkVertexBuffer.destroy(),this.groundRadiusBuffer&&this.groundRadiusBuffer.destroy(),this._segments&&this._segments.destroy(),this.programConfigurations.destroy();for(let l=0;l<=4;l++){const d=this.regionSegments[l];d&&d.destroy()}}}}class dA{constructor(l){this.zoom=l.zoom,this.canonical=l.canonical,this.overscaling=l.overscaling,this.layers=l.layers,this.pixelRatio=l.pixelRatio,this.layerIds=this.layers.map(d=>d.fqid),this.index=l.index,this.hasPattern=!1,this.edgeRadius=0,this.projection=l.projection,this.activeReplacements=[],this.replacementUpdateTime=0,this.centroidData=[],this.footprintIndices=new Fa,this.footprintVertices=new Wf,this.footprintSegments=[],this.layoutVertexArray=new Pg,this.centroidVertexArray=new QE,this.wallVertexArray=new lv,this.indexArray=new Fa,this.programConfigurations=new ed(l.layers,{zoom:l.zoom,lut:l.lut},d=>Gbe.includes(d)),this.segments=new Hi,this.stateDependentLayerIds=this.layers.filter(d=>d.isStateDependent()).map(d=>d.id),this.groundEffect=new t3(l),this.maxHeight=0,this.partLookup={},this.triangleSubSegments=[],this.polygonSegments=[],this.worldview=l.worldview,this.hasAppearances=null}updateFootprints(l,d){}updateAppearances(l,d,p,y){}populate(l,d,p,y){this.features=[],this.hasPattern=W4("fill-extrusion",this.layers,this.pixelRatio,d),this.featuresOnBorder=[],this.borderFeatureIndices=[[],[],[],[]],this.borderDoneWithNeighborZ=[-1,-1,-1,-1],this.selfDEMTileTimestamp=Number.MAX_VALUE,this.borderDEMTileTimestamp=[Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE],this.tileToMeter=fe(p),this.edgeRadius=this.layers[0].layout.get("fill-extrusion-edge-radius")/this.tileToMeter,this.wallMode=this.layers[0].paint.get("fill-extrusion-line-width").constantOr(1)!==0;for(const{feature:b,id:w,index:k,sourceLayerIndex:M}of l){const F=this.layers[0]._featureFilter.needGeometry,$=ht(b,F);if(!this.layers[0]._featureFilter.filter(new wi(this.zoom,{worldview:this.worldview,activeFloors:d.activeFloors}),$,p))continue;const U={id:w,sourceLayerIndex:M,index:k,geometry:F?$.geometry:Qe(b,p,y),properties:b.properties,type:b.type,patterns:{}},H=this.layoutVertexArray.length,Z=e3[U.type]==="Polygon";if(this.hasPattern)this.features.push({featureId:b.id,feature:G4("fill-extrusion",this.layers,U,this.zoom,this.pixelRatio,d)});else if(this.wallMode)for(const Y of U.geometry)for(const ne of xG(Y,Z))this.addFeature(b.id,U,[ne],k,p,{},d.availableImages,y,d.brightness);else this.addFeature(b.id,U,U.geometry,k,p,{},d.availableImages,y,d.brightness);d.featureIndex.insert(b,U.geometry,k,M,this.index,H)}this.sortBorders(),this.projection.name==="mercator"&&this.splitToSubtiles(),this.groundEffect.prepareBorderSegments(),this.polygonSegments.length=0}addFeatures(l,d,p,y,b,w){for(const{featureId:k,feature:M}of this.features){const F=e3[M.type]==="Polygon",{geometry:$}=M;if(this.wallMode)for(const U of $)for(const H of xG(U,F))this.addFeature(k,M,[H],M.index,d,p,y,b,w);else this.addFeature(k,M,$,M.index,d,p,y,b,w)}this.sortBorders(),this.projection.name==="mercator"&&this.splitToSubtiles()}update(l,d,p,y,b,w,k){this.programConfigurations.updatePaintArrays(l,d,b,p,y,w,k,this.worldview),this.groundEffect.update(l,d,b,p,y,w,k,this.worldview)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload||this.groundEffect.programConfigurations.needsUpload}upload(l){this.uploaded||(this.layoutVertexBuffer=l.createVertexBuffer(this.layoutVertexArray,Hbe),this.indexBuffer=l.createIndexBuffer(this.indexArray),this.wallVertexBuffer=l.createVertexBuffer(this.wallVertexArray,Ube.members),this.layoutVertexExtArray&&(this.layoutVertexExtBuffer=l.createVertexBuffer(this.layoutVertexExtArray,qbe.members,!0)),this.groundEffect.upload(l)),this.groundEffect.uploadPaintProperties(l),this.programConfigurations.upload(l),this.uploaded=!0}uploadCentroid(l){this.groundEffect.uploadHiddenByLandmark(l),this.needsCentroidUpdate&&(!this.centroidVertexBuffer&&this.centroidVertexArray.length>0?this.centroidVertexBuffer=l.createVertexBuffer(this.centroidVertexArray,$be.members,!0):this.centroidVertexBuffer&&this.centroidVertexBuffer.updateData(this.centroidVertexArray),this.needsCentroidUpdate=!1)}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.centroidVertexBuffer&&this.centroidVertexBuffer.destroy(),this.layoutVertexExtBuffer&&this.layoutVertexExtBuffer.destroy(),this.groundEffect.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy())}addFeature(l,d,p,y,b,w,k,M,F){const $=this.layers[0].paint.get("fill-extrusion-flood-light-ground-radius").evaluate(d,{})/this.tileToMeter,U=[new Wt(0,0),new Wt(mr,mr)],H=M.projection,Z=H.name==="globe",Y=this.wallMode||e3[d.type]==="Polygon",ne=new SG;ne.centroidDataIndex=this.centroidData.length;const ce=new jG;ce.buildingId=l,d.properties&&d.properties.hasOwnProperty("building_id")&&(ce.buildingId=d.properties.building_id);const le=this.layers[0].paint.get("fill-extrusion-base").evaluate(d,{},b)<=0,ye=this.layers[0].paint.get("fill-extrusion-height").evaluate(d,{},b);let we;if(ce.height=ye,ce.vertexArrayOffset=this.layoutVertexArray.length,ce.groundVertexArrayOffset=this.groundEffect.vertexArray.length,Z&&!this.layoutVertexExtArray&&(this.layoutVertexExtArray=new pb),this.wallMode){if(Z)return void Ge("Non zero fill-extrusion-line-width is not yet supported on globe.");if(p.length!==1)return;we=function(ft){const Ft=ft[0].x===ft[ft.length-1].x&&ft[0].y===ft[ft.length-1].y;(function(Or){let Br=0;const $n=Or.length;for(let dr=0;dr<$n;dr++)Br+=(Or[(dr+1)%$n].x-Or[dr].x)*(Or[(dr+1)%$n].y+Or[dr].y);return Br>=0})(ft)||(ft=ft.reverse());const qt={geometry:[],joinNormals:[],indices:[]},er=[],nr=[],Yt=[];let Xt=ft.length;for(;Xt>=2&&ft[Xt-1].equals(ft[Xt-2]);)Xt--;if(Xt<(Ft?3:2))return qt;let Rt,It,Jt,gr,cr,Gr=0;for(;Gr0;let wn="miter";const ls=2;wn==="miter"&&dr>ls&&(wn="bevel"),wn==="bevel"&&(dr>100&&(wn="flipbevel"),dr{const zt=new Wt(Tn.x,Tn.y),tr=new Wt(Tn.x,Tn.y);zt.x+=Js.x*qe,zt.y+=Js.y*qe,tr.x-=Js.x*Math.max(Fe,1),tr.y-=Js.y*Math.max(Fe,1),Yt.push(Js),er.push(zt),nr.push(tr)};if(wn==="miter")Br._mult(dr),hs(Rt,Br,0,0);else if(wn==="flipbevel")Br=cr.mult(-1),hs(Rt,Br,0,0),hs(Rt,Br.mult(-1),0,0);else{const Tn=-Math.sqrt(dr*dr-1),Js=$r?Tn:0,Fe=$r?0:Tn;It&&hs(Rt,gr,Js,Fe),Jt&&hs(Rt,cr,Js,Fe)}}qt.geometry=[...er,...nr.reverse(),er[0]],qt.joinNormals=[...Yt,...Yt.reverse(),Yt[Yt.length-1]];const Er=qt.geometry.length-1;for(let Or=0;Orft<(Ft.length-1)/2||ft===Ft.length-1,Ue=this.wallMode?[p]:vN(p,500);for(let ft=Ue.length-1;ft>=0;ft--){const Ft=Ue[ft];(Ft.length===0||(Le=Ft[0]).every(Vt=>Vt.x<=0)||Le.every(Vt=>Vt.x>=mr)||Le.every(Vt=>Vt.y<=0)||Le.every(Vt=>Vt.y>=mr))&&Ue.splice(ft,1)}var Le;let Ke;if(Z)Ke=IG(Ue,U,b);else{Ke=[];for(const ft of Ue)Ke.push({polygon:ft,bounds:U})}const Je=Y?this.edgeRadius:0,it=Je>0&&this.zoom<17,Pt=(ft,Ft)=>{if(ft.length===0)return!1;const Vt=ft[ft.length-1];return Ft.x===Vt.x&&Ft.y===Vt.y};for(const{polygon:ft,bounds:Ft}of Ke){let Vt=0,qt=0;for(const Xt of ft)Y&&!Xt[0].equals(Xt[Xt.length-1])&&Xt.push(Xt[0]),qt+=Y?Xt.length-1:Xt.length;const er=this.segments.prepareSegment((Y?5:4)*qt,this.layoutVertexArray,this.indexArray);ce.footprintSegIdx<0&&(ce.footprintSegIdx=this.footprintSegments.length),ce.polygonSegIdx<0&&(ce.polygonSegIdx=this.polygonSegments.length);const nr={triangleArrayOffset:this.indexArray.length,triangleCount:0,triangleSegIdx:this.segments.segments.length-1},Yt=new wG;if(Yt.vertexOffset=this.footprintVertices.length,Yt.indexOffset=3*this.footprintIndices.length,Yt.ringIndices=[],Y){const Xt=[],Rt=[];Vt=er.vertexLength;for(let Jt=0;Jt4&&EG(Rt[Rt.length-2],Rt[0],Rt[1]),Jt=Je?Jbe(Rt[Rt.length-2],Rt[0],Rt[1],Je):0;const gr=[];let cr,Gr,Er;Gr=Rt[1].sub(Rt[0])._perp()._unit();let Or=!0;for(let Br=1,$n=0;Br0?1:0,Js=dr.dist($r);if($n+Js>32768&&($n=0),Je){Er=wn.sub($r)._perp()._unit();let tr=kG(dr,$r,wn,CG(Gr,Er),Je);isNaN(tr)&&(tr=0);const Nr=$r.sub(dr)._unit();dr=dr.add(Nr.mult(Jt))._round(),$r=$r.add(Nr.mult(-tr))._round(),Jt=tr,Gr=Er,le&&this.zoom>=17&&(Pt(gr,dr)||gr.push(dr),Pt(gr,$r)||gr.push($r))}const Fe=er.vertexLength,qe=Rt.length>4&&EG(dr,$r,wn);let zt=AG($n,It,Or);if(bN(this.layoutVertexArray,dr.x,dr.y,hs,Tn,0,0,zt),bN(this.layoutVertexArray,dr.x,dr.y,hs,Tn,0,1,zt),this.wallMode){const tr=Ee(Br-1,Rt),Nr=we.joinNormals[Br-1];wN(this.wallVertexArray,Nr,tr),wN(this.wallVertexArray,Nr,tr)}if($n+=Js,zt=AG($n,qe,!Or),It=qe,bN(this.layoutVertexArray,$r.x,$r.y,hs,Tn,0,0,zt),bN(this.layoutVertexArray,$r.x,$r.y,hs,Tn,0,1,zt),this.wallMode){const tr=Ee(Br,Rt),Nr=we.joinNormals[Br];wN(this.wallVertexArray,Nr,tr),wN(this.wallVertexArray,Nr,tr)}if(er.vertexLength+=4,this.indexArray.emplaceBack(Fe+0,Fe+1,Fe+2),this.indexArray.emplaceBack(Fe+1,Fe+3,Fe+2),er.primitiveLength+=2,Je){const tr=Vt+(Br===1?Rt.length-2:Br-2),Nr=Br===1?Vt:tr+1;if(this.indexArray.emplaceBack(Fe+1,tr,Fe+3),this.indexArray.emplaceBack(tr,Nr,Fe+3),er.primitiveLength+=2,cr===void 0&&(cr=Fe),!r3(wn,Rt[Br],Ft)){const Cr=Br===Rt.length-1?cr:er.vertexLength;this.indexArray.emplaceBack(Fe+2,Fe+3,Cr),this.indexArray.emplaceBack(Fe+3,Cr+1,Cr),this.indexArray.emplaceBack(Fe+3,Nr,Cr+1),er.primitiveLength+=3}Or=!Or}if(Z){const tr=this.layoutVertexExtArray,Nr=H.projectTilePoint(dr.x,dr.y,b),Cr=H.projectTilePoint($r.x,$r.y,b),Kr=H.upVector(b,dr.x,dr.y),Xr=H.upVector(b,$r.x,$r.y);jN(tr,Nr,Kr),jN(tr,Nr,Kr),jN(tr,Cr,Xr),jN(tr,Cr,Xr)}}Y&&(Vt+=Rt.length-1),le&&Je&&this.zoom>=17&&(gr.length!==0&&Pt(gr,gr[0])&&gr.pop(),this.groundEffect.addData(gr,Ft,$,Je>0))}this.footprintSegments.push(Yt),nr.triangleCount=this.indexArray.length-nr.triangleArrayOffset,this.polygonSegments.push(nr),++ce.footprintSegLen,++ce.polygonSegLen}if(ce.vertexCount=this.layoutVertexArray.length-ce.vertexArrayOffset,ce.groundVertexCount=this.groundEffect.vertexArray.length-ce.groundVertexArrayOffset,ce.vertexCount!==0){if(ce.centroidXY=ne.borders?vG:this.encodeCentroid(ne,ce),this.centroidData.push(ce),ne.borders){this.featuresOnBorder.push(ne);const ft=this.featuresOnBorder.length-1;for(let Ft=0;Ftthis.featuresOnBorder[d].borders[l][0]-this.featuresOnBorder[p].borders[l][0])}splitToSubtiles(){const l=[];for(let k=0;kmr),$=2*F+(+(M.min.x+M.max.x>mr)^F);for(let U=0;Uk.triangleSegmentIdx===M.triangleSegmentIdx?k.subtile-M.subtile:k.triangleSegmentIdx-M.triangleSegmentIdx);let p=0,y=0,b=0;for(const k of l){if(k.triangleSegmentIdx!==p)break;b++}const w=l.length;for(;y!==l.length;){p=l[y].triangleSegmentIdx;let k=0,M=y,F=y;for(let $=M;$0&&this.triangleSubSegments.push({segment:Z,min:U,max:H}),M=F;for(let Y=M;Y[ne[0]*(1-le[0])+ce[0]*le[0],ne[1]*(1-le[1])+ce[1]*le[1]],Z=[],Y=[];for(const ne of this.triangleSubSegments){Z[0]=ne.min.x/mr,Z[1]=ne.min.y/mr,Y[0]=ne.max.x/mr,Y[1]=ne.max.y/mr;const ce=H($,U,Z),le=H($,U,Y);if(new qr([ce[0],ce[1],b],[le[0],le[1],w]).intersectsPrecise(p)===0){F&&(y.segments.push(F),F=void 0);continue}const ye=ne.segment;F&&F.vertexOffset!==ye.vertexOffset&&(y.segments.push(F),F=void 0),F?(F.vertexLength+=ye.vertexLength,F.primitiveLength+=ye.primitiveLength):F={vertexOffset:ye.vertexOffset,primitiveLength:ye.primitiveLength,vertexLength:ye.vertexLength,primitiveOffset:ye.primitiveOffset,sortKey:void 0,vaos:{}}}return F&&y.segments.push(F),y}encodeCentroid(l,d){const p=l.centroid(),y=d.span(),b=Math.min(7,Math.round(y.x*this.tileToMeter/10)),w=Math.min(7,Math.round(y.y*this.tileToMeter/10));return new Wt(ue(p.x,1,mr-1)<<3|b,ue(p.y,1,mr-1)<<3|w)}encodeBorderCentroid(l){if(!l.borders)return new Wt(0,0);const d=l.borders,p=Number.MAX_VALUE;if(d[0][0]!==p||d[1][0]!==p){const y=d[0][0]!==p?0:1;return new Wt(6|(d[0][0]!==p?0:65528),(d[y][0]+d[y][1])/2<<3|6)}{const y=d[2][0]!==p?2:3;return new Wt((d[y][0]+d[y][1])/2<<3|6,6|(d[2][0]!==p?0:65528))}}showCentroid(l){const d=this.centroidData[l.centroidDataIndex];d.flags&=2147483647,d.centroidXY.x=0,d.centroidXY.y=0,this.writeCentroidToBuffer(d)}writeCentroidToBuffer(l){this.groundEffect.updateHiddenByLandmark(l);const d=l.vertexArrayOffset,p=l.vertexCount+l.vertexArrayOffset,y=l.flags&om?vG:l.centroidXY,b=this.centroidVertexArray.geta_centroid_pos0(d);if(this.centroidVertexArray.geta_centroid_pos1(d)!==y.y||b!==y.x){for(let w=d;wM.max.x||M.min.x>w.max.x||w.min.y>M.max.y||M.min.y>w.max.y||w.footprint.buildingIds.has(M.buildingId)&&(M.flags|=om);else for(const M of this.centroidData)if(!(M.flags&om||w.min.x>M.max.x||M.min.x>w.max.x||w.min.y>M.max.y||M.min.y>w.max.y))for(let F=0;Fd!=Z>d&&l<(this.footprintVertices.int16[2*($+w.vertexOffset)+0]-U)*(d-H)/(Z-H)+U&&(y=!y)}k=M}}return y}getHeightAtTileCoord(l,d){let p=Number.NEGATIVE_INFINITY,y=!0;const b=4*(l+mr)*mr+(d+mr);if(this.partLookup.hasOwnProperty(b)){const w=this.partLookup[b];return w?{height:w.height,hidden:!!(w.flags&om)}:void 0}for(const w of this.centroidData)l>w.max.x||w.min.x>l||d>w.max.y||w.min.y>d||w.height<=p||this.footprintContainsPoint(l,d,w)&&(p=w.height,this.partLookup[b]=w,y=!!(w.flags&om));if(p!==Number.NEGATIVE_INFINITY)return{height:p,hidden:y};this.partLookup[b]=void 0}}function CG(h,l){const d=h.add(l)._unit();return h.x*d.x+h.y*d.y}function Jbe(h,l,d,p){const y=l.sub(h)._perp()._unit(),b=d.sub(l)._perp()._unit();return kG(h,l,d,CG(y,b),p)}function kG(h,l,d,p,y){const b=Math.sqrt(1-p*p);return Math.min(h.dist(l)/3,l.dist(d)/3,y*b/p)}function r3(h,l,d){return h.xd[1].x&&l.x>d[1].x||h.yd[1].y&&l.y>d[1].y}function TG(h,l){return h.xl[1].x||h.yl[1].y}function EG(h,l,d){if(h.x<0||h.x>=mr||l.x<0||l.x>=mr||d.x<0||d.x>=mr)return!1;const p=d.sub(l),y=p.perp(),b=h.sub(l);return(p.x*b.x+p.y*b.y)/Math.sqrt((p.x*p.x+p.y*p.y)*(b.x*b.x+b.y*b.y))>-.866&&y.x*b.x+y.y*b.y<0}function AG(h,l,d){const p=l?2|h:-3&h;return d?1|p:-2&p}function PG(){const h=Math.PI/32,l=Math.tan(h),d=x;return d*Math.sqrt(1+2*l*l)-d}function IG(h,l,d){const p=1<{for(const Je of Le)Y.push({polygon:Je,bounds:Ke})},ce=Math.ceil(Math.log2($)),le=Math.ceil(Math.log2(U)),ye=ce-le,we=[];for(let Le=0;Le0?0:1);for(let Le=0;LeKe+1?Ue.push({polygons:qt,bounds:nr,depth:Ke+1}):ne(qt,nr)}if(er.length){const nr=[new Wt(Je===0?Vt:it.x,Je===1?Vt:it.y),Pt];we.length>Ke+1?Ue.push({polygons:er,bounds:nr,depth:Ke+1}):ne(er,nr)}}return Y}(h,l,Math.ceil((b-y)/11.25),Math.ceil((w-k)/11.25),1,(M,F,$)=>{if(M===0)return .5*(F+$);{const U=ee((d.y+F/mr)/p);return(B(.5*(ee((d.y+$/mr)/p)+U))*p-d.y)*mr}})}function ewe(h,l,d,p,y,b){const w=Math.pow(2,p.z-y.z);for(let k=0;k=M[w]&&(k=l,M=h),k[w]y&&DG(k,M,w,y),k[w]b&&DG(M,k,w,b)}}function hA(h,l,d,p,y,b){const w=[];for(let k=0;k=p&&Y.x>=p||(Z.x>=p?Z=new Wt(p,Z.y+(p-Z.x)/(Y.x-Z.x)*(Y.y-Z.y))._round():Y.x>=p&&(Y=new Wt(p,Z.y+(p-Z.x)/(Y.x-Z.x)*(Y.y-Z.y))._round()),Z.y>=y&&Y.y>=y||(Z.y>=y?Z=new Wt(Z.x+(y-Z.y)/(Y.y-Z.y)*(Y.x-Z.x),y)._round():Y.y>=y&&(Y=new Wt(Z.x+(y-Z.y)/(Y.y-Z.y)*(Y.x-Z.x),y)._round()),F&&Z.equals(F[F.length-1])||(F=[Z],w.push(F),b&&b.push({progress:{min:ce+FG(le,ye,Z)*ne,max:1},parentIndex:k,prevPoint:le,nextPoint:ye})),F.push(Y),b&&(b[b.length-1].progress.max=ce+FG(le,ye,Y)*ne,b[b.length-1].nextPoint=ye)))))}if(b&&U>0)for(let H=$;HF.t-$.t);let w=0,k=0,M=[];for(p.push(M);w!==h.length;){if(k===b.length){for(;w!==h.length;)M.length!==0&&M[M.length-1].equals(h[w])||M.push(h[w]),w++;break}b[k].t<=w?(M.length!==0&&M[M.length-1].equals(b[k].point)||M.push(b[k].point),Math.trunc(b[k].t),k++):(M.length!==0&&M[M.length-1].equals(h[w])||M.push(h[w]),w++)}}function FG(h,l,d){return h.x!==l.x?(d.x-h.x)/(l.x-h.x):h.y!==l.y?(d.y-h.y)/(l.y-h.y):0}function SN(h,l){return h.x*l.x+h.y*l.y}function zG(h,l){if(h.length===1){let d=0;const p=l[d++];let y;for(;!y||p.equals(y);)if(y=l[d++],!y)return 1/0;for(;d{Vt[0]=qt,Vt[1]=er,Vt[2]=nr,Vt[3]=1},Ft=PG();Z>0&&(Z+=Ft),Y+=Ft;for(const Vt of H){const qt=[],er=[];for(const nr of Vt){const Yt=nr.x+ne.x,Xt=nr.y+ne.y,Rt=U.projection.projectTilePoint(Yt,Xt,Ue),It=U.projection.upVector(Ue,nr.x,nr.y);let Jt=Z,gr=Y;if(le){const cr=UG(Yt,Xt,Z,Y,le,ye,we,Ee);Jt+=cr.base,gr+=cr.top}Z!==0?ft(it,Rt.x+It[0]*Je*Jt,Rt.y+It[1]*Je*Jt,Rt.z+It[2]*Je*Jt):ft(it,Rt.x,Rt.y,Rt.z),ft(Pt,Rt.x+It[0]*Je*gr,Rt.y+It[1]*Je*gr,Rt.z+It[2]*Je*gr),ut(it,it,ce),ut(Pt,Pt,ce),qt.push(new xv(it[0],it[1],it[2])),er.push(new xv(Pt[0],Pt[1],Pt[2]))}Le.push(qt),Ke.push(er)}return[Le,Ke]}(h,l,d,p,y,b,w,k,M,F,$):w?function(U,H,Z,Y,ne,ce,le,ye,we){const Ee=[],Ue=[],Le=[0,0,0,1];for(const Ke of U){const Je=[],it=[];for(const Pt of Ke){const ft=Pt.x+Y.x,Ft=Pt.y+Y.y,Vt=UG(ft,Ft,H,Z,ce,le,ye,we);Le[0]=ft,Le[1]=Ft,Le[2]=Vt.base,Le[3]=1,rr(Le,Le,ne),Le[3]=Math.max(Le[3],1e-5);const qt=new xv(Le[0]/Le[3],Le[1]/Le[3],Le[2]/Le[3]);Le[0]=ft,Le[1]=Ft,Le[2]=Vt.top,Le[3]=1,rr(Le,Le,ne),Le[3]=Math.max(Le[3],1e-5);const er=new xv(Le[0]/Le[3],Le[1]/Le[3],Le[2]/Le[3]);Je.push(qt),it.push(er)}Ee.push(Je),Ue.push(it)}return[Ee,Ue]}(l,d,p,y,b,w,k,M,F):function(U,H,Z,Y,ne){const ce=[],le=[],ye=ne[8]*H,we=ne[9]*H,Ee=ne[10]*H,Ue=ne[11]*H,Le=ne[8]*Z,Ke=ne[9]*Z,Je=ne[10]*Z,it=ne[11]*Z;for(const Pt of U){const ft=[],Ft=[];for(const Vt of Pt){const qt=Vt.x+Y.x,er=Vt.y+Y.y,nr=ne[0]*qt+ne[4]*er+ne[12],Yt=ne[1]*qt+ne[5]*er+ne[13],Xt=ne[2]*qt+ne[6]*er+ne[14],Rt=ne[3]*qt+ne[7]*er+ne[15],It=nr+ye,Jt=Yt+we,gr=Xt+Ee,cr=Math.max(Rt+Ue,1e-5),Gr=nr+Le,Er=Yt+Ke,Or=Xt+Je,Br=Math.max(Rt+it,1e-5);ft.push(new xv(It/cr,Jt/cr,gr/cr)),Ft.push(new xv(Gr/Br,Er/Br,Or/Br))}ce.push(ft),le.push(Ft)}return[ce,le]}(l,d,p,y,b)}function UG(h,l,d,p,y,b,w,k){const M=w*y.getElevationAt(h,l,!0,!0),F=b[0]!==0,$=F?b[1]===0?w*(b[0]/_G-bG):w*function(U,H,Z){const Y=Math.floor(H[0]/8),ne=Math.floor(H[1]/8),ce=10*(H[0]-8*Y),le=10*(H[1]-8*ne),ye=U.getElevationAt(Y,ne,!0,!0),we=U.getMeterToDEM(Z),Ee=Math.floor(.5*(ce*we-1)),Ue=Math.floor(.5*(le*we-1)),Le=U.tileCoordToPixel(Y,ne),Ke=2*Ee+1,Je=2*Ue+1,it=function(er,nr,Yt,Xt,Rt){return[er.getElevationAtPixel(nr,Yt,!0),er.getElevationAtPixel(nr+Rt,Yt,!0),er.getElevationAtPixel(nr,Yt+Rt,!0),er.getElevationAtPixel(nr+Xt,Yt+Rt,!0)]}(U,Le.x-Ee,Le.y-Ue,Ke,Je),Pt=Math.abs(it[0]-it[1]),ft=Math.abs(it[2]-it[3]),Ft=Math.abs(it[0]-it[2])+Math.abs(it[1]-it[3]),Vt=Math.min(.25,.5*we*(Pt+ft)/Ke),qt=Math.min(.25,.5*we*Ft/Je);return ye+Math.max(Vt*ce,qt*le)}(y,b,k):M;return{base:M+(d===0?-1:d),top:F?Math.max($+p,M+d+2):M+p}}class rwe{constructor(l){this._callback=l,this._triggered=!1,typeof MessageChannel<"u"&&(this._channel=new MessageChannel,this._channel.port2.onmessage=()=>{this._triggered=!1,this._callback()})}trigger(){this._triggered||(this._triggered=!0,this._channel?this._channel.port1.postMessage(!0):setTimeout(()=>{this._triggered=!1,this._callback()},0))}remove(){this._channel=void 0,this._callback=()=>{}}}class nwe{constructor(){this.tasks={},this.taskQueue=[],dt(["process"],this),this.invoker=new rwe(this.process),this.nextId=0}add(l,d){const p=this.nextId++,y=function({type:b,isSymbolTile:w,zoom:k}){return k=k||0,b==="message"?0:b!=="maybePrepare"||w?b!=="parseTile"||w?b==="parseTile"&&w?300-k:b==="maybePrepare"&&w?400-k:500:200-k:100-k}(d);if(y===0){try{l()}finally{}return null}return this.tasks[p]={fn:l,metadata:d,priority:y,id:p},this.taskQueue.push(p),this.invoker.trigger(),{cancel:()=>{delete this.tasks[p]}}}process(){try{if(this.taskQueue=this.taskQueue.filter(p=>!!this.tasks[p]),!this.taskQueue.length)return;const l=this.pick();if(l===null)return;const d=this.tasks[l];if(delete this.tasks[l],this.taskQueue.length&&this.invoker.trigger(),!d)return;d.fn()}finally{}}pick(){let l=null,d=1/0;for(let y=0;y{p&&delete this.callbacks[k],this.target.postMessage({id:k,type:"",targetMapId:y,sourceMapId:this.mapId})}}}receive(l){const d=l.data;if(!d)return;const p=d.id;if(p&&(!d.targetMapId||this.mapId===d.targetMapId))if(d.type===""){const y=this.cancelCallbacks[p];delete this.cancelCallbacks[p],y&&y.cancel()}else if(d.mustQueue||cn(self)){const y=this.callbacks[p],b=this.scheduler.add(()=>this.processTask(p,d),y&&y.metadata||{type:"message"});b&&(this.cancelCallbacks[p]=b)}else this.processTask(p,d)}processTask(l,d){if(delete this.cancelCallbacks[l],d.type===""){const p=this.callbacks[l];delete this.callbacks[l],p&&(d.error?p(Hf(d.error)):p(null,Hf(d.data)))}else{const p=new Set,y=d.hasCallback?(w,k)=>{this.target.postMessage({id:l,type:"",sourceMapId:this.mapId,error:w?Eh(w):null,data:Eh(k,p)},p)}:()=>{},b=Hf(d.data);if(this.parent[d.type])this.parent[d.type](d.sourceMapId,b,y);else if(this.parent.getWorkerSource){const w=d.type.split("."),{source:k,scope:M}=b;this.parent.getWorkerSource(d.sourceMapId,w[0],k,M)[w[1]](b,y)}else y(new Error(`Could not find function ${d.type}`))}}remove(){this.scheduler.remove(),this.target.removeEventListener("message",this.receive,!1)}}var NN={workerUrl:"",workerClass:null,workerParams:void 0};const n3="mapboxgl_preloaded_worker_pool";class vv{constructor(l){this.active={},this.name=l}acquire(l,d=vv.workerCount){if(!this.workers)for(this.workers=[];this.workers.length{d.terminate()}),this.workers=null)}isPreloaded(){return!!this.active[n3]}numActive(){return Object.keys(this.active).length}}vv.workerCount=2;class Ob{constructor(l,d,p="Worker",y=vv.workerCount){this.workerPool=l,this.actors=[],this.currentActor=0,this.id=lt();const b=this.workerPool.acquire(this.id,y);for(let w=0;w{this.ready=!0})}broadcast(l,d,p){tt(this.actors,(y,b)=>{y.send(l,d,b)},p=p||function(){})}getActor(){return this.currentActor=(this.currentActor+1)%this.actors.length,this.actors[this.currentActor]}remove(){this.actors.forEach(l=>{l.remove()}),this.actors=[],this.workerPool.release(this.id)}}let CN,s3;function fA(){return CN||(CN=new vv),CN}Ob.Actor=VG;const i3=4096;class swe{constructor(l){this.module=l,this.memoryStack=this.module.malloc(i3),this.memoryStackNextFree=this.memoryStack}createIntArray(l){const d=this.memoryStackNextFree;return this.memoryStackNextFree+=l.length*Int32Array.BYTES_PER_ELEMENT,this.memoryStackNextFree-this.memoryStack>i3?-1:(new Int32Array(this.module.heap32.buffer,d,l.length).set(l),d)}createFloatArray(l){const d=this.memoryStackNextFree;return this.memoryStackNextFree+=l.length*Float32Array.BYTES_PER_ELEMENT,this.memoryStackNextFree-this.memoryStack>i3?-1:(new Float32Array(this.module.heapF32.buffer,d,l.length).set(l),d)}readStringBuffer(l){let d="";for(;this.module.heapU8[l]!==0;)d+=String.fromCharCode(this.module.heapU8[l]),++l;return d}setStyle(l){const d=l.normalScale;this.module.setStyle(d[0],d[1],d[2],l.tileToMeters)}setAOOptions(l,d){this.module.setAOOptions(l?1:0,d)}setMetricOptions(l,d){this.module.setMetricOptions(l?1:0,d)}setStructuralOptions(l){this.module.setStructuralOptions(l?1:0)}setFacadeOptions(l,d){this.module.setFacadeOptions(l,d?1:0)}setFauxFacadeOptions(l,d,p){this.module.setFauxFacadeOptions(l?1:0,d?1:0,p)}setFacadeClassifierOptions(l){this.module.setFacadeClassifierOptions(l)}generateMesh(l,d){this.memoryStackNextFree=this.memoryStack;for(const k of l){const M=this.createIntArray(k.ringIndices),F=this.createFloatArray(k.coordinates);if(M===-1||F===-1)return`building_gen: Out of stack memory: ${this.memoryStackNextFree-this.memoryStack}/4096`;this.module.addFeature(k.id,k.sourceId,k.minHeight,k.height,k.roofType,F,M,k.ringIndices.length-1)}for(const k of d){let M;M=k.entrances?JSON.parse(k.entrances):[];const F=this.createFloatArray(M),$=this.createFloatArray(k.coordinates);if(F===-1||$===-1)return`building_gen: Out of stack memory: ${this.memoryStackNextFree-this.memoryStack}/4096`;this.module.addFacade(k.sourceId,k.crossPerc,k.distanceToRoad,F,M.length,$,k.coordinates.length)}if(!this.module.generateMesh()){const k=this.module.getLastError();return this.readStringBuffer(k)}const p=this.module.getMeshCount(),y=new Array(p);for(let k=0;ky.arrayBuffer()).then(y=>{l.buffers[d]=y})}function XG(h,l){const d=h.json.bufferViews[l];return new Uint8Array(h.buffers[d.buffer],d.byteOffset||0,d.byteLength)}function uwe(h,l,d,p){if(h.uri){const y=YG(h.uri,p);return fetch(y).then(b=>b.blob()).then(b=>createImageBitmap(b)).then(b=>{l.images[d]=b})}if(h.bufferView!==void 0){const y=XG(l,h.bufferView),b=new Blob([y],{type:h.mimeType});return createImageBitmap(b).then(w=>{l.images[d]=w})}}function QG(h,l=0,d){const p={json:null,images:[],buffers:[]};if(new Uint32Array(h,l,1)[0]===KG){const $=new Uint32Array(h,l);let U=2;const H=($[U++]>>2)-3,Z=$[U++]>>2;if(U++,p.json=JSON.parse(ZG.decode($.subarray(U,U+Z))),U+=Z,U{const $=[],U=k&&k.includes(l3),H=k&&k.includes(gA);if(U&&$.push(function(){if(!$h)return kN??(kN=function(Z){let Y,ne=null;function ce(){Y=new Uint8Array(ne.buffer)}function le(){throw new Error("Unexpected Draco error.")}const ye={a:{a:le,d:function(we,Ee,Ue){return Y.copyWithin(we,Ee,Ee+Ue)},c:function(we){const Ee=Y.length,Ue=Math.max(we>>>0,Math.ceil(1.2*Ee)),Le=Math.ceil((Ue-Ee)/65536);try{return ne.grow(Le),ce(),!0}catch{return!1}},b:le}};return(WebAssembly.instantiateStreaming?WebAssembly.instantiateStreaming(Z,ye):Z.then(we=>we.arrayBuffer()).then(we=>WebAssembly.instantiate(we,ye))).then(we=>{const{Rb:Ee,Qb:Ue,P:Le,T:Ke,X:Je,Ja:it,La:Pt,Qa:ft,Va:Ft,Wa:Vt,eb:qt,jb:er,f:nr,e:Yt,yb:Xt,zb:Rt,Ab:It,Bb:Jt,Db:gr,Gb:cr}=we.instance.exports;ne=Yt;const Gr=(()=>{let Er=0,Or=0,Br=0,$n=0;return dr=>{Br&&(Ee($n),Ee(Er),Or+=Br,Br=Er=0),Er||(Or+=128,Er=Ue(Or));const $r=dr.length+7&-8;let wn=Er;$r>=Or&&(Br=$r,wn=$n=Ue($r));for(let ls=0;ls{$h=Z,kN=void 0}))}()),H&&$.push(function(){if(o3)return;const Z=function(Y){let ne;const ce=WebAssembly.instantiateStreaming(Y,{}).then(we=>{ne=we.instance,ne.exports.__wasm_call_ctors()}),le={NONE:"",OCTAHEDRAL:"meshopt_decodeFilterOct",QUATERNION:"meshopt_decodeFilterQuat",EXPONENTIAL:"meshopt_decodeFilterExp"},ye={ATTRIBUTES:"meshopt_decodeVertexBuffer",TRIANGLES:"meshopt_decodeIndexBuffer",INDICES:"meshopt_decodeIndexSequence"};return{ready:ce,supported:!0,decodeGltfBuffer(we,Ee,Ue,Le,Ke,Je){(function(it,Pt,ft,Ft,Vt,qt,er){const nr=it.exports.sbrk,Yt=Ft+3&-4,Xt=nr(Yt*Vt),Rt=nr(qt.length),It=new Uint8Array(it.exports.memory.buffer);It.set(qt,Rt);const Jt=Pt(Xt,Ft,Vt,Rt,qt.length);if(Jt===0&&er&&er(Xt,Yt,Vt),ft.set(It.subarray(Xt,Xt+Ft*Vt)),nr(Xt-nr(0)),Jt!==0)throw new Error(`Malformed buffer data: ${Jt}`)})(ne,ne.exports[ye[Ke]],we,Ee,Ue,Le,ne.exports[le[Je]])}}}(fetch(WG()));return Z.ready.then(()=>{o3=Z})}()),b)for(let Z=0;Z{if(U&&w)for(const{primitives:Z}of w)for(const Y of Z)owe(Y,p);if(H&&w&&M)for(const Z of M)lwe(Z,p);return p})})}function JG(h){return fetch(h).then(l=>l.arrayBuffer()).then(l=>QG(l,0,h))}function c3(h){switch(h){case WebGL2RenderingContext.RGBA8:return WebGL2RenderingContext.RGBA;case WebGL2RenderingContext.DEPTH_COMPONENT16:return WebGL2RenderingContext.DEPTH_COMPONENT;case WebGL2RenderingContext.DEPTH24_STENCIL8:return WebGL2RenderingContext.DEPTH_STENCIL;case WebGL2RenderingContext.R8:case WebGL2RenderingContext.R32F:return WebGL2RenderingContext.RED}}function u3(h){switch(h){case WebGL2RenderingContext.RGBA8:return WebGL2RenderingContext.UNSIGNED_BYTE;case WebGL2RenderingContext.DEPTH_COMPONENT16:return WebGL2RenderingContext.UNSIGNED_SHORT;case WebGL2RenderingContext.DEPTH24_STENCIL8:return WebGL2RenderingContext.UNSIGNED_INT_24_8;case WebGL2RenderingContext.R8:return WebGL2RenderingContext.UNSIGNED_BYTE;case WebGL2RenderingContext.R32F:return WebGL2RenderingContext.FLOAT}}class d3{constructor(l,d,p,y){this.context=l,this.format=p,this.useMipmap=y&&y.useMipmap,this.texture=l.gl.createTexture(),this.update(d,{premultiply:y&&y.premultiply})}update(l,d){const p=l&&l instanceof HTMLVideoElement&&l.width===0?l.videoWidth:l.width,y=l&&l instanceof HTMLVideoElement&&l.height===0?l.videoHeight:l.height,{context:b}=this,{gl:w}=b,{x:k,y:M}=d&&d.position?d.position:{x:0,y:0},F=k+p,$=M+y;!this.size||this.size[0]===F&&this.size[1]===$||(w.bindTexture(w.TEXTURE_2D,null),w.deleteTexture(this.texture),this.texture=w.createTexture(),this.size=null),w.bindTexture(w.TEXTURE_2D,this.texture),b.pixelStoreUnpackFlipY.set(!1),b.pixelStoreUnpack.set(1),b.pixelStoreUnpackPremultiplyAlpha.set(this.format===w.RGBA8&&(!d||d.premultiply!==!1));const U=l instanceof HTMLImageElement||l instanceof HTMLCanvasElement||l instanceof HTMLVideoElement||l instanceof ImageData||ImageBitmap&&l instanceof ImageBitmap;if(!this.size&&F>0&&$>0){const H=this.useMipmap?Math.floor(Math.log2(Math.max(F,$)))+1:1;w.texStorage2D(w.TEXTURE_2D,H,this.format,F,$),this.size=[F,$]}this.size&&(U?w.texSubImage2D(w.TEXTURE_2D,0,k,M,c3(this.format),u3(this.format),l):"data"in l&&l.data&&w.texSubImage2D(w.TEXTURE_2D,0,k,M,p,y,c3(this.format),u3(this.format),l.data)),this.useMipmap&&w.generateMipmap(w.TEXTURE_2D)}bind(l,d,p=!1){const{context:y}=this,{gl:b}=y;b.bindTexture(b.TEXTURE_2D,this.texture),l!==this.minFilter&&(b.texParameteri(b.TEXTURE_2D,b.TEXTURE_MAG_FILTER,l),b.texParameteri(b.TEXTURE_2D,b.TEXTURE_MIN_FILTER,this.useMipmap&&!p?l===b.NEAREST?b.NEAREST_MIPMAP_NEAREST:b.LINEAR_MIPMAP_LINEAR:l),this.minFilter=l),d!==this.wrapS&&(b.texParameteri(b.TEXTURE_2D,b.TEXTURE_WRAP_S,d),b.texParameteri(b.TEXTURE_2D,b.TEXTURE_WRAP_T,d),this.wrapS=d)}bindExtraParam(l,d,p,y,b){const{context:w}=this,{gl:k}=w;k.bindTexture(k.TEXTURE_2D,this.texture),d!==this.magFilter&&(k.texParameteri(k.TEXTURE_2D,k.TEXTURE_MAG_FILTER,d),this.magFilter=d),l!==this.minFilter&&(k.texParameteri(k.TEXTURE_2D,k.TEXTURE_MIN_FILTER,this.useMipmap?l===k.NEAREST?k.NEAREST_MIPMAP_NEAREST:k.LINEAR_MIPMAP_LINEAR:l),this.minFilter=l),p!==this.wrapS&&(k.texParameteri(k.TEXTURE_2D,k.TEXTURE_WRAP_S,p),this.wrapS=p),y!==this.wrapT&&(k.texParameteri(k.TEXTURE_2D,k.TEXTURE_WRAP_T,y),this.wrapT=y),b!==this.compareMode&&(b?(k.texParameteri(k.TEXTURE_2D,k.TEXTURE_COMPARE_MODE,k.COMPARE_REF_TO_TEXTURE),k.texParameteri(k.TEXTURE_2D,k.TEXTURE_COMPARE_FUNC,b)):k.texParameteri(k.TEXTURE_2D,k.TEXTURE_COMPARE_MODE,k.NONE),this.compareMode=b)}destroy(){const{gl:l}=this.context;l.deleteTexture(this.texture),this.texture=null}}class EN{constructor(l,d){this.context=l,this.texture=d}bind(l,d){const{context:p}=this,{gl:y}=p;y.bindTexture(y.TEXTURE_2D,this.texture),l!==this.minFilter&&(y.texParameteri(y.TEXTURE_2D,y.TEXTURE_MAG_FILTER,l),y.texParameteri(y.TEXTURE_2D,y.TEXTURE_MIN_FILTER,l),this.minFilter=l),d!==this.wrapS&&(y.texParameteri(y.TEXTURE_2D,y.TEXTURE_WRAP_S,d),y.texParameteri(y.TEXTURE_2D,y.TEXTURE_WRAP_T,d),this.wrapS=d)}}const dwe=ts([{name:"a_pos_3f",components:3,type:"Float32"}]),hwe=ts([{name:"a_color_3f",components:3,type:"Float32"}]),fwe=ts([{name:"a_color_4f",components:4,type:"Float32"}]),pwe=ts([{name:"a_uv_2f",components:2,type:"Float32"}]),mwe=ts([{name:"a_normal_3f",components:3,type:"Float32"}]),gwe=ts([{name:"a_normal_matrix0",components:4,type:"Float32"},{name:"a_normal_matrix1",components:4,type:"Float32"},{name:"a_normal_matrix2",components:4,type:"Float32"},{name:"a_normal_matrix3",components:4,type:"Float32"}]),ywe=ts([{name:"a_pbr",components:4,type:"Uint16"},{name:"a_heightBasedEmissiveStrength",components:3,type:"Float32"}]);function e9(h,l){const d=yA(h.projection,h.zoom,h.width,h.height),p=function(b,w,k,M,F){const $=new f(k.lng-180*$g,k.lat),U=new f(k.lng+180*$g,k.lat),H=b.project($.lng,$.lat),Z=b.project(U.lng,U.lat),Y=-Math.atan2(Z.y-H.y,Z.x-H.x),ne=Ne.fromLngLat(k);ne.y=ue(ne.y,-1+$g,1-$g);const ce=ne.toLngLat(),le=b.project(ce.lng,ce.lat),ye=Ne.fromLngLat(ce);ye.x+=$g;const we=ye.toLngLat(),Ee=b.project(we.lng,we.lat),Ue=r9(Ee.x-le.x,Ee.y-le.y,Y),Le=Ne.fromLngLat(ce);Le.y+=$g;const Ke=Le.toLngLat(),Je=b.project(Ke.lng,Ke.lat),it=r9(Je.x-le.x,Je.y-le.y,Y),Pt=Math.abs(Ue.x)/Math.abs(it.y),ft=I([]);Q(ft,ft,-Y*(1-(F?0:M)));const Ft=I([]);return W(Ft,Ft,[1,1-(1-Pt)*M,1]),Ft[4]=-it.x/it.y*M,Q(Ft,Ft,Y),R(Ft,ft,Ft),Ft}(h.projection,0,h.center,d,l),y=t9(h);return W(p,p,[y,y,1]),p}function t9(h){const l=h.projection,d=yA(h.projection,h.zoom,h.width,h.height),p=h3(l,h.center),y=h3(l,f.convert(l.center));return Math.pow(2,p*d+(1-d)*y)}function yA(h,l,d,p,y=1/0){const b=h.range;if(!b)return 0;const w=Math.min(y,Math.max(d,p)),k=Math.log2(w/1024);return be(b[0]+k,b[1]+k,l)}const $g=1/4e4;function h3(h,l){const d=ue(l.lat,-re,re),p=new f(l.lng-180*$g,d),y=new f(l.lng+180*$g,d),b=h.project(p.lng,d),w=h.project(y.lng,d),k=Ne.fromLngLat(p),M=Ne.fromLngLat(y),F=w.x-b.x,$=w.y-b.y,U=M.x-k.x,H=M.y-k.y,Z=Math.sqrt((U*U+H*H)/(F*F+$*$));return Math.log2(Z)}function r9(h,l,d){const p=Math.cos(d),y=Math.sin(d);return{x:h*p-l*y,y:h*y+l*p}}function n9(h,l,d){I(h),Q(h,h,Xn(l[2])),V(h,h,Xn(l[0])),K(h,h,Xn(l[1])),W(h,h,d),R(h,h,[1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,1])}function xA(h,l,d,p,y,b,w,k){const M=[d[0]-l[0],d[1]-l[1],0],F=[p[0]-l[0],p[1]-l[1],0];if(ge(M)<1e-12||ge(F)<1e-12)return kr(h);const $=Be([],M,F);Oe($,$),je(F,p,l),M[2]=(b-y)*k,F[2]=(w-y)*k;const U=M;return Be(U,M,F),Oe(U,U),Xo(h,$,U)}function vA(h,l,d=!1){const p=zg(l.zoom),y=function(b,w,k){const M=w.worldSize,F=[b[12],b[13],b[14]],$=ee(F[1]/M),U=G(F[0]/M),H=I([]),Z=q(1,$)*M,Y=q(1,0)*M*se($,w.zoom),ne=1/$4(M);let ce=Y*ne;if(k){const Ee=yA(w.projection,w.zoom,w.width,w.height,1024);ce=ne*w.projection.pixelSpaceConversion(w.center.lat,M,Ee)}const le=Dg($,U);Se(le,le,Ye([],Oe([],le),Z*ce*F[2]));const ye=function(Ee){const Ue=[Ee[0],Ee[1],Ee[2]];let Le=[0,1,0];const Ke=Be([],Le,Ue);return Be(Le,Ue,Ke),gt(Le)===0&&(Le=[0,1,0],Be(Ke,Ue,Le)),Oe(Ke,Ke),Oe(Le,Le),Oe(Ue,Ue),[Ke[0],Ke[1],Ke[2],0,Le[0],Le[1],Le[2],0,Ue[0],Ue[1],Ue[2],0,Ee[0],Ee[1],Ee[2],1]}(le);W(H,H,[ce,ce,ce*Z]),z(H,H,[-F[0],-F[1],-F[2]]);const we=R([],w.globeMatrix,ye);return R(we,we,H),R(we,we,b),we}(h,l,d);if(p>0){const b=function(w,k){const M=k.worldSize,F=q(1,0)*M*se(k.center.lat,k.zoom)/$4(M),$=q(1,k.center.lat)*M,U=I([]);K(U,U,Xn(k.center.lng)),V(U,U,Xn(k.center.lat)),z(U,U,[0,0,rl]),W(U,U,[F,F,F*$]);const H=k.point;return z(U,U,[-H.x,-H.y,0]),R(U,U,w),R(U,k.globeMatrix,U)}(h,l);return function(w,k,M){const F=(Y,ne,ce)=>{const le=ge(Y),ye=ge(ne),we=Bh(Y,ne,ce);return Ye(we,we,1/ge(we)*fn(le,ye,ce))},$=F([w[0],w[1],w[2]],[k[0],k[1],k[2]],M),U=F([w[4],w[5],w[6]],[k[4],k[5],k[6]],M),H=F([w[8],w[9],w[10]],[k[8],k[9],k[10]],M),Z=Bh([w[12],w[13],w[14]],[k[12],k[13],k[14]],M);return[$[0],$[1],$[2],0,U[0],U[1],U[2],0,H[0],H[1],H[2],0,Z[0],Z[1],Z[2],1]}(y,b,p)}return y}function f3(h,l,d,p){const y=qr.projectAabbCorners(p,d);let b=Number.MAX_VALUE;for(let k=0;k0||ce===0&&Y[0]*ne[0]+Y[1]*ne[1]>=0&&Y[0]*Y[0]+Y[1]*Y[1]>ne[0]*ne[0]+ne[1]*ne[1])&&($=Z)}U=$}while(U!==F);return M.length>0&&M.push(M[0]),M}(y);if(ws(h,w))return b}const _v=64,Fb={CoordinateSpaceTile:1,HasMapboxMeshFeatures:4,HasMeshoptCompression:8};function _A(h,l,d,p,y,b,w,k,M,F=!1){const $=d.zoom,U=d.project(p),H=se(p.lat,$),Z=1/H;I(h),z(h,h,[U.x+w[0]*Z,U.y+w[1]*Z,w[2]]);let Y=1,ne=1;const ce=d.worldSize;if(F){if(d.projection.name==="mercator"){let Ee=0;d.elevation&&(Ee=d.elevation.getAtPointOrZero(new Ne(U.x/ce,U.y/ce),0));const Ue=rr([],[U.x,U.y,Ee,1],d.projMatrix)[3]/d.cameraToCenterDistance;Y=Ue,ne=Ue*se(d.center.lat,$)}else if(d.projection.name==="globe"){const Ee=vA(h,d),Ue=[0,0,0,1];rr(Ue,Ue,R([],d.projMatrix,Ee));const Le=Ue[3]/d.cameraToCenterDistance,Ke=zg($),Je=d.projection.pixelsPerMeter(p.lat,ce)*se(p.lat,$),it=d.projection.pixelsPerMeter(d.center.lat,ce)*se(d.center.lat,$);Y=Le/fn(Je,oe(d.center.lat),Ke),ne=Le*H/Je,Y*=it,ne*=it}}else Y=Z;W(h,h,[Y,Y,ne]);const le=[...h],ye=l.orientation,we=[];if(n9(we,[ye[0]+(y?y[0]:0),ye[1]+(y?y[1]:0),ye[2]+(y?y[2]:0)],b),R(h,le,we),k&&d.elevation){let Ee=0;const Ue=[];if(M&&d.elevation){Ee=function(Ke,Je,it,Pt,ft){const Ft=Je.elevation;if(!Ft)return 0;const Vt=qr.projectAabbCorners(it,Pt),qt=q(1,ft.lat)*Je.worldSize,er=function(Or,Br){const $n=[0,0,1],dr=[{corners:[0,1,3,2],dotProductWithUp:0},{corners:[1,5,2,6],dotProductWithUp:0},{corners:[0,4,1,5],dotProductWithUp:0},{corners:[2,6,3,7],dotProductWithUp:0},{corners:[4,7,5,6],dotProductWithUp:0},{corners:[0,3,4,7],dotProductWithUp:0}];for(const $r of dr){const wn=Or[$r.corners[0]],ls=Or[$r.corners[1]],hs=Or[$r.corners[2]],Tn=[ls[0]-wn[0],ls[1]-wn[1],Br*(ls[2]-wn[2])],Js=Be(Tn,Tn,[hs[0]-wn[0],hs[1]-wn[1],Br*(hs[2]-wn[2])]);Oe(Js,Js),$r.dotProductWithUp=Ie(Js,$n)}return dr.sort(($r,wn)=>$r.dotProductWithUp-wn.dotProductWithUp),dr[0].corners}(Vt,qt),nr=Vt[er[0]],Yt=Vt[er[1]],Xt=Vt[er[2]],Rt=Vt[er[3]],It=Ft.getAtPointOrZero(new Ne(nr[0]/Je.worldSize,nr[1]/Je.worldSize),0),Jt=Ft.getAtPointOrZero(new Ne(Yt[0]/Je.worldSize,Yt[1]/Je.worldSize),0),gr=Ft.getAtPointOrZero(new Ne(Xt[0]/Je.worldSize,Xt[1]/Je.worldSize),0),cr=Ft.getAtPointOrZero(new Ne(Rt[0]/Je.worldSize,Rt[1]/Je.worldSize),0),Gr=(It+cr)/2,Er=(Jt+gr)/2;return Gr>Er?Jt=l.gl.NEAREST_MIPMAP_NEAREST}),h.uploaded=!0,h.image=null)}function xwe(h,l,d){h.indexBuffer=l.createIndexBuffer(h.indexArray,!1,!0),h.vertexBuffer=l.createVertexBuffer(h.vertexArray,dwe.members,!1,!0),h.normalArray&&(h.normalBuffer=l.createVertexBuffer(h.normalArray,mwe.members,!1,!0)),h.texcoordArray&&(h.texcoordBuffer=l.createVertexBuffer(h.texcoordArray,pwe.members,!1,!0)),h.colorArray&&(h.colorBuffer=l.createVertexBuffer(h.colorArray,(h.colorArray.bytesPerElement===12?hwe:fwe).members,!1,!0)),h.featureArray&&(h.pbrBuffer=l.createVertexBuffer(h.featureArray,ywe.members,!0)),h.segments=Hi.simpleSegment(0,0,h.vertexArray.length,h.indexArray.length);const p=h.material;p.pbrMetallicRoughness.baseColorTexture&&AN(p.pbrMetallicRoughness.baseColorTexture,l),p.pbrMetallicRoughness.metallicRoughnessTexture&&AN(p.pbrMetallicRoughness.metallicRoughnessTexture,l),p.normalTexture&&AN(p.normalTexture,l),p.occlusionTexture&&AN(p.occlusionTexture,l,d),p.emissionTexture&&AN(p.emissionTexture,l)}function p3(h,l,d){if(h.meshes)for(const p of h.meshes)xwe(p,l,d);if(h.children)for(const p of h.children)p3(p,l,d)}function bA(h){if(h.meshes)for(const l of h.meshes)l.indexArray.destroy(),l.vertexArray.destroy(),l.colorArray&&l.colorArray.destroy(),l.normalArray&&l.normalArray.destroy(),l.texcoordArray&&l.texcoordArray.destroy(),l.featureArray&&l.featureArray.destroy();if(h.children)for(const l of h.children)bA(l)}function m3(h){if(h.meshes)for(const d of h.meshes)d.vertexBuffer&&(d.vertexBuffer.destroy(),d.indexBuffer.destroy(),d.normalBuffer&&d.normalBuffer.destroy(),d.texcoordBuffer&&d.texcoordBuffer.destroy(),d.colorBuffer&&d.colorBuffer.destroy(),d.pbrBuffer&&d.pbrBuffer.destroy(),d.segments.destroy(),d.material&&((l=d.material).pbrMetallicRoughness.baseColorTexture&&l.pbrMetallicRoughness.baseColorTexture.gfxTexture&&l.pbrMetallicRoughness.baseColorTexture.gfxTexture.destroy(),l.pbrMetallicRoughness.metallicRoughnessTexture&&l.pbrMetallicRoughness.metallicRoughnessTexture.gfxTexture&&l.pbrMetallicRoughness.metallicRoughnessTexture.gfxTexture.destroy(),l.normalTexture&&l.normalTexture.gfxTexture&&l.normalTexture.gfxTexture.destroy(),l.emissionTexture&&l.emissionTexture.gfxTexture&&l.emissionTexture.gfxTexture.destroy(),l.occlusionTexture&&l.occlusionTexture.gfxTexture&&l.occlusionTexture.gfxTexture.destroy()));var l;if(h.children)for(const d of h.children)m3(d)}function bv(h,l){const d=h.json.bufferViews[l.bufferView],p=mA[l.componentType];return new p(h.buffers[d.buffer],(l.byteOffset||0)+(d.byteOffset||0),l.count*(d.byteStride&&d.byteStride!==TN[l.type]*p.BYTES_PER_ELEMENT?d.byteStride/p.BYTES_PER_ELEMENT:TN[l.type]))}function g3(h,l,d,p){const y=mA[l.componentType],b=function($){switch($){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:return 1}}(y),w=h.json.bufferViews[l.bufferView],k=w.byteStride?w.byteStride/y.BYTES_PER_ELEMENT:TN[l.type],M=d.float32,F=M.length/d.capacity;for(let $=0,U=0;$0){for(let ce=0;ce0){b.texcoordArray=new zd;const H=l.json.accessors[y.TEXCOORD_0];b.texcoordArray.resize(H.count);const Z=bv(l,H);g3(l,H,b.texcoordArray,Z)}if(y._FEATURE_ID_RGBA4444!==void 0){const H=l.json.accessors[y._FEATURE_ID_RGBA4444];l.json.extensionsUsed&&l.json.extensionsUsed.includes("EXT_meshopt_compression")&&(b.featureData=bv(l,H))}y._FEATURE_RGBA4444!==void 0&&(b.featureData=new Uint32Array(bv(l,l.json.accessors[y._FEATURE_RGBA4444]).buffer));const U=h.material;return b.material=function(H,Z){const{emissiveFactor:Y=[0,0,0],alphaMode:ne="OPAQUE",alphaCutoff:ce=.5,normalTexture:le,occlusionTexture:ye,emissiveTexture:we,doubleSided:Ee,name:Ue}=H,{baseColorFactor:Le=[1,1,1,1],metallicFactor:Ke=1,roughnessFactor:Je=1,baseColorTexture:it,metallicRoughnessTexture:Pt}=H.pbrMetallicRoughness||{},ft=ye?Z[ye.index]:void 0;if(ye&&ye.extensions&&ye.extensions.KHR_texture_transform&&ft){const Ft=ye.extensions.KHR_texture_transform;ft.offsetScale=[Ft.offset[0],Ft.offset[1],Ft.scale[0],Ft.scale[1]]}return{name:Ue,pbrMetallicRoughness:{baseColorFactor:new Us(...Le),metallicFactor:Ke,roughnessFactor:Je,baseColorTexture:it?Z[it.index]:void 0,metallicRoughnessTexture:Pt?Z[Pt.index]:void 0},doubleSided:Ee,emissiveFactor:new Us(...Y),alphaMode:ne,alphaCutoff:ce,normalTexture:le?Z[le.index]:void 0,occlusionTexture:ft,emissionTexture:we?Z[we.index]:void 0,defined:H.defined===void 0}}(U!==void 0?l.json.materials[U]:{defined:!1},d),b}function i9(h,l,d){const{matrix:p,rotation:y,translation:b,scale:w,mesh:k,extras:M,children:F,name:$}=h,U={};if(U.name=$,U.localMatrix=p||function(H,Z,Y,ne){var ce=Z[0],le=Z[1],ye=Z[2],we=Z[3],Ee=ce+ce,Ue=le+le,Le=ye+ye,Ke=ce*Ee,Je=ce*Ue,it=ce*Le,Pt=le*Ue,ft=le*Le,Ft=ye*Le,Vt=we*Ee,qt=we*Ue,er=we*Le,nr=ne[0],Yt=ne[1],Xt=ne[2];return H[0]=(1-(Pt+Ft))*nr,H[1]=(Je+er)*nr,H[2]=(it-qt)*nr,H[3]=0,H[4]=(Je-er)*Yt,H[5]=(1-(Ke+Ft))*Yt,H[6]=(ft+Vt)*Yt,H[7]=0,H[8]=(it+qt)*Xt,H[9]=(ft-Vt)*Xt,H[10]=(1-(Ke+Pt))*Xt,H[11]=0,H[12]=Y[0],H[13]=Y[1],H[14]=Y[2],H[15]=1,H}([],y||[0,0,0,1],b||[0,0,0],w||[1,1,1]),U.globalMatrix=A(U.localMatrix),k!==void 0){U.meshes=d[k];const H=U.anchor=[0,0];for(const Z of U.meshes){const{min:Y,max:ne}=Z.aabb;H[0]+=Y[0]+ne[0],H[1]+=Y[1]+ne[1]}H[0]=Math.floor(H[0]/U.meshes.length/2),H[1]=Math.floor(H[1]/U.meshes.length/2)}if(M&&(M.id&&(U.id=M.id),M.lights&&(U.lights=function(H){if(!H.length)return[];const Z=function(ye){const we=atob(ye),Ee=new Uint8Array(we.length);for(let Ue=0;Ue1&&p[p.length-1].equals(p[0])&&p.pop();let y=0;for(let w=0;w0&&p.reverse();const b=Ib(p.flatMap(w=>[w.x,w.y]),[]);return b.length===0?null:{vertices:p,indices:b}}function wwe(h,l){const d=[],p=[];let y=0;const b=[];for(const w of h){y=d.length;const k=w.vertexArray.float32,M=w.indexArray.uint16;for(let F=0;F0&&([p[w+1],p[w+2]]=[p[w+2],p[w+1]])}return{vertices:d,indices:p}}function y3(h){const l=function(M,F){const $=[],U=WebGL2RenderingContext;if(M.json.textures)for(const H of M.json.textures){const Z={magFilter:U.LINEAR,minFilter:U.NEAREST,wrapS:U.REPEAT,wrapT:U.REPEAT};H.sampler!==void 0&&Object.assign(Z,M.json.samplers[H.sampler]),$.push({image:F[H.source],sampler:Z,uploaded:!1})}return $}(h,h.images),d=function(M,F){const $=[];for(const U of M.json.meshes){const H=[];for(const Z of U.primitives)H.push(vwe(Z,M,F));$.push(H)}return $}(h,l),{scenes:p,scene:y,nodes:b}=h.json,w=p?p[y||0].nodes:[...b.keys()],k=[];for(const M of w)k.push(i9(b[M],h,d));return function(M,F,$){const U={},H=new Set;for(let Z=0;Z0){const Z=Array.from(H.values()).sort((Y,ne)=>Y-ne);for(let Y=Z.length-1;Y>=0;Y--)M.splice(Z[Y],1)}}(k,w,h.json.nodes),k}function jwe(h){h.heightmap=new Float32Array(4096),h.heightmap.fill(-1);const l=h.vertexArray.float32,d=h.aabb.min[0]-1,p=h.aabb.min[1]-1,y=_v/(h.aabb.max[0]-d+2),b=_v/(h.aabb.max[1]-p+2);for(let w=0;wh.heightmap[F*_v+M]&&(h.heightmap[F*_v+M]=k)}}function a9(h,l,d,p,y){d.reserve(d.length+4*h.length),p.reserve(p.length+10*h.length),y.reserve(y.length+10*h.length);let b=p.length;for(const w of h){const k=Math.min(10,Math.max(4,1.3*w.height))*l,M=[-w.normal[1],w.normal[0],0],F=Math.min(.29,.1*w.width/w.depth),$=w.width-2*w.depth*l*(F+.01),U=pt([],w.pos,M,$/2),H=pt([],w.pos,M,-$/2),Z=[U[0],U[1],U[2]+w.height],Y=[H[0],H[1],H[2]+w.height],ne=pt([],w.normal,M,F);Ye(ne,ne,k);const ce=pt([],w.normal,M,-F);Ye(ce,ce,k),Se(ne,U,ne),Se(ce,H,ce),U[2]+=.1,H[2]+=.1,p.emplaceBack(ne[0],ne[1],ne[2]),p.emplaceBack(ce[0],ce[1],ce[2]),p.emplaceBack(U[0],U[1],U[2]),p.emplaceBack(H[0],H[1],H[2]),p.emplaceBack(Z[0],Z[1],Z[2]),p.emplaceBack(Y[0],Y[1],Y[2]),p.emplaceBack(U[0],U[1],U[2]),p.emplaceBack(H[0],H[1],H[2]),p.emplaceBack(ne[0],ne[1],ne[2]),p.emplaceBack(ce[0],ce[1],ce[2]);const le=$/k/2;y.emplaceBack(-le-F,-1,le,.8),y.emplaceBack(le+F,-1,le,.8),y.emplaceBack(-le,0,le,1.3),y.emplaceBack(le,0,le,1.3),y.emplaceBack(le+F,-.8,le,.7),y.emplaceBack(le+F,-.8,le,.7),y.emplaceBack(0,0,le,1.3),y.emplaceBack(0,0,le,1.3),y.emplaceBack(le+F,-1.2,le,.8),y.emplaceBack(le+F,-1.2,le,.8),d.emplaceBack(6+b,4+b,8+b),d.emplaceBack(7+b,9+b,5+b),d.emplaceBack(0+b,1+b,2+b),d.emplaceBack(1+b,3+b,2+b),b+=10}}function Swe(h,l){const d={};d.indexArray=new Fa,d.vertexArray=new Vc,d.colorArray=new Gf,a9(h,l,d.indexArray,d.vertexArray,d.colorArray);const p={defined:!0};p.emissiveFactor=Us.black;const y={};return y.baseColorFactor=Us.white,p.pbrMetallicRoughness=y,d.material=p,d.aabb=new qr([1/0,1/0,1/0],[-1/0,-1/0,-1/0]),d}const o9=ts([{name:"a_pos_3f",components:3,type:"Float32"}]),Nwe=ts([{name:"a_normal_3",components:3,type:"Int16"}]),Cwe=ts([{name:"a_centroid_3",components:3,type:"Int16"}]),l9=ts([{name:"a_part_color_emissive",components:2,type:"Uint16"}]),kwe=ts([{name:"a_faux_facade_color_emissive",components:2,type:"Uint16"}]),Twe=ts([{name:"a_faux_facade_data",components:4,type:"Uint16"}]),Ewe=ts([{name:"a_faux_facade_vertical_range",components:2,type:"Uint16"}]),Awe=ts([{name:"a_bloom_attenuation",components:4,type:"Float32"}]),Pwe=ts([{name:"a_flood_light_wall_radius_1i16",components:1,type:"Uint16"}]),c9=ot.types,wA=32767;function Iwe(h,l){const d=mr+l;for(const p of h)for(const y of p)if(y.x<-l||y.x>d||y.y<-l||y.y>d)return!1;return!0}function Mwe(h){switch(h){case"flat":return 3;case"hipped":return 1;case"gabled":return 2;case"parapet":return 0;case"mansard":return 4;case"skillion":return 5;case"pyramidal":return 6;default:throw new Error(`Unknown roof shape: ${h}`)}}class x3{constructor(){this.layoutVertexArray=new Vc,this.layoutAttenuationArray=new Gf,this.layoutColorArray=new qc,this.indexArray=new Fa,this.indexArrayForConflation=new Fa,this.segmentsBucket=new Hi}}class v3{constructor(l){this.layoutFacadePaintArray=null,this.layoutFacadeDataArray=null,this.layoutFacadeVerticalRangeArray=null,this.segmentsBucket=new Hi,this.entranceBloom=new x3;const d=66560;this.layoutVertexArray=new Vc,this.layoutVertexArray.reserve(d),this.layoutNormalArray=new Ag,this.layoutNormalArray.reserve(d),this.layoutCentroidArray=new Ag,this.layoutCentroidArray.reserve(d),this.layoutColorArray=new qc,this.layoutColorArray.reserve(d),this.layoutFloodLightDataArray=new Kf,this.layoutFloodLightDataArray.reserve(d),this.layoutAOArray=new _b,this.layoutAOArray.reserve(d),this.indexArray=new Fa,this.indexArray.reserve(66560),this.indexArrayForConflation=new Fa,this.segmentsBucket=new Hi,this.entranceBloom=new x3,l&&(this.layoutFacadePaintArray=new qc,this.layoutFacadeDataArray=new nm,this.layoutFacadeVerticalRangeArray=new qc)}reserve(l,d,p){this.layoutVertexArray.reserveForAdditional(l),this.layoutCentroidArray.reserveForAdditional(l),this.layoutFloodLightDataArray.reserveForAdditional(l),this.layoutNormalArray.reserveForAdditional(l),this.layoutAOArray.reserveForAdditional(l),this.layoutColorArray.reserveForAdditional(l),this.indexArray.reserveForAdditional(d),p&&(this.layoutFacadePaintArray.reserveForAdditional(l),this.layoutFacadeDataArray.reserveForAdditional(l),this.layoutFacadeVerticalRangeArray.reserveForAdditional(l))}}class u9{constructor(l){this.colorBufferUploaded=!1,this.maxHeight=0,this.replacementUpdateTime=0,this.activeReplacements=[],this.footprints=[],this.footprintsVertices=new zd,this.footprintsIndices=new Kf,this.footprintsMin=new Wt(1/0,1/0),this.footprintsMax=new Wt(-1/0,-1/0),this.featuresOnBorder=[],this.buildingWithoutFacade=new v3(!1),this.buildingWithFacade=new v3(!0),this.indexArrayForConflationUploaded=!1,this.featureFootprintLookup=new Map,this.buildingIds=new Set,this.footprintLookup={},this.zoom=l.zoom,this.canonical=l.canonical,this.layers=l.layers,this.layerIds=this.layers.map(d=>d.fqid),this.index=l.index,this.hasPattern=!1,this.worldview=l.worldview,this.lut=l.lut,this.programConfigurations=new ed(l.layers,{zoom:l.zoom,lut:l.lut}),this.stateDependentLayerIds=this.layers.filter(d=>d.isStateDependent()).map(d=>d.id),this.projection=l.projection,this.groundEffect=new t3(l),this.groundEffect.groundRadiusArray=new Mh,this.hasAppearances=null}updateFootprints(l,d){const p=new oA([],[],1),y={vertices:[],indices:new Uint32Array(0),grid:p,min:this.footprintsMin,max:this.footprintsMax,buildingIds:this.buildingIds};d.push({footprint:y,id:l})}updateAppearances(l,d,p,y){}prepare(){return function(){if(pA!=null||qG!=null)return null;if(Lb!=null)return Lb;const l=fetch(is.BUILDING_GEN_URL);return Lb=function(d){let p,y,b,w,k;function M(){p=new Uint8Array(k.buffer),y=new Int16Array(k.buffer),b=new Int32Array(k.buffer),w=new Float32Array(k.buffer)}function F(){throw new Error("Unexpected BuildingGen error.")}const $=()=>{},U={a:{a:F,f:function(H){const Z=p.length,Y=Math.max(H>>>0,Math.ceil(1.2*Z)),ne=Math.ceil((Y-Z)/65536);try{return k.grow(ne),M(),!0}catch{return!1}},g:F,b:$,c:$,d:$,e:$}};return(WebAssembly.instantiateStreaming?WebAssembly.instantiateStreaming(d,U):d.then(H=>H.arrayBuffer()).then(H=>WebAssembly.instantiate(H,U))).then(H=>{const Z=H.instance.exports;return(0,Z.g)(),k=Z.f,M(),new swe({setStyle:Z.h,setAOOptions:Z.i,setMetricOptions:Z.j,setStructuralOptions:Z.k,setFacadeOptions:Z.l,setFauxFacadeOptions:Z.m,setFacadeClassifierOptions:Z.n,addFeature:Z.o,addFacade:Z.p,generateMesh:Z.q,getLastError:Z.r,getOuterRingLength:Z.s,getMeshCount:Z.t,getPositionsPtr:Z.u,getPositionsLength:Z.v,getNormalsPtr:Z.w,getNormalsLength:Z.x,getAOPtr:Z.y,getAOLength:Z.z,getUVPtr:Z.A,getUVLength:Z.B,getFauxFacadePtr:Z.C,getFauxFacadeLength:Z.D,getIndicesPtr:Z.E,getIndicesLength:Z.F,getBuildingPart:Z.G,getRingCount:Z.H,getRingPtr:Z.I,getRingLength:Z.J,malloc:Z.K,free:Z.L,heapU8:p,heap16:y,heap32:b,heapF32:w})})}(l).then(d=>(Lb=null,pA=d,pA)).catch(d=>{Ge("Could not load building-gen"),Lb=null,qG=d}),Lb}()}populate(l,d,p,y){const b=iwe();if(!b)return;const w=fe(p);this.tileToMeter=w,this.brightness=d.brightness,b.setStyle({normalScale:[1,-1,w],tileToMeters:w}),b.setAOOptions(!1,.3),b.setMetricOptions(!1,16),b.setStructuralOptions(!0),b.setFacadeClassifierOptions(3);const k=new Map,M=new Map;let F=0;for(const{feature:le}of l){if(c9[le.type]!=="LineString"){k.set(le.id,le.properties.source_id);continue}const ye=this.layers[0]._featureFilter.needGeometry;if(ye&&!this.layers[0]._featureFilter.filter(new wi(this.zoom),le,p))continue;const we=ht(le,ye);if(!ye&&!this.layers[0]._featureFilter.filter(new wi(this.zoom),we,p))continue;const Ee=ye?we.geometry:Qe(le,p,y),Ue=[];for(const it of Ee)for(const Pt of it)Ue.push(Pt.x),Ue.push(Pt.y);const Le={coordinates:Ue,crossPerc:le.properties.cross_perc,distanceToRoad:le.properties.distance_to_road,entrances:le.properties.entrances,sourceId:0},Ke=le.properties.source_id;let Je=M.get(Ke);Je||(Je=[],M.set(Ke,Je)),Je.push(Le),++F}this.maxHeight=0;const $=new Array,U=new Set,H=le=>{le!=null&&U.add(le)},Z=(le,ye)=>{le!=null&&$.push({buildingId:le,footprintIndex:ye})},Y=64*(l.length-F),ne=Y/2;this.buildingWithFacade.reserve(Y,ne,!0),this.buildingWithoutFacade.reserve(2*Y,2*ne,!1),this.footprintsIndices.reserve(16*(l.length-F)),this.footprintsVertices.reserve(8*(l.length-F));for(const{feature:le,id:ye,index:we,sourceLayerIndex:Ee}of l){if(c9[le.type]==="LineString")continue;const Ue=this.layers[0]._featureFilter.needGeometry;if(Ue&&!this.layers[0]._featureFilter.filter(new wi(this.zoom),le,p))continue;let Le=null;if(le.properties&&le.properties.hasOwnProperty("building_id")&&(Le=le.properties.building_id,U.has(Le)))continue;const Ke=ht(le,Ue);if(!Ue&&!this.layers[0]._featureFilter.filter(new wi(this.zoom),Ke,p))continue;const Je=Ue?Ke.geometry:Qe(le,p,y),it=vN(Je,500);let Pt=!1;for(const ln of it)if(ln.length!==1){Pt=!0;break}if(Pt){H(Le);continue}if(!Iwe(Je,163)){H(Le);continue}const ft=this.layers[0],Ft=Mwe(ft.layout.get("building-roof-shape").evaluate(le,{},p)),Vt=ft.layout.get("building-base").evaluate(le,{},p),qt=ft.layout.get("building-height").evaluate(le,{},p),er=ft.layout.get("building-flood-light-ground-radius").evaluate(le,{},p),nr=ft.paint.get("building-ambient-occlusion-intensity"),Yt=er/this.tileToMeter;le.properties["building-part"]="roof";const Xt=ft.paint.get("building-color").evaluate(le,{},this.canonical).toPremultipliedRenderColor(this.lut),Rt=ft.paint.get("building-emissive-strength").evaluate(le,{},this.canonical);le.properties["building-part"]="wall";const It=ft.paint.get("building-color").evaluate(le,{},this.canonical).toPremultipliedRenderColor(this.lut),Jt=ft.paint.get("building-emissive-strength").evaluate(le,{},this.canonical);le.properties["building-part"]="window";const gr=ft.paint.get("building-color").evaluate(le,{},this.canonical).toPremultipliedRenderColor(this.lut),cr=ft.paint.get("building-emissive-strength").evaluate(le,{},this.canonical);le.properties["building-part"]="door";const Gr=ft.paint.get("building-color").evaluate(le,{},this.canonical).toPremultipliedRenderColor(this.lut),Er=ft.paint.get("building-emissive-strength").evaluate(le,{},this.canonical);let Or=ft.layout.get("building-flood-light-wall-radius").evaluate(le,{},p);Or=ue(Or,0,2048);const Br=Or/2048*wA,$n=k.get(ye),dr=M.get($n)||[],$r=dr.length!==0&&ft.layout.get("building-facade").evaluate(le,{},p);b.setFacadeOptions(4,!0),b.setFauxFacadeOptions($r,!1,1);let wn=0,ls=0,hs=0,Tn=0,Js=0,Fe=0,qe=0,zt=0,tr=0,Nr=0,Cr=0;if($r){let ln=Math.round(ft.layout.get("building-facade-floors").evaluate(le,{},p));if(Vt===0){ln=Math.max(1,ln-(dr.length>0?1:0));let Hs=4;if(qt>100){const Fi=[10,13,15];Hs=Fi[le.id?le.id%Fi.length:0]}else qt<=10&&(Hs=3);b.setFacadeOptions(Hs,!0),Js=(qt<15?1.3:1.61803)*Hs/w}else Js=Vt/w;Fe=qt/w,Js=Math.min(Js,Fe),hs=ft.layout.get("building-facade-unit-width").evaluate(le,{},p)/w,Tn=(Fe-Js)/ln,b.setFauxFacadeOptions(!0,!0,hs);const Ki=ft.layout.get("building-facade-window").evaluate(le,{},p);wn=Ki[0],ls=Ki[1],qe=Math.floor(65535*Math.min(1,Js/mr)),zt=Math.floor(65535*Math.min(1,Fe/mr)),tr=Math.floor(255*wn)<<8|Math.floor(255*ls),Nr=Math.floor(65535*Math.min(1,hs/mr)),Cr=Math.floor(65535*Math.min(1,Tn/mr))}const Kr=Array(it.length),Xr={x:1/0,y:1/0},kn={x:-1/0,y:-1/0},In={x:0,y:0};let zn=0;for(let ln=0;ln0){const Hs=[],Fi=Array(Ki.length+1);Fi[0]=0;for(let $a=0;$amr||Xr.y<0||kn.y>mr)&&this.featuresOnBorder.push({featureId:le.id,footprintIndex:this.footprints.length});{const ln=Ib(ai,null,2);this.footprintsIndices.resize(this.footprintsIndices.length+ln.length),this.footprintsIndices.uint16.set(ln,on),this.buildingIds.add(Le??le.id),this.footprintsMin.x=Math.min(this.footprintsMin.x,yi.x),this.footprintsMin.y=Math.min(this.footprintsMin.y,yi.y),this.footprintsMax.x=Math.max(this.footprintsMax.x,ji.x),this.footprintsMax.y=Math.max(this.footprintsMax.y,ji.y);const Ki={footprintVertexOffset:ns,footprintVertexLength:this.footprintsVertices.length-ns,footprintIndexOffset:on,footprintIndexLength:this.footprintsIndices.length-on,min:yi,max:ji,hiddenFlags:0,indicesOffset:Fs,indicesLength:Vi,bloomIndicesOffset:qs,bloomIndicesLength:di,groundEffectVertexOffset:ga,groundEffectVertexLength:xi,hasFauxFacade:$r,height:Mn,promoteId:ye,feature:Ke,parts:ks,buildingBloom:Ts},Hs=this.footprints.length;le.id!==void 0&&this.featureFootprintLookup.set(le.id,Hs),Z(Le,Hs),this.footprints.push(Ki)}this.programConfigurations.populatePaintArrays(un.layoutVertexArray.length,le,we,{},d.availableImages,p,d.brightness),this.groundEffect.addPaintPropertiesData(le,we,{},d.availableImages,p,d.brightness),d.featureIndex.insert(le,Je,we,Ee,this.index,ei)}$.forEach(({buildingId:le,footprintIndex:ye})=>{U.has(le)&&(this.footprints[ye].hiddenFlags|=4)});const ce=new Set;this.buildingIds.forEach((le,ye,we)=>{U.has(le)||ce.add(le)}),this.buildingIds=ce,this.groundEffect.prepareBorderSegments()}update(l,d,p,y,b,w,k){this.programConfigurations.updatePaintArrays(l,d,b,p,y,w,k),this.groundEffect.update(l,d,b,p,y,w,k),this.evaluate(this.layers[0],l),this.colorBufferUploaded=!1}isEmpty(){return this.buildingWithoutFacade.layoutVertexArray.length===0&&this.buildingWithFacade.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload||this.groundEffect.programConfigurations.needsUpload}upload(l){const d=p=>{p.layoutVertexBuffer=l.createVertexBuffer(p.layoutVertexArray,o9.members),p.layoutNormalBuffer=l.createVertexBuffer(p.layoutNormalArray,Nwe.members),p.layoutCentroidBuffer=l.createVertexBuffer(p.layoutCentroidArray,Cwe.members),p.layoutFloodLightDataBuffer=l.createVertexBuffer(p.layoutFloodLightDataArray,Pwe.members),p.layoutFacadeDataArray&&p.layoutFacadeDataArray.length&&(p.layoutFacadeDataBuffer=l.createVertexBuffer(p.layoutFacadeDataArray,Twe.members)),p.layoutFacadeVerticalRangeArray&&p.layoutFacadeVerticalRangeArray.length&&(p.layoutFacadeVerticalRangeBuffer=l.createVertexBuffer(p.layoutFacadeVerticalRangeArray,Ewe.members)),p.entranceBloom.layoutVertexArray.length&&(p.entranceBloom.layoutVertexBuffer=l.createVertexBuffer(p.entranceBloom.layoutVertexArray,o9.members),p.entranceBloom.layoutAttenuationBuffer=l.createVertexBuffer(p.entranceBloom.layoutAttenuationArray,Awe.members)),this.uploadUpdatedColorBuffer(l),this.uploadUpdatedIndexBuffer(l)};this.uploaded||(d(this.buildingWithoutFacade),d(this.buildingWithFacade),this.groundEffect.upload(l)),this.groundEffect.uploadPaintProperties(l),this.programConfigurations.upload(l),this.uploaded=!0}destroy(){const l=d=>{d.layoutVertexBuffer&&(d.layoutVertexBuffer.destroy(),d.layoutNormalBuffer.destroy(),d.layoutColorBuffer.destroy(),d.segmentsBucket.destroy(),d.indexBuffer&&d.indexBuffer.destroy(),d.entranceBloom.layoutVertexBuffer&&(d.entranceBloom.layoutVertexBuffer.destroy(),d.entranceBloom.layoutColorBuffer.destroy(),d.entranceBloom.layoutAttenuationBuffer.destroy(),d.entranceBloom.indexBuffer.destroy(),d.entranceBloom.segmentsBucket.destroy()))};l(this.buildingWithoutFacade),l(this.buildingWithFacade),this.groundEffect.destroy(),this.programConfigurations.destroy()}updateFootprintHiddenFlags(l,d,p=!0){let y=!1;const b=p?d:0,w=0|(p?-1:~d);this.groundEffect.hiddenByLandmarkVertexArray.length===0&&this.groundEffect.hiddenByLandmarkVertexArray.resize(this.groundEffect.vertexArray.length);for(const k of l){const M=this.footprints[k],F=M.hiddenFlags&w|b;M.hiddenFlags!==F&&(M.hiddenFlags=F,y=!0,this.groundEffect.updateHiddenByLandmarkRange(M.groundEffectVertexOffset,M.groundEffectVertexLength,M.hiddenFlags!==0))}return y&&(this.indexArrayForConflationUploaded=!1),y}uploadUpdatedIndexBuffer(l){if(this.groundEffect.uploadHiddenByLandmark(l),this.indexArrayForConflationUploaded)return;const d=y=>{y.indexArray.length!==0&&(y.indexArrayForConflation.resize(y.indexArray.length),y.indexArrayForConflation.uint16.set(y.indexArray.uint16),y.entranceBloom.indexArrayForConflation.resize(y.entranceBloom.indexArray.length),y.entranceBloom.indexArrayForConflation.uint16.set(y.entranceBloom.indexArray.uint16))};d(this.buildingWithoutFacade),d(this.buildingWithFacade);for(const y of this.footprints){const b=y.hasFauxFacade?this.buildingWithFacade:this.buildingWithoutFacade,w=y.indicesOffset+y.indicesLength;if(y.hiddenFlags!==0){for(let M=y.indicesOffset;M{y.indexArray.length!==0&&(y.indexBuffer?y.indexBuffer.updateData(y.indexArrayForConflation):y.indexBuffer=l.createIndexBuffer(y.indexArrayForConflation,!0),y.entranceBloom.indexBuffer?y.entranceBloom.indexBuffer.updateData(y.entranceBloom.indexArrayForConflation):y.entranceBloom.indexBuffer=l.createIndexBuffer(y.entranceBloom.indexArrayForConflation,!0))};p(this.buildingWithoutFacade),p(this.buildingWithFacade),this.indexArrayForConflationUploaded=!0}uploadUpdatedColorBuffer(l){const d=p=>{p.layoutColorBuffer?p.layoutColorBuffer.updateData(p.layoutColorArray):p.layoutColorBuffer=l.createVertexBuffer(p.layoutColorArray,l9.members,!0),p.layoutFacadePaintArray&&(p.layoutFacadePaintBuffer?p.layoutFacadePaintBuffer.updateData(p.layoutFacadePaintArray):p.layoutFacadePaintBuffer=l.createVertexBuffer(p.layoutFacadePaintArray,kwe.members,!0)),p.entranceBloom.layoutColorBuffer?p.entranceBloom.layoutColorBuffer.updateData(p.entranceBloom.layoutColorArray):p.entranceBloom.layoutColorBuffer=l.createVertexBuffer(p.entranceBloom.layoutColorArray,l9.members,!0)};d(this.buildingWithoutFacade),d(this.buildingWithFacade),this.colorBufferUploaded=!0}evaluate(l,d){const p=l.paint.get("building-ambient-occlusion-intensity");for(const y of this.footprints){if(4&y.hiddenFlags)continue;const b=d[y.promoteId],w=y.feature;w.properties["building-part"]="roof";const k=l.paint.get("building-color").evaluate(w,b,this.canonical).toPremultipliedRenderColor(this.lut),M=l.paint.get("building-emissive-strength").evaluate(w,b,this.canonical);w.properties["building-part"]="wall";const F=l.paint.get("building-color").evaluate(w,b,this.canonical).toPremultipliedRenderColor(this.lut),$=l.paint.get("building-emissive-strength").evaluate(w,b,this.canonical);w.properties["building-part"]="window";const U=l.paint.get("building-color").evaluate(w,b,this.canonical).toPremultipliedRenderColor(this.lut),H=l.paint.get("building-emissive-strength").evaluate(w,b,this.canonical);w.properties["building-part"]="door";const Z=l.paint.get("building-color").evaluate(w,b,this.canonical).toPremultipliedRenderColor(this.lut),Y=l.paint.get("building-emissive-strength").evaluate(w,b,this.canonical),ne=y.hasFauxFacade?this.buildingWithFacade:this.buildingWithoutFacade;for(const le of y.parts){let ye,we=k;le.part===1?(we=k,ye=M):le.part===0?(we=F,ye=$):le.part===2?(we=U,ye=H):le.part===3&&(we=Z,ye=Y),ye=ue(ye,0,1);for(let Ee=0;Eew.max.x||M.max.xw.max.y||M.max.yk.max.x||k.min.x>l||d>k.max.y||k.min.y>d||k.height<=p||Owe(w,this.footprintsVertices.float32.subarray(2*k.footprintVertexOffset,2*(k.footprintVertexOffset+k.footprintVertexLength)),this.footprintsIndices.uint16.subarray(k.footprintIndexOffset,k.footprintIndexOffset+k.footprintIndexLength))&&(p=k.height,this.footprintLookup[b]=k,y=k.hiddenFlags!==0);if(p!==Number.NEGATIVE_INFINITY)return{height:p,hidden:y};this.footprintLookup[b]=void 0}}function Owe(h,l,d){for(let p=0;p1&&(M=l[++k]);const $=Math.abs(F-M.left),U=Math.abs(F-M.right),H=Math.min($,U);let Z;const Y=b/p*(y+1);if(M.isDash){const ne=y-Math.abs(Y);Z=Math.sqrt(H*H+ne*ne)}else Z=y-Math.sqrt(H*H+Y*Y);this.image.data[w+F]=Math.max(0,Math.min(255,Z+128))}}}addRegularDash(l,d){for(let M=l.length-1;M>=0;--M){const F=l[M],$=l[M+1];F.zeroLength?l.splice(M,1):$&&$.isDash===F.isDash&&($.left=F.left,l.splice(M,1))}const p=l[0],y=l[l.length-1];p.isDash===y.isDash&&(p.left=y.left-this.width,y.right=p.right+this.width);const b=this.width*this.nextRow;let w=0,k=l[w];for(let M=0;M1&&(k=l[++w]);const F=Math.abs(M-k.left),$=Math.abs(M-k.right),U=Math.min(F,$);this.image.data[b+M]=Math.max(0,Math.min(255,(k.isDash?U:-U)+d+128))}}addDash(l,d){const p=this.getKey(l,d);if(this.positions[p])return this.positions[p];const y=d==="round",b=y?7:0,w=2*b+1;if(this.nextRow+w>this.height)return Ge("LineAtlas out of space"),null;l.length===0&&l.push(1);let k=0;for(let $=0;$d.fqid),this.index=l.index,this.projection=l.projection,this.hasPattern=!1,this.hasCrossSlope=!1,this.patternFeatures=[],this.lineClipsArray=[],this.gradients={},this.layers.forEach(d=>{this.gradients[d.id]={}}),this.layoutVertexArray=new fb,this.layoutVertexArray2=new Vc,this.patternVertexArray=new Vc,this.indexArray=new Fa,this.programConfigurations=new ed(l.layers,{zoom:l.zoom,lut:l.lut}),this.segments=new Hi,this.maxLineLength=0,this.zOffsetVertexArray=new Vc,this.stateDependentLayerIds=this.layers.filter(d=>d.isStateDependent()).map(d=>d.id),this.tessellationStep=l.tessellationStep?l.tessellationStep:mr/64,this.worldview=l.worldview,this.hasAppearances=null}updateFootprints(l,d){}updateAppearances(l,d,p,y){}populate(l,d,p,y){this.hasPattern=W4("line",this.layers,this.pixelRatio,d);const b=this.layers[0].layout.get("line-sort-key");this.tileToMeter=fe(p);const w=this.layers[0].layout.get("line-elevation-reference");if(w==="hd-road-markup")this.elevationType="road";else{const H=this.layers[0].layout.get("line-z-offset"),Z=H.isConstant()&&!H.constantOr(0);this.elevationType=w!=="sea"&&w!=="ground"&&Z?"none":"offset",this.elevationType==="offset"&&w==="none"&&Ge(`line-elevation-reference: ground is used for the layer ${this.layerIds[0]} because non-zero line-z-offset value was found.`)}const k=this.layers[0].layout.get("line-cross-slope");this.hasCrossSlope=this.elevationType==="offset"&&k!==void 0;const M=[];for(const{feature:H,id:Z,index:Y,sourceLayerIndex:ne}of l){const ce=this.layers[0]._featureFilter.needGeometry,le=ht(H,ce);if(!this.layers[0]._featureFilter.filter(new wi(this.zoom,{worldview:this.worldview,activeFloors:d.activeFloors}),le,p))continue;const ye=b?b.evaluate(le,{},p):void 0,we={id:Z,properties:H.properties,type:H.type,sourceLayerIndex:ne,index:Y,geometry:ce?le.geometry:Qe(H,p,y),patterns:{},sortKey:ye};M.push(we)}b&&M.sort((H,Z)=>H.sortKey-Z.sortKey);const{lineAtlas:F,featureIndex:$}=d,U=this.addConstantDashes(F);for(const H of M){const{geometry:Z,index:Y,sourceLayerIndex:ne}=H;if(U&&this.addFeatureDashes(H,F),this.hasPattern){const ce=G4("line",this.layers,H,this.zoom,this.pixelRatio,d);this.patternFeatures.push(ce)}else this.addFeature(H,Z,Y,p,F.positions,d.availableImages,d.brightness,d.elevationFeatures);$.insert(l[Y].feature,Z,Y,ne,this.index)}}addConstantDashes(l){let d=!1;for(const p of this.layers){const y=p.paint.get("line-dasharray").value,b=p.layout.get("line-cap").value;if(y.kind!=="constant"||b.kind!=="constant")d=!0;else{const w=b.value,k=y.value;if(!k)continue;l.addDash(k,w)}}return d}addFeatureDashes(l,d){const p=this.zoom;for(const y of this.layers){const b=y.paint.get("line-dasharray").value,w=y.layout.get("line-cap").value;if(b.kind==="constant"&&w.kind==="constant")continue;let k,M;if(b.kind==="constant"){if(k=b.value,!k)continue}else k=b.evaluate({zoom:p},l);M=w.kind==="constant"?w.value:w.evaluate({zoom:p},l),d.addDash(k,M),l.patterns[y.id]=[d.getKey(k,M)]}}update(l,d,p,y,b,w,k,M){this.programConfigurations.updatePaintArrays(l,d,b,p,y,w,k,M)}addFeatures(l,d,p,y,b,w){for(const k of this.patternFeatures)this.addFeature(k,k.geometry,k.index,d,p,y,w,l.elevationFeatures)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(l){this.uploaded||(this.layoutVertexArray2.length!==0&&(this.layoutVertexBuffer2=l.createVertexBuffer(this.layoutVertexArray2,Bwe)),this.patternVertexArray.length!==0&&(this.patternVertexBuffer=l.createVertexBuffer(this.patternVertexArray,Uwe)),!this.zOffsetVertexBuffer&&this.zOffsetVertexArray.length>0&&(this.zOffsetVertexBuffer=l.createVertexBuffer(this.zOffsetVertexArray,Lwe.members,!0)),this.layoutVertexBuffer=l.createVertexBuffer(this.layoutVertexArray,Fwe),this.indexBuffer=l.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(l),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.zOffsetVertexBuffer&&this.zOffsetVertexBuffer.destroy(),this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy())}lineFeatureClips(l,d){let p,y;if(d&&d>0?(p=`mapbox_clip_start_${d}`,y=`mapbox_clip_end_${d}`):(p="mapbox_clip_start",y="mapbox_clip_end"),l.properties&&l.properties.hasOwnProperty(p)&&l.properties.hasOwnProperty(y))return{start:+l.properties[p],end:+l.properties[y]}}addFeature(l,d,p,y,b,w,k,M){const F=this.layers[0].layout,$=F.get("line-join").evaluate(l,{}),U=F.get("line-cap").evaluate(l,{}),H=F.get("line-miter-limit"),Z=F.get("line-round-limit");this.lineClips=this.lineFeatureClips(l),this.lineFeature=l;const Y=!(!l.properties||!l.properties.hasOwnProperty("mapbox_line_metrics"))&&l.properties.mapbox_line_metrics;this.zOffsetValue=F.get("line-z-offset").value;const ne=this.layers[0].paint.get("line-width").value;if(ne.kind!=="constant"&&ne.isLineProgressConstant===!1&&(this.variableWidthValue=ne),this.elevationType==="road"){const ce=this.layoutVertexArray.length;if(!this.addElevatedRoadFeature(l,d,y,M,$,U,H,Z)){const[le,ye]=this.clipRuntimeLinesToTile(d,1);for(let we=0;we0?Ue.parentIndex:null)}this.fillNonElevatedRoadSegment(ce)}}else for(let ce=0;ce0?ce:null);this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,l,p,b,w,y,k,void 0,this.worldview)}computeSegNextDir(l,d){return l.nextPoint.sub(d.at(-2)).unit()}computeSegPrevDir(l,d){return d[1].sub(l.prevPoint).unit()}clipLinesToTile(l,d){return hA(l,-d,-d,mr+d,mr+d)}clipRuntimeLinesToTile(l,d){const p=[];return[hA(l,-d,-d,mr+d,mr+d,p),p]}addElevatedRoadFeature(l,d,p,y,b,w,k,M){const F=[],$=Ds.getElevationFeature(l,y);if($){const U=this.clipLinesToTile(d,1),H=this.prepareElevatedLines(U,$,p);for(const Z of H)F.push({geometry:Z,elevation:$,elevationTileID:p,segment:{progress:{min:0,max:1},nextDir:void 0,prevDir:void 0}})}if(F.length===0)return!1;for(const U of F){const H=this.layoutVertexArray.length;this.addLine(U.geometry,l,p,b,w,k,M);const Z=new Ys(p,U.elevationTileID);if(U.elevation)for(let Y=H;Y>1,this.layoutVertexArray.int16[6*Y+1]>>1),ce=Z.pointElevation(ne,U.elevation,.05);this.updateHeightRange(ce),this.zOffsetVertexArray.emplaceBack(ce,0,0)}else this.fillNonElevatedRoadSegment(H)}return!0}prepareElevatedLines(l,d,p){if(d.constantHeight!=null)return l;const y=[],b=1/fe(p);for(const w of l)twe(w,new Cs(d,b),0,y);return y}fillNonElevatedRoadSegment(l){for(let d=l;d0,H=M&&M.progress.max<1;if(this.lineClips){let it={min:this.lineClips.start,max:this.lineClips.end},Pt=1;if(M){const Vt=this.lineClips.end-this.lineClips.start;it=function(qt,er,nr){return{min:gi(qt.min,er,nr),max:gi(qt.max,er,nr)}}(M.progress,{min:0,max:1},it),Vt>0&&(Pt=(it.max-it.min)/Vt)}const ft=+d.properties.mapbox_clip_feature_len,Ft=+d.properties.mapbox_clip_seg_len;if(Number.isNaN(ft)||Number.isNaN(Ft)){for(let qt=0;qt=2&&l[Y-1].equals(l[Y-2]);)Y--;let ne=0;for(;ne0,Rt=this.overscaling<=16?15*mr/(512*this.overscaling):0;if(Pt&&ft==="round"){if(erw&&(ft="bevel"),ft==="bevel"&&(er>2&&(ft="flipbevel"),er2*Rt){const gr=le.sub(le.sub(ye)._mult(Rt/It)._round());this.updateDistance(ye,gr),this.addCurrentVertex(gr,Ee,0,0,ce,Je),ye=gr}this.updateDistance(ye,le),Vt._mult(er),this.addCurrentVertex(le,Vt,0,0,ce,Je);const Jt=le.dist(we);if(Jt>2*Rt){const gr=le.add(we.sub(le)._mult(Rt/Jt)._round());this.updateDistance(le,gr),this.addCurrentVertex(gr,Ue,0,0,ce,Je),le=gr}}else Vt._mult(er),this.addCurrentVertex(le,Vt,0,0,ce,Je);else if(ft==="flipbevel"){if(er>100)Vt=Ue.mult(-1);else{const It=er*Ee.add(Ue).mag()/Ee.sub(Ue).mag();Vt._perp()._mult(It*(Xt?-1:1))}this.addCurrentVertex(le,Vt,0,0,ce,Je),this.addCurrentVertex(le,Vt.mult(-1),0,0,ce,Je)}else if(ft==="bevel"||ft==="fakeround"){Je!=null&&ye&&this.addCurrentVertex(le,Ke||Ee,-1,-1,ce,Je);const It=le.dist(ye)<=2*Rt&&ft!=="bevel",Jt=Vt.mult(Xt?1:-1);Jt._mult(er);const gr=Ue.mult(Xt?-1:1),cr=Ee.mult(Xt?-1:1),Gr=this.evaluateLineProgressFeatures(this.distance);if(Je==null&&(this.addHalfVertex(le,Jt.x,Jt.y,!1,!Xt,0,ce,Gr),It||this.addHalfVertex(le,Jt.x+2*cr.x,Jt.y+2*cr.y,!1,Xt,0,ce,Gr)),ft==="fakeround"){const Er=Math.round(180*nr/Math.PI/20);this.addHalfVertex(le,cr.x,cr.y,!1,Xt,0,ce,Gr);for(let Or=0;Or1){this.lineSoFar=l.w;const ne=(d.x-l.x)/U,ce=(d.y-l.y)/U,le=(d.z-l.z)/U,ye=(d.w-l.w)/U;for(let we=1;we=0&&this.e2>=0&&(this.indexArray.emplaceBack(this.e1,this.e2,$),M.primitiveLength++),w?this.e2=$:this.e1=$,F!=null&&this.zOffsetVertexArray.emplaceBack(F.zOffset,F.variableWidth,F.variableWidth)}updateScaledDistance(){this.lineClips?(this.scaledDistance=this.distance/this.totalDistance,this.lineSoFar=this.totalFeatureLength*this.lineClips.start+this.distance):this.lineSoFar=this.distance}updateDistance(l,d){this.prevDistance=this.distance,this.distance+=l.dist(d),this.updateScaledDistance()}}function b3(h,l,d){return h.xd||h.yd}let p9,m9;function g9(h,l,d){return l*(mr/(h.tileSize*Math.pow(2,d-h.tileID.overscaledZ)))}Lr(_3,"LineBucket",{omit:["layers","patternFeatures","currentVertex","currentVertexIsOutside"]});const y9=(h,l,d)=>(1-d)*h+d*l;function x9(h,l){return 1/g9(h,1,l.tileZoom)}function v9(h,l,d,p){return h.translatePosMatrix(p||l.tileID.projMatrix,l,d.paint.get("line-translate"),d.paint.get("line-translate-anchor"))}const _9=h=>{const l=[];b9(h)&&l.push("RENDER_LINE_DASH"),h.paint.get("line-gradient")&&l.push("RENDER_LINE_GRADIENT");const d=h.paint.get("line-trim-offset");d[0]===0&&d[1]===0||l.push("RENDER_LINE_TRIM_OFFSET"),h.paint.get("line-border-width").constantOr(1)!==0&&l.push("RENDER_LINE_BORDER");const p=h.layout.get("line-join").constantOr("miter")==="none",y=!!h.paint.get("line-pattern").constantOr(1);return p&&y&&l.push("LINE_JOIN_NONE"),l};function b9(h){const l=h.paint.get("line-dasharray").value;return l.kind!=="constant"||l.value}let w3;const w9=()=>w3||(w3={layout:p9||(p9=new ta({"line-cap":new br(yt.layout_line["line-cap"]),"line-join":new br(yt.layout_line["line-join"]),"line-miter-limit":new hr(yt.layout_line["line-miter-limit"]),"line-round-limit":new hr(yt.layout_line["line-round-limit"]),"line-sort-key":new br(yt.layout_line["line-sort-key"]),"line-z-offset":new br(yt.layout_line["line-z-offset"]),"line-elevation-reference":new hr(yt.layout_line["line-elevation-reference"]),"line-cross-slope":new hr(yt.layout_line["line-cross-slope"]),visibility:new hr(yt.layout_line.visibility),"line-width-unit":new hr(yt.layout_line["line-width-unit"])})),paint:m9||(m9=new ta({"line-opacity":new br(yt.paint_line["line-opacity"]),"line-color":new br(yt.paint_line["line-color"]),"line-translate":new hr(yt.paint_line["line-translate"]),"line-translate-anchor":new hr(yt.paint_line["line-translate-anchor"]),"line-width":new br(yt.paint_line["line-width"]),"line-gap-width":new br(yt.paint_line["line-gap-width"]),"line-offset":new br(yt.paint_line["line-offset"]),"line-blur":new br(yt.paint_line["line-blur"]),"line-dasharray":new br(yt.paint_line["line-dasharray"]),"line-pattern":new br(yt.paint_line["line-pattern"]),"line-pattern-cross-fade":new hr(yt.paint_line["line-pattern-cross-fade"]),"line-gradient":new em(yt.paint_line["line-gradient"]),"line-trim-offset":new hr(yt.paint_line["line-trim-offset"]),"line-trim-fade-range":new hr(yt.paint_line["line-trim-fade-range"]),"line-trim-color":new hr(yt.paint_line["line-trim-color"]),"line-emissive-strength":new br(yt.paint_line["line-emissive-strength"]),"line-border-width":new br(yt.paint_line["line-border-width"]),"line-border-color":new br(yt.paint_line["line-border-color"]),"line-occlusion-opacity":new hr(yt.paint_line["line-occlusion-opacity"]),"line-color-use-theme":new br({type:"string",default:"default","property-type":"data-driven"}),"line-gradient-use-theme":new br({type:"string",default:"default","property-type":"data-driven"}),"line-trim-color-use-theme":new br({type:"string",default:"default","property-type":"data-driven"}),"line-border-color-use-theme":new br({type:"string",default:"default","property-type":"data-driven"})}))},w3);class Wwe extends br{possiblyEvaluate(l,d){return d=new wi(Math.floor(d.zoom),{now:d.now,fadeDuration:d.fadeDuration,transition:d.transition,worldview:d.worldview}),super.possiblyEvaluate(l,d)}evaluate(l,d,p,y){return d=Object.assign({},d,{zoom:Math.floor(d.zoom)}),super.evaluate(l,d,p,y)}}let PN;function j9(h,l){return l>0?l+2*h:h}const Gwe=ts([{name:"a_pos_offset",components:4,type:"Int16"},{name:"a_tex_size",components:4,type:"Uint16"},{name:"a_pixeloffset",components:4,type:"Int16"}],4),Kwe=ts([{name:"a_globe_anchor",components:3,type:"Int16"},{name:"a_globe_normal",components:3,type:"Float32"}],4),Zwe=ts([{name:"a_projected_pos",components:4,type:"Float32"}],4);ts([{name:"a_fade_opacity",components:1,type:"Uint32"}],4);const Ywe=ts([{name:"a_auto_z_offset",components:1,type:"Float32"}],4),Xwe=ts([{name:"a_x_axis",components:3,type:"Float32"},{name:"a_y_axis",components:3,type:"Float32"}]),Qwe=ts([{name:"a_texb",components:2,type:"Uint16"}]),Jwe=ts([{name:"a_placed",components:2,type:"Uint8"},{name:"a_shift",components:2,type:"Float32"},{name:"a_elevation_from_sea",components:2,type:"Float32"}]),e1e=ts([{name:"a_size_scale",components:1,type:"Float32"},{name:"a_padding",components:2,type:"Float32"},{name:"a_auto_z_offset",components:1,type:"Float32"}]);ts([{type:"Int16",name:"projectedAnchorX"},{type:"Int16",name:"projectedAnchorY"},{type:"Int16",name:"projectedAnchorZ"},{type:"Int16",name:"tileAnchorX"},{type:"Int16",name:"tileAnchorY"},{type:"Float32",name:"x1"},{type:"Float32",name:"y1"},{type:"Float32",name:"x2"},{type:"Float32",name:"y2"},{type:"Int16",name:"padding"},{type:"Uint32",name:"featureIndex"},{type:"Uint16",name:"sourceLayerIndex"},{type:"Uint16",name:"bucketIndex"}]);const S9=ts([{name:"a_pos",components:3,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4),t1e=ts([{name:"a_pos_2f",components:2,type:"Float32"},{name:"a_radius",components:1,type:"Float32"},{name:"a_flags",components:2,type:"Int16"}],4);ts([{name:"triangle",components:3,type:"Uint16"}]),ts([{type:"Int16",name:"projectedAnchorX"},{type:"Int16",name:"projectedAnchorY"},{type:"Int16",name:"projectedAnchorZ"},{type:"Float32",name:"tileAnchorX"},{type:"Float32",name:"tileAnchorY"},{type:"Uint16",name:"glyphStartIndex"},{type:"Uint16",name:"numGlyphs"},{type:"Uint32",name:"vertexStartIndex"},{type:"Uint32",name:"lineStartIndex"},{type:"Uint32",name:"lineLength"},{type:"Uint16",name:"segment"},{type:"Uint16",name:"lowerSize"},{type:"Uint16",name:"upperSize"},{type:"Float32",name:"lineOffsetX"},{type:"Float32",name:"lineOffsetY"},{type:"Uint8",name:"writingMode"},{type:"Uint8",name:"placedOrientation"},{type:"Uint8",name:"hidden"},{type:"Uint32",name:"crossTileID"},{type:"Int16",name:"associatedIconIndex"},{type:"Uint8",name:"flipState"}]),ts([{type:"Float32",name:"tileAnchorX"},{type:"Float32",name:"tileAnchorY"},{type:"Int16",name:"projectedAnchorX"},{type:"Int16",name:"projectedAnchorY"},{type:"Int16",name:"projectedAnchorZ"},{type:"Int16",name:"rightJustifiedTextSymbolIndex"},{type:"Int16",name:"centerJustifiedTextSymbolIndex"},{type:"Int16",name:"leftJustifiedTextSymbolIndex"},{type:"Int16",name:"verticalPlacedTextSymbolIndex"},{type:"Int16",name:"placedIconSymbolIndex"},{type:"Int16",name:"verticalPlacedIconSymbolIndex"},{type:"Uint16",name:"key"},{type:"Uint16",name:"textBoxStartIndex"},{type:"Uint16",name:"textBoxEndIndex"},{type:"Uint16",name:"verticalTextBoxStartIndex"},{type:"Uint16",name:"verticalTextBoxEndIndex"},{type:"Uint16",name:"iconBoxStartIndex"},{type:"Uint16",name:"iconBoxEndIndex"},{type:"Uint16",name:"verticalIconBoxStartIndex"},{type:"Uint16",name:"verticalIconBoxEndIndex"},{type:"Uint16",name:"featureIndex"},{type:"Uint16",name:"numHorizontalGlyphVertices"},{type:"Uint16",name:"numVerticalGlyphVertices"},{type:"Uint16",name:"numIconVertices"},{type:"Uint16",name:"numVerticalIconVertices"},{type:"Uint16",name:"useRuntimeCollisionCircles"},{type:"Uint32",name:"crossTileID"},{type:"Float32",components:2,name:"textOffset"},{type:"Float32",name:"collisionCircleDiameter"},{type:"Float32",name:"zOffset"},{type:"Uint8",name:"hasIconTextFit"},{type:"Uint16",name:"elevationFeatureIndex"}]),ts([{type:"Float32",name:"offsetX"}]),ts([{type:"Int16",name:"x"},{type:"Int16",name:"y"}]);var uo=24;function r1e(h,l,d){return h.sections.forEach(p=>{p.text=function(y,b,w){const k=b.layout.get("text-transform").evaluate(w,{});return k==="uppercase"?y=y.toLocaleUpperCase():k==="lowercase"&&(y=y.toLocaleLowerCase()),Ih.applyArabicShaping&&(y=Ih.applyArabicShaping(y)),y}(p.text,l,d)}),h}const IN={"!":"︕","#":"#",$:"$","%":"%","&":"&","(":"︵",")":"︶","*":"*","+":"+",",":"︐","-":"︲",".":"・","/":"/",":":"︓",";":"︔","<":"︿","=":"=",">":"﹀","?":"︖","@":"@","[":"﹇","\\":"\","]":"﹈","^":"^",_:"︳","`":"`","{":"︷","|":"―","}":"︸","~":"~","¢":"¢","£":"£","¥":"¥","¦":"¦","¬":"¬","¯":" ̄","–":"︲","—":"︱","‘":"﹃","’":"﹄","“":"﹁","”":"﹂","…":"︙","‧":"・","₩":"₩","、":"︑","。":"︒","〈":"︿","〉":"﹀","《":"︽","》":"︾","「":"﹁","」":"﹂","『":"﹃","』":"﹄","【":"︻","】":"︼","〔":"︹","〕":"︺","〖":"︗","〗":"︘","!":"︕","(":"︵",")":"︶",",":"︐","-":"︲",".":"・",":":"︓",";":"︔","<":"︿",">":"﹀","?":"︖","[":"﹇","]":"﹈","_":"︳","{":"︷","|":"―","}":"︸","⦅":"︵","⦆":"︶","。":"︒","「":"﹁","」":"﹂","←":"↑","→":"↓"};function n1e(h){return h==="︶"||h==="﹈"||h==="︸"||h==="﹄"||h==="﹂"||h==="︾"||h==="︼"||h==="︺"||h==="︘"||h==="﹀"||h==="︐"||h==="︓"||h==="︔"||h==="`"||h===" ̄"||h==="︑"||h==="︒"}function s1e(h){return h==="︵"||h==="﹇"||h==="︷"||h==="﹃"||h==="﹁"||h==="︽"||h==="︻"||h==="︹"||h==="︗"||h==="︿"}const j3=4294967296,N9=1/j3,C9=typeof TextDecoder>"u"?null:new TextDecoder("utf-8");let jA=class{constructor(h=new Uint8Array(16)){this.buf=ArrayBuffer.isView(h)?h:new Uint8Array(h),this.dataView=new DataView(this.buf.buffer),this.pos=0,this.type=0,this.length=this.buf.length}readFields(h,l,d=this.length){for(;this.pos>3,b=this.pos;this.type=7&p,h(y,l,this),this.pos===b&&this.skip(p)}return l}readMessage(h,l){return this.readFields(h,l,this.readVarint()+this.pos)}readFixed32(){const h=this.dataView.getUint32(this.pos,!0);return this.pos+=4,h}readSFixed32(){const h=this.dataView.getInt32(this.pos,!0);return this.pos+=4,h}readFixed64(){const h=this.dataView.getUint32(this.pos,!0)+this.dataView.getUint32(this.pos+4,!0)*j3;return this.pos+=8,h}readSFixed64(){const h=this.dataView.getUint32(this.pos,!0)+this.dataView.getInt32(this.pos+4,!0)*j3;return this.pos+=8,h}readFloat(){const h=this.dataView.getFloat32(this.pos,!0);return this.pos+=4,h}readDouble(){const h=this.dataView.getFloat64(this.pos,!0);return this.pos+=8,h}readVarint(h){const l=this.buf;let d,p;return p=l[this.pos++],d=127&p,p<128?d:(p=l[this.pos++],d|=(127&p)<<7,p<128?d:(p=l[this.pos++],d|=(127&p)<<14,p<128?d:(p=l[this.pos++],d|=(127&p)<<21,p<128?d:(p=l[this.pos],d|=(15&p)<<28,function(y,b,w){const k=w.buf;let M,F;if(F=k[w.pos++],M=(112&F)>>4,F<128||(F=k[w.pos++],M|=(127&F)<<3,F<128)||(F=k[w.pos++],M|=(127&F)<<10,F<128)||(F=k[w.pos++],M|=(127&F)<<17,F<128)||(F=k[w.pos++],M|=(127&F)<<24,F<128)||(F=k[w.pos++],M|=(1&F)<<31,F<128))return zb(y,M,b);throw new Error("Expected varint not more than 10 bytes")}(d,h,this)))))}readVarint64(){return this.readVarint(!0)}readSVarint(){const h=this.readVarint();return h%2==1?(h+1)/-2:h/2}readBoolean(){return!!this.readVarint()}readString(){const h=this.readVarint()+this.pos,l=this.pos;return this.pos=h,h-l>=12&&C9?C9.decode(this.buf.subarray(l,h)):function(d,p,y){let b="",w=p;for(;w239?4:k>223?3:k>191?2:1;if(w+H>y)break;H===1?k<128&&(U=k):H===2?(M=d[w+1],(192&M)==128&&(U=(31&k)<<6|63&M,U<=127&&(U=null))):H===3?(M=d[w+1],F=d[w+2],(192&M)==128&&(192&F)==128&&(U=(15&k)<<12|(63&M)<<6|63&F,(U<=2047||U>=55296&&U<=57343)&&(U=null))):H===4&&(M=d[w+1],F=d[w+2],$=d[w+3],(192&M)==128&&(192&F)==128&&(192&$)==128&&(U=(15&k)<<18|(63&M)<<12|(63&F)<<6|63&$,(U<=65535||U>=1114112)&&(U=null))),U===null?(U=65533,H=1):U>65535&&(U-=65536,b+=String.fromCharCode(U>>>10&1023|55296),U=56320|1023&U),b+=String.fromCharCode(U),w+=H}return b}(this.buf,l,h)}readBytes(){const h=this.readVarint()+this.pos,l=this.buf.subarray(this.pos,h);return this.pos=h,l}readPackedVarint(h=[],l){const d=this.readPackedEnd();for(;this.pos127;);else if(l===2)this.pos=this.readVarint()+this.pos;else if(l===5)this.pos+=4;else{if(l!==1)throw new Error(`Unimplemented type: ${l}`);this.pos+=8}}writeTag(h,l){this.writeVarint(h<<3|l)}realloc(h){let l=this.length||16;for(;l268435455||h<0?function(l,d){let p,y;if(l>=0?(p=l%4294967296|0,y=l/4294967296|0):(p=~(-l%4294967296),y=~(-l/4294967296),4294967295^p?p=p+1|0:(p=0,y=y+1|0)),l>=18446744073709552e3||l<-18446744073709552e3)throw new Error("Given varint doesn't fit into 10 bytes");d.realloc(10),function(b,w,k){k.buf[k.pos++]=127&b|128,b>>>=7,k.buf[k.pos++]=127&b|128,b>>>=7,k.buf[k.pos++]=127&b|128,b>>>=7,k.buf[k.pos++]=127&b|128,k.buf[k.pos]=127&(b>>>=7)}(p,0,d),function(b,w){const k=(7&b)<<4;w.buf[w.pos++]|=k|((b>>>=3)?128:0),b&&(w.buf[w.pos++]=127&b|((b>>>=7)?128:0),b&&(w.buf[w.pos++]=127&b|((b>>>=7)?128:0),b&&(w.buf[w.pos++]=127&b|((b>>>=7)?128:0),b&&(w.buf[w.pos++]=127&b|((b>>>=7)?128:0),b&&(w.buf[w.pos++]=127&b)))))}(y,d)}(h,this):(this.realloc(4),this.buf[this.pos++]=127&h|(h>127?128:0),h<=127||(this.buf[this.pos++]=127&(h>>>=7)|(h>127?128:0),h<=127||(this.buf[this.pos++]=127&(h>>>=7)|(h>127?128:0),h<=127||(this.buf[this.pos++]=h>>>7&127))))}writeSVarint(h){this.writeVarint(h<0?2*-h-1:2*h)}writeBoolean(h){this.writeVarint(+h)}writeString(h){h=String(h),this.realloc(4*h.length),this.pos++;const l=this.pos;this.pos=function(p,y,b){for(let w,k,M=0;M55295&&w<57344){if(!k){w>56319||M+1===y.length?(p[b++]=239,p[b++]=191,p[b++]=189):k=w;continue}if(w<56320){p[b++]=239,p[b++]=191,p[b++]=189,k=w;continue}w=k-55296<<10|w-56320|65536,k=null}else k&&(p[b++]=239,p[b++]=191,p[b++]=189,k=null);w<128?p[b++]=w:(w<2048?p[b++]=w>>6|192:(w<65536?p[b++]=w>>12|224:(p[b++]=w>>18|240,p[b++]=w>>12&63|128),p[b++]=w>>6&63|128),p[b++]=63&w|128)}return b}(this.buf,h,this.pos);const d=this.pos-l;d>=128&&k9(l,d,this),this.pos=l-1,this.writeVarint(d),this.pos+=d}writeFloat(h){this.realloc(4),this.dataView.setFloat32(this.pos,h,!0),this.pos+=4}writeDouble(h){this.realloc(8),this.dataView.setFloat64(this.pos,h,!0),this.pos+=8}writeBytes(h){const l=h.length;this.writeVarint(l),this.realloc(l);for(let d=0;d=128&&k9(d,p,this),this.pos=d-1,this.writeVarint(p),this.pos+=p}writeMessage(h,l,d){this.writeTag(h,2),this.writeRawMessage(l,d)}writePackedVarint(h,l){l.length&&this.writeMessage(h,i1e,l)}writePackedSVarint(h,l){l.length&&this.writeMessage(h,a1e,l)}writePackedBoolean(h,l){l.length&&this.writeMessage(h,c1e,l)}writePackedFloat(h,l){l.length&&this.writeMessage(h,o1e,l)}writePackedDouble(h,l){l.length&&this.writeMessage(h,l1e,l)}writePackedFixed32(h,l){l.length&&this.writeMessage(h,u1e,l)}writePackedSFixed32(h,l){l.length&&this.writeMessage(h,d1e,l)}writePackedFixed64(h,l){l.length&&this.writeMessage(h,h1e,l)}writePackedSFixed64(h,l){l.length&&this.writeMessage(h,f1e,l)}writeBytesField(h,l){this.writeTag(h,2),this.writeBytes(l)}writeFixed32Field(h,l){this.writeTag(h,5),this.writeFixed32(l)}writeSFixed32Field(h,l){this.writeTag(h,5),this.writeSFixed32(l)}writeFixed64Field(h,l){this.writeTag(h,1),this.writeFixed64(l)}writeSFixed64Field(h,l){this.writeTag(h,1),this.writeSFixed64(l)}writeVarintField(h,l){this.writeTag(h,0),this.writeVarint(l)}writeSVarintField(h,l){this.writeTag(h,0),this.writeSVarint(l)}writeStringField(h,l){this.writeTag(h,2),this.writeString(l)}writeFloatField(h,l){this.writeTag(h,5),this.writeFloat(l)}writeDoubleField(h,l){this.writeTag(h,1),this.writeDouble(l)}writeBooleanField(h,l){this.writeVarintField(h,+l)}};function zb(h,l,d){return d?4294967296*l+(h>>>0):4294967296*(l>>>0)+(h>>>0)}function k9(h,l,d){const p=l<=16383?1:l<=2097151?2:l<=268435455?3:Math.floor(Math.log(l)/(7*Math.LN2));d.realloc(p);for(let y=d.pos-1;y>=h;y--)d.buf[y+p]=d.buf[y]}function i1e(h,l){for(let d=0;d=0&&p>=l&&SA[this.text.charCodeAt(p)];p--)d--;this.text=this.text.substring(l,d),this.sectionIndex=this.sectionIndex.slice(l,d)}substring(l,d){const p=new Bb;return p.text=this.text.substring(l,d),p.sectionIndex=this.sectionIndex.slice(l,d),p.sections=this.sections,p}toString(){return this.text}getMaxScale(){return this.sectionIndex.reduce((l,d)=>Math.max(l,this.sections[d].scale),0)}addTextSection(l,d){this.text+=l.text,this.sections.push(MN.forText(l.scale,l.fontStack||d));const p=this.sections.length-1;for(let y=0;y=63743?null:++this.imageSectionID:(this.imageSectionID=57344,this.imageSectionID)}}function N3(h,l,d,p,y,b,w,k,M,F,$,U,H,Z,Y,ne=1){const ce=Bb.fromFeature(h,y,ne);U===Gc.vertical&&ce.verticalizePunctuation(H);let le=[];const ye=function(Ke,Je,it,Pt,ft,Ft){if(!Ke)return[];const Vt=[],qt=function(Xt,Rt,It,Jt,gr,cr){let Gr=0;for(let Er=0;Er=0;let nr=0;for(let Xt=0;Xt0&&Ts>Tn&&(Tn=Ts)}else{const ys=it[tr.fontStack];if(!ys)continue;ys[Cr]&&(kn=ys[Cr]);const ks=Je[tr.fontStack];if(!ks)continue;const Ts=ks.glyphs[Cr];if(!Ts)continue;if(Xr=Ts.metrics,zn=Cr!==8203?uo:0,cr){const qs=ks.ascender!==void 0?Math.abs(ks.ascender):0,di=ks.descender!==void 0?Math.abs(ks.descender):0,ei=(qs+di)*Kr;Js-d/2;){if(w--,w<0)return!1;k-=h[w].dist(b),b=h[w]}k+=h[w].dist(h[w+1]),w++;const M=[];let F=0;for(;kp;)F-=M.shift().angleDelta;if(F>y)return!1;w++,k+=$.dist(U)}return!0}function F9(h){let l=0;for(let d=0;dF){const Y=(F-M)/Z,ne=fn(U.x,H.x,Y),ce=fn(U.y,H.y,Y),le=new lm(ne,ce,0,H.angleTo(U),$);return!w||L9(h,le,k,w,l)?le:void 0}M+=Z}}function _1e(h,l,d,p,y,b,w,k,M){const F=z9(p,b,w),$=B9(p,y),U=$*w,H=h[0].x===0||h[0].x===M||h[0].y===0||h[0].y===M;return l-U=0&&Ee=0&&Ue=0&&H+F<=$){const Le=new lm(Ee,Ue,0,ye,Y);p&&!L9(h,Le,b,p,y)||Z.push(Le)}}U+=le}return k||Z.length||w||(Z=$9(h,U/2,d,p,y,b,w,!0,M)),Z}function U9(h){let l=0,d=0;for(const w of h)l+=w.w*w.h,d=Math.max(d,w.w);h.sort((w,k)=>k.h-w.h);const p=[{x:0,y:0,w:Math.max(Math.ceil(Math.sqrt(l/.95)),d),h:1/0}];let y=0,b=0;for(const w of h)for(let k=p.length-1;k>=0;k--){const M=p[k];if(!(w.w>M.w||w.h>M.h)){if(w.x=M.x,w.y=M.y,b=Math.max(b,w.y+w.h),y=Math.max(y,w.x+w.w),w.w===M.w&&w.h===M.h){const F=p.pop();F&&k1?Y-1:Y,il.copy(U.data,F,{x:0,y:0},{x:ne,y:ce},U.data,p),il.copy(U.data,F,{x:0,y:ye-Y},{x:ne,y:ce-Y},{width:le,height:Y},p),il.copy(U.data,F,{x:0,y:0},{x:ne,y:ce+ye},{width:le,height:Y},p),il.copy(U.data,F,{x:le-Y,y:0},{x:ne-Y,y:ce},{width:Y,height:ye},p),il.copy(U.data,F,{x:0,y:0},{x:ne+le,y:ce},{width:Y,height:ye},p),il.copy(U.data,F,{x:le-Y,y:ye-Y},{x:ne-Y,y:ce-Y},{width:Y,height:Y},p),il.copy(U.data,F,{x:0,y:ye-Y},{x:ne+le,y:ce-Y},{width:Y,height:Y},p),il.copy(U.data,F,{x:0,y:0},{x:ne+le,y:ce+ye},{width:Y,height:Y},p),il.copy(U.data,F,{x:le-Y,y:0},{x:ne-Y,y:ce+ye},{width:Y,height:Y},p)}this.lut=p,this.image=F,this.iconPositions=y,this.patternPositions=b}addImages(l,d,p,y){for(const[b,w]of l.entries()){const{bin:k,imagePosition:M,imageVariant:F}=A3(b,w,p);d.set(b,M),y.push(k),w.hasRenderCallback&&this.haveRenderCallbacks.push(F.id)}}patchUpdatedImages(l,d,p){this.haveRenderCallbacks=this.haveRenderCallbacks.filter(y=>l.hasImage(y,p)),l.dispatchRenderCallbacks(this.haveRenderCallbacks,p);for(const y of l.getUpdatedImages(p)){for(const b of this.iconPositions.keys()){const w=Nh.parse(b);if(vl.isEqual(w.id,y)){const k=l.getImage(y,p);this.patchUpdatedImage(this.iconPositions.get(b),k,d,null)}}for(const b of this.patternPositions.keys()){const w=Nh.parse(b);if(vl.isEqual(w.id,y)){const k=l.getImage(y,p);this.patchUpdatedImage(this.patternPositions.get(b),k,d,this.lut)}}}}patchUpdatedImage(l,d,p,y=null){if(!l||!d||l.version===d.version)return;l.version=d.version;const[b,w]=l.tl,k=l.sdf;if(this.lut||k){const M={width:d.data.width,height:d.data.height},F=new il(M);il.copy(d.data,F,{x:0,y:0},{x:0,y:0},M,y,k),p.update(F,{position:{x:b,y:w}})}else p.update(d.data,{position:{x:b,y:w}})}}Lr(ON,"ImagePosition"),Lr(V9,"ImageAtlas");const RN=1e20;function q9(h,l,d,p,y,b,w,k,M){for(let F=l;F-1);M++,b[M]=k,w[M]=F,w[M+1]=RN}for(let k=0,M=0;k{let M=this.entries[b];M||(M=this.entries[b]={glyphs:{},requests:{},ranges:{},ascender:void 0,descender:void 0});let F=M.glyphs[w];if(F!==void 0)return void k(null,{stack:b,id:w,glyph:F});if(F=this._tinySDF(M,b,w),F)return M.glyphs[w]=F,void k(null,{stack:b,id:w,glyph:F});const $=Math.floor(w/256);if(256*$>65535)return Ge("glyphs > 65535 not supported"),void k(null,{stack:b,id:w,glyph:F});if(M.ranges[$])return void k(null,{stack:b,id:w,glyph:F});let U=M.requests[$];U||(U=M.requests[$]=[],Vb.loadGlyphRange(b,$,y,this.requestManager,(H,Z)=>{if(Z){M.ascender=Z.ascender,M.descender=Z.descender;for(const Y in Z.glyphs)this._doesCharSupportLocalGlyph(+Y)||(M.glyphs[+Y]=Z.glyphs[+Y]);M.ranges[$]=!0}for(const Y of U)Y(H,Z);delete M.requests[$]})),U.push((H,Z)=>{H?k(H):Z&&k(null,{stack:b,id:w,glyph:Z.glyphs[w]||null})})},(b,w)=>{if(b)d(b);else if(w){const k={};for(const{stack:M,id:F,glyph:$}of w)k[M]===void 0&&(k[M]={}),k[M].glyphs===void 0&&(k[M].glyphs={}),k[M].glyphs[F]=$&&{id:$.id,bitmap:$.bitmap.clone(),metrics:$.metrics},k[M].ascender=this.entries[M].ascender,k[M].descender=this.entries[M].descender;d(null,k)}})}_doesCharSupportLocalGlyph(l){return this.localGlyphMode!==P3.none&&(this.localGlyphMode===P3.all?!!this.localFontFamily:!!this.localFontFamily&&(an["CJK Unified Ideographs"](l)||an["Hangul Syllables"](l)||an.Hiragana(l)||an.Katakana(l)||an["CJK Symbols and Punctuation"](l)||an["CJK Unified Ideographs Extension A"](l)||an["CJK Unified Ideographs Extension B"](l)||an.Osage(l)))}_tinySDF(l,d,p){const y=this.localFontFamily;if(!y||!this._doesCharSupportLocalGlyph(p))return;let b=l.tinySDF;if(!b){let ne="400";/bold/i.test(d)?ne="900":/medium/i.test(d)?ne="500":/light/i.test(d)&&(ne="200"),b=l.tinySDF=new Vb.TinySDF({fontFamily:y,fontWeight:ne,fontSize:24*Vh,buffer:3*Vh,radius:8*Vh}),b.fontWeight=ne}if(this.localGlyphs[b.fontWeight][p])return this.localGlyphs[b.fontWeight][p];const w=String.fromCodePoint(p),{data:k,width:M,height:F,glyphWidth:$,glyphHeight:U,glyphLeft:H,glyphTop:Z,glyphAdvance:Y}=b.draw(w);return this.localGlyphs[b.fontWeight][p]={id:p,bitmap:new Bg({width:M,height:F},k),metrics:{width:$/Vh,height:U/Vh,left:H/Vh,top:Z/Vh-27,advance:Y/Vh,localGlyph:!0}}}}Vb.loadGlyphRange=function(h,l,d,p,y){const b=256*l,w=b+255,k=p.transformRequest(p.normalizeGlyphsURL(d).replace("{fontstack}",h).replace("{range}",`${b}-${w}`),Mx.Glyphs);Sh(k,(M,F)=>{if(M)y(M);else if(F){const $={},U=function(H){return new jA(H).readFields(p1e,{})}(F);for(const H of U.glyphs)$[H.id]=H;y(null,{glyphs:$,ascender:U.ascender,descender:U.descender})}})},Vb.TinySDF=class{constructor({fontSize:h=24,buffer:l=3,radius:d=8,cutoff:p=.25,fontFamily:y="sans-serif",fontWeight:b="normal",fontStyle:w="normal",lang:k=null}={}){this.buffer=l,this.cutoff=p,this.radius=d,this.lang=k;const M=this.size=h+4*l,F=this._createCanvas(M),$=this.ctx=F.getContext("2d",{willReadFrequently:!0});$.font=`${w} ${b} ${h}px ${y}`,$.textBaseline="alphabetic",$.textAlign="left",$.fillStyle="black",this.gridOuter=new Float64Array(M*M),this.gridInner=new Float64Array(M*M),this.f=new Float64Array(M),this.z=new Float64Array(M+1),this.v=new Uint16Array(M)}_createCanvas(h){const l=document.createElement("canvas");return l.width=l.height=h,l}draw(h){const{width:l,actualBoundingBoxAscent:d,actualBoundingBoxDescent:p,actualBoundingBoxLeft:y,actualBoundingBoxRight:b}=this.ctx.measureText(h),w=Math.ceil(d),k=Math.max(0,Math.min(this.size-this.buffer,Math.ceil(b-y))),M=Math.min(this.size-this.buffer,w+Math.ceil(p)),F=k+2*this.buffer,$=M+2*this.buffer,U=Math.max(F*$,0),H=new Uint8ClampedArray(U),Z={data:H,width:F,height:$,glyphWidth:k,glyphHeight:M,glyphTop:w,glyphLeft:0,glyphAdvance:l};if(k===0||M===0)return Z;const{ctx:Y,buffer:ne,gridInner:ce,gridOuter:le}=this;this.lang&&(Y.lang=this.lang),Y.clearRect(ne,ne,k,M),Y.fillText(h,ne,ne+w);const ye=Y.getImageData(ne,ne,k,M);le.fill(RN,0,U),ce.fill(0,0,U);for(let we=0;we0?Ke*Ke:0,ce[Le]=Ke<0?Ke*Ke:0}}q9(le,0,0,F,$,F,this.f,this.v,this.z),q9(ce,ne,ne,k,M,F,this.f,this.v,this.z);for(let we=0;we{const er=kA(ft.stretch-ye,we,$,h.left*y),nr=TA(ft.fixed-Le,Ke,ft.stretch,Y),Yt=kA(Ft.stretch-Ee,Ue,U,h.top*y),Xt=TA(Ft.fixed-Je,it,Ft.stretch,ne),Rt=kA(Vt.stretch-ye,we,$,h.left*y),It=TA(Vt.fixed-Le,Ke,Vt.stretch,Y),Jt=kA(qt.stretch-Ee,Ue,U,h.top*y),gr=TA(qt.fixed-Je,it,qt.stretch,ne),cr=new Wt(er,Yt),Gr=new Wt(Rt,Yt),Er=new Wt(Rt,Jt),Or=new Wt(er,Jt),Br=new Wt(nr/k,Xt/k),$n=new Wt(It/k,gr/k),dr=l*Math.PI/180;if(dr){const Js=Math.sin(dr),Fe=Math.cos(dr),qe=[Fe,-Js,Js,Fe];cr._matMult(qe),Gr._matMult(qe),Or._matMult(qe),Er._matMult(qe)}const $r=ft.stretch+ft.fixed,wn=Vt.stretch+Vt.fixed,ls=Ft.stretch+Ft.fixed,hs=qt.stretch+qt.fixed,Tn=h.imageSecondary;return{tl:cr,tr:Gr,bl:Or,br:Er,texPrimary:{x:w.paddedRect.x+Qf+$r,y:w.paddedRect.y+Qf+ls,w:wn-$r,h:hs-ls},texSecondary:Tn?{x:Tn.paddedRect.x+Qf+$r,y:Tn.paddedRect.y+Qf+ls,w:wn-$r,h:hs-ls}:void 0,writingMode:void 0,glyphOffset:[0,0],sectionIndex:0,pixelOffsetTL:Br,pixelOffsetBR:$n,minFontScaleX:Ke/k/$,minFontScaleY:it/k/U,isSDF:d}};if(p&&(w.stretchX||w.stretchY)){const ft=G9(H,ce,Y),Ft=G9(Z,le,ne);for(let Vt=0;Vtb)&&(b=Y.x),(!Z||Y.y>w)&&(w=Y.y)}const M=Math.min(b-p,w-y);let F=M/2;const $=new M0([],S1e);if(M===0)return new Wt(p,y);for(let Z=p;ZU.d||!U.d)&&(U=Z,d&&console.log("found best %d after %d probes",Math.round(1e4*Z.d)/1e4,H)),Z.max-U.d<=l||(F=Z.h/2,$.push(new qb(Z.p.x-F,Z.p.y-F,F,h)),$.push(new qb(Z.p.x+F,Z.p.y-F,F,h)),$.push(new qb(Z.p.x-F,Z.p.y+F,F,h)),$.push(new qb(Z.p.x+F,Z.p.y+F,F,h)),H+=4)}return d&&(console.log(`num probes: ${H}`),console.log(`best distance: ${U.d}`)),U.p}function S1e(h,l){return l.max-h.max}class qb{constructor(l,d,p,y){this.p=new Wt(l,d),this.h=p,this.d=function(b,w){let k=!1,M=1/0;for(let F=0;Fb.y!=ne.y>b.y&&b.x<(ne.x-Y.x)*(b.y-Y.y)/(ne.y-Y.y)+Y.x&&(k=!k),M=Math.min(M,ua(b,Y,ne))}}return(k?1:-1)*Math.sqrt(M)}(this.p,y),this.max=this.d+this.h*Math.SQRT2}}const N1e=Object.keys,M3=Number.POSITIVE_INFINITY,C1e=Math.sqrt(2);function Ug(h,l,d,p,y){const b=k3(h)&&h.collisionPadding?h.collisionPadding:[0,0,0,0],w={top:h.top-b[1],bottom:h.bottom+b[3],left:h.left-b[0],right:h.right+b[2],scaled:!1};return p!==void 0&&function(k,M){k.top*=M,k.bottom*=M,k.left*=M,k.right*=M,k.scaled=!0}(w,p),d&&function(k,M){if(!M)return;const F=Xn(M),$=new Wt(k.left,k.top),U=new Wt(k.right,k.top),H=new Wt(k.left,k.bottom),Z=new Wt(k.right,k.bottom),Y=new Wt(0,0);$._rotateAround(F,Y),U._rotateAround(F,Y),H._rotateAround(F,Y),Z._rotateAround(F,Y),k.left=Math.min($.x,U.x,H.x,Z.x),k.right=Math.max($.x,U.x,H.x,Z.x),k.top=Math.min($.y,U.y,H.y,Z.y),k.bottom=Math.max($.y,U.y,H.y,Z.y)}(w,d),y&&(w.left+=y[0],w.right+=y[0],w.top+=y[1],w.bottom+=y[1]),l?{top:Math.min(l.top,w.top),bottom:Math.max(l.bottom,w.bottom),left:Math.min(l.left,w.left),right:Math.max(l.right,w.right),scaled:l.scaled||w.scaled}:w}function Z9(h,[l,d]){let p=0,y=0;if(d===M3){l<0&&(l=0);const b=l/C1e;switch(h){case"top-right":case"top-left":y=b-7;break;case"bottom-right":case"bottom-left":y=7-b;break;case"bottom":y=7-l;break;case"top":y=l-7}switch(h){case"top-right":case"bottom-right":p=-b;break;case"top-left":case"bottom-left":p=b;break;case"left":p=l;break;case"right":p=-l}}else{switch(l=Math.abs(l),d=Math.abs(d),h){case"top-right":case"top-left":case"top":y=d-7;break;case"bottom-right":case"bottom-left":case"bottom":y=7-d}switch(h){case"top-right":case"bottom-right":case"right":p=-l;break;case"top-left":case"bottom-left":case"left":p=l}}return[p,y]}function k1e(h,l,d,p,y,b,w,k,M,F,$,U,H,Z){const Y=h.layers[0],ne=Y.appearances;if(ne.length===0)return{iconBBox:null,iconVerticalBBox:null,textBBox:null,textVerticalBBox:null};const ce={iconBBox:null,iconVerticalBBox:null},le={textBBox:null,textVerticalBBox:null},{baseIconRotate:ye,baseTextRotate:we,iconScaleFactor:Ee}=function(Le,Ke,Je){const it=Le.get("icon-rotate").evaluate(Ke,{},Je),Pt=Le.get("text-rotate").evaluate(Ke,{},Je),[ft,Ft]=Le.get("icon-size-scale-range");return{baseIconRotate:it,baseTextRotate:Pt,iconScaleFactor:ue(1,ft,Ft)}}(p,y,b);l&&(ce.iconBBox=Ug(l,ce.iconBBox,ye,w),d)&&(ce.iconVerticalBBox=Ug(d,ce.iconVerticalBBox,ye+90,w));const Ue=AA(U.horizontal);Ue&&(le.textBBox=Ug(Ue,le.textBBox,we,1,Z)),U.vertical&&(le.textVerticalBBox=Ug(U.vertical,le.textVerticalBBox,we+90,1,Z));for(const Le of ne)Le.hasIconProperties()&&T1e(ce,h,Y,Le,y,b,k,ye,w,M,l,F,Ee,$),Le.hasTextProperties()&&E1e(le,Y,Le,y,b,Z,we,H,Ue,U.vertical);return{iconBBox:ce.iconBBox,iconVerticalBBox:ce.iconVerticalBBox,textBBox:le.textBBox,textVerticalBBox:le.textVerticalBBox}}function T1e(h,l,d,p,y,b,w,k,M,F,$,U,H,Z){const{appearanceIconOffset:Y,appearanceIconRotate:ne,appearanceIconSize:ce}=function(Ee,Ue,Le,Ke,Je,it,Pt,ft){const Ft=Ee.hasProperty("icon-offset")?Ue.getAppearanceValueAndResolveTokens(Ee,"icon-offset",Le,Ke,[]):null,Vt=Ft&&Array.isArray(Ft)?Ft:Je,qt=Ee.hasProperty("icon-rotate")?Ue.getAppearanceValueAndResolveTokens(Ee,"icon-rotate",Le,Ke,[]):null,er=typeof qt=="number"?qt:it,nr=Ee.hasProperty("icon-size")?Ue.getAppearanceValueAndResolveTokens(Ee,"icon-size",Le,Ke,[]):null;return{appearanceIconOffset:Vt,appearanceIconRotate:er,appearanceIconSize:typeof nr=="number"?nr*ft.iconScaleFactor:Pt}}(p,d,y,b,w,k,M,F);let le=null,ye=null,we=null;p.hasProperty("icon-image")?we=function(Ee,Ue,Le,Ke,Je,it,Pt){let ft=null;const Ft=Ue.getAppearanceValueAndResolveTokens(Le,"icon-image",Ke,Je,[]);if(Ft){const Vt=Ee.getResolvedImageFromTokens(Ft),qt=Le.getUnevaluatedProperty("icon-size"),er=DN(Vt,$b(Ee.zoom,qt,Ee.worldview),qt,Je,Ee.zoom,Ke,Ee.pixelRatio,Pt,Ee.worldview);ft=it.get(er.iconPrimary.toString())}return ft}(l,d,p,y,b,U,H):$&&(we=$.imagePrimary),we&&(le=NA(we,null,Y,Z),l.allowVerticalPlacement&&(ye=NA(we,null,Y,Z))),le&&(h.iconBBox=Ug(le,h.iconBBox,ne,ce)),ye&&(h.iconVerticalBBox=Ug(ye,h.iconVerticalBBox,ne+90,ce))}function E1e(h,l,d,p,y,b,w,k,M,F){const{appearanceTextOffset:$,appearanceTextRotate:U,appearanceTextSize:H}=function(Y,ne,ce,le,ye,we,Ee){const Ue=Y.hasProperty("text-offset")?ne.getAppearanceValueAndResolveTokens(Y,"text-offset",ce,le,[]):null,Le=Ue&&Array.isArray(Ue)?[Ue[0]*uo,Ue[1]*uo]:ye,Ke=Y.hasProperty("text-rotate")?ne.getAppearanceValueAndResolveTokens(Y,"text-rotate",ce,le,[]):null,Je=typeof Ke=="number"?Ke:we,it=Y.hasProperty("text-size")?ne.getAppearanceValueAndResolveTokens(Y,"text-size",ce,le,[]):null;return{appearanceTextOffset:Le,appearanceTextRotate:Je,appearanceTextSize:typeof it=="number"?it:Ee}}(d,l,p,y,b,w,k),Z=H/k;M&&(h.textBBox=Ug(M,h.textBBox,U,Z,$)),F&&(h.textVerticalBBox=Ug(F,h.textVerticalBBox,U+90,Z,$))}function EA(h,l,d,p,y,b,w,k,M){if(!l||!l.usvg)return;const F=D9(p),$=D9(y),U=b!=="both"&&b!=="width"||!O9(p)?1:$.width/F.width,H=b!=="both"&&b!=="height"||!R9(p)?1:$.height/F.height;d.scaleSelf(U,H);const Z=d.toString();w.set(Z,d),k.set(Z,l);const{imagePosition:Y}=A3(Z,l,wv);M.set(Z,Y)}function Y9(h,l,d,p,y,b,w,k,M){if(!h)return;const F=function($,U,H,Z,Y,ne){if($.kind==="camera")return $.maxSize;if($.kind==="composite"){const ce=U.possiblyEvaluate(new wi($.maxZoom,{worldview:ne}),H).evaluate(Y,{},H),le=U.possiblyEvaluate(new wi($.minZoom,{worldview:ne}),H).evaluate(Y,{},H);return Math.max(ce,le)}return U.possiblyEvaluate(new wi(Z,{worldview:ne})).evaluate(Y,{},H)}(l,d,p,y,b,M);return h.scaleSelf(F*k*w)}function DN(h,l,d,p,y,b,w,k,M){return{iconPrimary:Y9(h.getPrimary(),l,d,p,y,b,w,k,M),iconSecondary:Y9(h.getSecondary(),l,d,p,y,b,w,k,M)}}function A1e(h,l,d){if(!l)return;const p=d.get(h.toString()),y=d.get(l.toString());p&&y&&(p.paddedRect.w===y.paddedRect.w&&p.paddedRect.h===y.paddedRect.h||Ge(`Mismatch in icon variant sizes: ${h.toString()} and ${l.toString()}`),p.usvg!==y.usvg&&Ge(`Mismatch in icon variant image types: ${h.id} and ${l.id}`))}function X9(h,l,d,p){if(!h)return;const y=l.get(d.toString());if(h.imagePrimary=y,p){const b=l.get(p.toString());h.imageSecondary=b}}function P1e(h,l){for(const d in h.horizontal)Q9(h.horizontal[d],l);Q9(h.vertical,l)}function Q9(h,l){if(h){for(const d of h.positionedLines)for(const p of d.positionedGlyphs)if(p.image!==null){const y=p.image.toString();p.rect=l.get(y).paddedRect}}}function O3(h){switch(h){case"right":case"top-right":case"bottom-right":return"right";case"left":case"top-left":case"bottom-left":return"left"}return"center"}function I1e(h,l,d,p,y,b,w,k,M){const F=AA(b.horizontal)||b.vertical,$=d.get("icon-text-fit-padding").evaluate(p,{},y);let U,H=l;return l&&M!=="none"&&(h.allowVerticalPlacement&&b.vertical&&(U=T3(l,b.vertical,M,$,k,w)),F&&(H=T3(l,F,M,$,k,w))),{defaultShapedIcon:H,verticallyShapedIcon:U}}function M1e(h,l,d,p,y,b,w,k,M,F,$,U,H,Z,Y,ne,ce,le,ye,we,Ee,Ue,Le,Ke){let Je=w.textMaxSize.evaluate(l,{},H);Je===void 0?Je=k*w.textScaleFactor:Je*=w.textScaleFactor;const it=h.layers[0].layout,Pt=uo,ft=k*w.textScaleFactor/Pt,Ft=AA(d.horizontal)||d.vertical;if(ce!=="none"&&h.appearanceFeatureData&&l.index18&&Jt>2&&(Jt>>=1),Math.max(mr/(512*Jt),1)*it.get("symbol-spacing")),nr=it.get("text-padding")*h.tilePixelRatio,Yt=it.get("icon-padding")*h.tilePixelRatio,Xt=Xn(it.get("text-max-angle")),Rt=it.get("icon-rotation-alignment")==="map"&&we!=="point",It=er/2;var Jt;h.hasAnyIconTextFit===!1&&ce!=="none"&&(h.hasAnyIconTextFit=!0);const gr=l.properties?+l.properties[Mt]:null,cr=gr&&h.elevationFeatureIdToIndex?h.elevationFeatureIdToIndex.get(gr):65535,Gr=(Er,Or,Br)=>{if(Or.x<0||Or.x>=mr||Or.y<0||Or.y>=mr)return;let $n=null;if(Vt){const{x:dr,y:$r,z:wn}=Z.projectTilePoint(Or.x,Or.y,Br);$n={anchor:new lm(dr,$r,wn,0,void 0),up:Z.upVector(Br,Or.x,Or.y)}}(function(dr,$r,wn,ls,hs,Tn,Js,Fe,qe,zt,tr,Nr,Cr,Kr,Xr,kn,In,zn,rs,un,bn,ys,ks,Ts,qs,di,ei,Ms,Fs,Mn,ds,Vi,on){const ns=dr.addToLineVertexArray($r,ls);let ai,yi,ji,ga,xi,ln,Ki,Hs=0,Fi=0,$a=0,ho=0,Ea=-1,Aa=-1;const Qa={};let lc=b0("");const vi=wn?wn.anchor:$r,da=Ms!=="none";let ya=0,Nc=0;if(qe._unevaluatedLayout.getValue("text-radial-offset")===void 0){const Vo=qe.layout.get("text-offset").evaluate(bn,{},qs);ya=Vo[0]*uo,Nc=Vo[1]*uo}else ya=qe.layout.get("text-radial-offset").evaluate(bn,{},qs)*uo,Nc=M3;if(dr.allowVerticalPlacement&&hs.vertical){const Vo=hs.vertical;if(Xr)ln=R3(Vo),Fe&&(Ki=R3(Fe));else{const Fl=qe.layout.get("text-rotate").evaluate(bn,{},qs)+90;ji=PA(zt,vi,$r,tr,Nr,Cr,Vo,Kr,Fl,kn,Vi),Fe&&(ga=PA(zt,vi,$r,tr,Nr,Cr,Fe,zn,Fl,null,ds))}}if(Tn){const Vo=dr.iconSizeData,Fl=qe.layout.get("icon-rotate").evaluate(bn,{},qs),Kc=I3(Tn,Fl,ks,da,ys.iconScaleFactor),Hg=Fe?I3(Fe,Fl,ks,da,ys.iconScaleFactor):void 0;yi=PA(zt,vi,$r,tr,Nr,Cr,Tn,zn,Fl,null,Mn);const Xb=function(Gh,eC,yK,Hje,xK,vK,Wje,Gje){const _K=Gh.layers[0],bK=_K.appearances;let Qb=eC.length;if(yK&&(Qb=Math.max(Qb,yK.length)),bK.length===0)return Qb;const[Kje,Zje]=Hje.get("icon-size-scale-range"),Yje=ue(1,Kje,Zje);for(const wK of bK){const jK=wK.getUnevaluatedProperties();if(jK._values["icon-image"].value!==void 0){const SK=_K.getAppearanceValueAndResolveTokens(wK,"icon-image",xK,vK,[]);if(SK){const NK=Gh.getResolvedImageFromTokens(SK);if(NK){const CK=jK._values["icon-size"],Xje=DN(NK,$b(Gh.zoom,CK,Gh.worldview),CK,vK,Gh.zoom,xK,Gh.pixelRatio,Yje,Gh.worldview),Qje=Wje.get(Xje.iconPrimary.toString());Qb=Math.max(Qb,b1e(Qje,Gje))}}}}return Qb}(dr,Kc,Hg,qe.layout,bn,qs,dr.iconAtlasPositions,da);Hs=4*Xb;let Wh=null;Vo.kind==="source"?(Wh=[Uh*qe.layout.get("icon-size").evaluate(bn,{},qs)*ys.iconScaleFactor],Wh[0]>cm&&Ge(`${dr.layerIds[0]}: Value for "icon-size" is >= ${LN}. Reduce your "icon-size".`)):Vo.kind==="composite"&&(Wh=[Uh*ys.compositeIconSizes[0].evaluate(bn,{},qs)*ys.iconScaleFactor,Uh*ys.compositeIconSizes[1].evaluate(bn,{},qs)*ys.iconScaleFactor],(Wh[0]>cm||Wh[1]>cm)&&Ge(`${dr.layerIds[0]}: Value for "icon-size" is >= ${LN}. Reduce your "icon-size".`)),dr.addSymbols(dr.icon,Kc,Wh,un,rs,bn,void 0,wn,$r,ns.lineStartIndex,ns.lineLength,-1,Ts,qs,di,ei,dr.symbolInstances.length,Xb),Ea=dr.icon.placedSymbolArray.length-1,Hg&&(Fi=4*Xb,dr.addSymbols(dr.icon,Hg,Wh,un,rs,bn,Gc.vertical,wn,$r,ns.lineStartIndex,ns.lineLength,-1,Ts,qs,di,ei,dr.symbolInstances.length,Xb),Aa=dr.icon.placedSymbolArray.length-1)}for(const Vo in hs.horizontal){const Fl=Vo,Kc=hs.horizontal[Fl];ai||(lc=b0(Kc.text),Xr?xi=R3(Kc):ai=PA(zt,vi,$r,tr,Nr,Cr,Kc,Kr,qe.layout.get("text-rotate").evaluate(bn,{},qs),kn,Vi));const Hg=Kc.positionedLines.length===1;if($a+=J9(dr,wn,$r,Kc,Js,qe,Xr,bn,kn,ns,hs.vertical?Gc.horizontal:Gc.horizontalOnly,Hg?N1e(hs.horizontal):[Fl],Qa,Ea,ys,Ts,qs,dr.symbolInstances.length,di),Hg)break}hs.vertical&&(ho+=J9(dr,wn,$r,hs.vertical,Js,qe,Xr,bn,kn,ns,Gc.vertical,["vertical"],Qa,Aa,ys,Ts,qs,dr.symbolInstances.length,di));let Ua=-1;const Vd=(Vo,Fl)=>Vo?Math.max(Vo,Fl):Fl;Ua=Vd(xi,Ua),Ua=Vd(ln,Ua),Ua=Vd(Ki,Ua);const Jf=Ua>-1?1:0;dr.glyphOffsetArray.length>=65535&&Ge("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907"),bn.sortKey!==void 0&&dr.addToSortKeyRanges(dr.symbolInstances.length,bn.sortKey),dr.symbolInstances.emplaceBack($r.x,$r.y,vi.x,vi.y,vi.z,Qa.right>=0?Qa.right:-1,Qa.center>=0?Qa.center:-1,Qa.left>=0?Qa.left:-1,Qa.vertical>=0?Qa.vertical:-1,Ea,Aa,lc,ai!==void 0?ai:dr.collisionBoxArray.length,ai!==void 0?ai+1:dr.collisionBoxArray.length,ji!==void 0?ji:dr.collisionBoxArray.length,ji!==void 0?ji+1:dr.collisionBoxArray.length,yi!==void 0?yi:dr.collisionBoxArray.length,yi!==void 0?yi+1:dr.collisionBoxArray.length,ga||dr.collisionBoxArray.length,ga?ga+1:dr.collisionBoxArray.length,tr,$a,ho,Hs,Fi,Jf,0,ya,Nc,Ua,0,da?1:0,Fs)})(h,Or,$n,Er,d,p,b,y,h.layers[0],h.collisionBoxArray,l.index,l.sourceLayerIndex,h.index,nr,ye,F,0,Yt,Rt,le,l,w,$,U,H,Y,ne,ce,cr,Ee,Ue,Le)};if(we==="line")for(const Er of hA(l.geometry,0,0,mr,mr)){const Or=_1e(Er,er,Xt,d.vertical||Ft,p,Pt,qt,h.overscaling,mr);for(const Br of Or)Ft&&O1e(h,Ft.text,It,Br)||Gr(Er,Br,H)}else if(we==="line-center"){for(const Er of l.geometry)if(Er.length>1){const Or=v1e(Er,Xt,d.vertical||Ft,p,Pt,qt);Or&&Gr(Er,Or,H)}}else if(l.type==="Polygon")for(const Er of vN(l.geometry,0)){const Or=j1e(Er,16);Gr(Er[0],new lm(Or.x,Or.y,0,0,void 0),H)}else if(l.type==="LineString")for(const Er of l.geometry)Gr(Er,new lm(Er[0].x,Er[0].y,0,0,void 0),H);else if(l.type==="Point")for(const Er of l.geometry)for(const Or of Er)Gr([Or],new lm(Or.x,Or.y,0,0,void 0),H)}const LN=255,cm=LN*Uh;function J9(h,l,d,p,y,b,w,k,M,F,$,U,H,Z,Y,ne,ce,le,ye){const we=function(Le,Ke,Je,it,Pt,ft,Ft,Vt){const qt=[];if(Ke.positionedLines.length===0)return qt;const er=it.layout.get("text-rotate").evaluate(ft,{})*Math.PI/180,nr=function(Jt){const gr=Jt[0],cr=Jt[1],Gr=gr*cr;return Gr>0?[gr,-cr]:Gr<0?[-gr,cr]:gr===0?[cr,gr]:[cr,-gr]}(Je);let Yt=Math.abs(Ke.top-Ke.bottom);for(const Jt of Ke.positionedLines)Yt-=Jt.lineOffset;const Xt=Ke.positionedLines.length,Rt=Yt/Xt;let It=Ke.top-Je[1];for(let Jt=0;Jtcm&&Ge(`${h.layerIds[0]}: Value for "text-size" is >= ${LN}. Reduce your "text-size".`)):Ee.kind==="composite"&&(Ue=[Uh*Y.compositeTextSizes[0].evaluate(k,{},ce)*Y.textScaleFactor,Uh*Y.compositeTextSizes[1].evaluate(k,{},ce)*Y.textScaleFactor],(Ue[0]>cm||Ue[1]>cm)&&Ge(`${h.layerIds[0]}: Value for "text-size" is >= ${LN}. Reduce your "text-size".`)),h.addSymbols(h.text,we,Ue,M,w,k,$,l,d,F.lineStartIndex,F.lineLength,Z,ne,ce,ye,!1,le,we.length);for(const Le of U)H[Le]=h.text.placedSymbolArray.length-1;return 4*we.length}function AA(h){for(const l in h)return h[l];return null}function PA(h,l,d,p,y,b,w,k,M,F,$){let U,H,Z,Y;if(U=$?$.top:w.top,H=$?$.bottom:w.bottom,Z=$?$.left:w.left,Y=$?$.right:w.right,k3(w)&&w.collisionPadding){const ne=w.collisionPadding;Z-=ne[0],U-=ne[1],Y+=ne[2],H+=ne[3]}if(M){const ne=new Wt(Z,U),ce=new Wt(Y,U),le=new Wt(Z,H),ye=new Wt(Y,H),we=Xn(M);let Ee=new Wt(0,0);F&&(Ee=new Wt(F[0],F[1])),ne._rotateAround(we,Ee),ce._rotateAround(we,Ee),le._rotateAround(we,Ee),ye._rotateAround(we,Ee),Z=Math.min(ne.x,ce.x,le.x,ye.x),Y=Math.max(ne.x,ce.x,le.x,ye.x),U=Math.min(ne.y,ce.y,le.y,ye.y),H=Math.max(ne.y,ce.y,le.y,ye.y)}return h.emplaceBack(l.x,l.y,l.z,d.x,d.y,Z,U,Y,H,k,p,y,b),h.length-1}function R3(h){k3(h)&&h.collisionPadding&&(h.top-=h.collisionPadding[1],h.bottom+=h.collisionPadding[3]);const l=h.bottom-h.top;return l>0?Math.max(10,l):null}function O1e(h,l,d,p){const y=h.compareText;if(l in y){const b=y[l];for(let w=b.length-1;w>=0;w--)if(p.dist(b[w])we&&(Ee(Le,qt,Je,it,Ft,Vt),Ee(qt,Ke,Ft,Vt,Pt,ft))}Ee(U,H,p,b,y,b),Ee(H,Z,y,b,y,w),Ee(Z,Y,y,w,p,w),Ee(Y,U,p,w,p,b),ne-=we,ce-=we,le+=we,ye+=we;const Ue=1/Math.max(le-ne,ye-ce);return{scale:Ue,x:ne*Ue,y:ce*Ue,x2:le*Ue,y2:ye*Ue,projection:l}}function t7(h,{x:l,y:d},p=0){return new Wt(((l-p)*h.scale-h.x)*mr,(d*h.scale-h.y)*mr)}const R1e=I(new Float32Array(16));class Vg{constructor(l){this.spec=l,this.name=l.name,this.wrap=!1,this.requiresDraping=!1,this.supportsWorldCopies=!1,this.supportsTerrain=!1,this.supportsFog=!1,this.supportsFreeCamera=!1,this.zAxisUnit="meters",this.isReprojectedInTileSpace=!0,this.unsupportedLayers=["custom"],this.center=[0,0],this.range=[3.5,7]}project(l,d){return{x:0,y:0,z:0}}unproject(l,d){return new f(0,0)}projectTilePoint(l,d,p){return{x:l,y:d,z:0}}locationPoint(l,d,p,y=!0){return l._coordinatePoint(l.locationCoordinate(d,p),y)}pixelsPerMeter(l,d){return q(1,l)*d}pixelSpaceConversion(l,d,p){return 1}farthestPixelDistance(l){return e7(l,l.pixelsPerMeter)}pointCoordinate(l,d,p,y){const b=l.horizonLineFromTop(!1),w=new Wt(d,Math.max(b,p));return l.rayIntersectionCoordinate(l.pointRayIntersection(w,y))}pointCoordinate3D(l,d,p){const y=new Wt(d,p);if(l.elevation)return l.elevation.pointCoordinate(y);{const b=this.pointCoordinate(l,y.x,y.y,0);return[b.x,b.y,b.z]}}isPointAboveHorizon(l,d){if(l.elevation&&l.elevation.visibleDemTiles.length)return!this.pointCoordinate3D(l,d.x,d.y);const p=l.horizonLineFromTop();return d.y0?d<-Hb+p&&(d=-Hb+p):d>Hb-p&&(d=Hb-p);const w=b/Math.pow(MA(d),y);let k=w*Math.sin(y*l),M=b-w*Math.cos(y*l);return k=.5*(k/Math.PI+.5),M=.5*(M/Math.PI+.5),{x:k,y:this.southernCenter?M:1-M,z:0}}unproject(l,d){l=(2*l-.5)*Math.PI,this.southernCenter&&(d=1-d),d=(2*(1-d)-.5)*Math.PI;const{n:p,f:y}=this,b=y-d,w=Math.sign(b),k=Math.sign(p)*Math.sqrt(l*l+b*b);let M=Math.atan2(l,Math.abs(b))*w;b*p<0&&(M-=Math.PI*Math.sign(l)*w);const F=ue(Bo(M/p)+this.center[0],-180,180),$=ue(Bo(2*Math.atan(Math.pow(y/k,1/p))-Hb),-re,re);return new f(F,this.southernCenter?-$:$)}}class r7 extends Vg{constructor(l){super(l),this.wrap=!0,this.supportsWorldCopies=!0,this.supportsTerrain=!0,this.supportsFog=!0,this.supportsFreeCamera=!0,this.isReprojectedInTileSpace=!1,this.unsupportedLayers=[],this.range=null}project(l,d){return{x:L(l),y:B(d),z:0}}unproject(l,d){const p=G(l),y=ee(d);return new f(p,y)}}const n7=Xn(re);class B1e extends Vg{project(l,d){const p=(d=Xn(d))*d,y=p*p;return{x:.5*((l=Xn(l))*(.8707-.131979*p+y*(y*(.003971*p-.001529*y)-.013791))/Math.PI+.5),y:1-.5*(d*(1.007226+p*(.015085+y*(.028874*p-.044475-.005916*y)))/Math.PI+1),z:0}}unproject(l,d){l=(2*l-.5)*Math.PI;let p=d=(2*(1-d)-1)*Math.PI,y=25,b=0,w=p*p;do{w=p*p;const F=w*w;b=(p*(1.007226+w*(.015085+F*(.028874*w-.044475-.005916*F)))-d)/(1.007226+w*(.045255+F*(.259866*w-.311325-.005916*11*F))),p=ue(p-b,-n7,n7)}while(Math.abs(b)>1e-6&&--y>0);w=p*p;const k=ue(Bo(l/(.8707+w*(w*(w*w*w*(.003971-.001529*w)-.013791)-.131979))),-180,180),M=Bo(p);return new f(k,M)}}const s7=Xn(re);class $1e extends Vg{project(l,d){d=Xn(d),l=Xn(l);const p=Math.cos(d),y=2/Math.PI,b=Math.acos(p*Math.cos(l/2)),w=Math.sin(b)/b,k=.5*(l*y+2*p*Math.sin(l/2)/w)||0,M=.5*(d+Math.sin(d)/w)||0;return{x:.5*(k/Math.PI+.5),y:1-.5*(M/Math.PI+1),z:0}}unproject(l,d){let p=l=(2*l-.5)*Math.PI,y=d=(2*(1-d)-1)*Math.PI,b=25;const w=1e-6;let k=0,M=0;do{const F=Math.cos(y),$=Math.sin(y),U=2*$*F,H=$*$,Z=F*F,Y=Math.cos(p/2),ne=Math.sin(p/2),ce=2*Y*ne,le=ne*ne,ye=1-Z*Y*Y,we=ye?1/ye:0,Ee=ye?Math.acos(F*Y)*Math.sqrt(1/ye):0,Ue=.5*(2*Ee*F*ne+2*p/Math.PI)-l,Le=.5*(Ee*$+y)-d,Ke=.5*we*(Z*le+Ee*F*Y*H)+1/Math.PI,Je=we*(ce*U/4-Ee*$*ne),it=.125*we*(U*ne-Ee*$*Z*ce),Pt=.5*we*(H*Y+Ee*le*F)+.5,ft=Je*it-Pt*Ke;k=(Le*Je-Ue*Pt)/ft,M=(Ue*it-Le*Ke)/ft,p=ue(p-k,-Math.PI,Math.PI),y=ue(y-M,-s7,s7)}while((Math.abs(k)>w||Math.abs(M)>w)&&--b>0);return new f(Bo(p),Bo(y))}}class i7 extends Vg{constructor(l){super(l),this.center=l.center||[0,0],this.parallels=l.parallels||[0,0],this.cosPhi=Math.max(.01,Math.cos(Xn(this.parallels[0]))),this.scale=1/(2*Math.max(Math.PI*this.cosPhi,1/this.cosPhi)),this.wrap=!0,this.supportsWorldCopies=!0}project(l,d){const{scale:p,cosPhi:y}=this;return{x:Xn(l)*y*p+.5,y:-Math.sin(Xn(d))/y*p+.5,z:0}}unproject(l,d){const{scale:p,cosPhi:y}=this,b=-(d-.5)/p,w=ue(Bo((l-.5)/p)/y,-180,180),k=Math.asin(ue(b*y,-1,1)),M=ue(Bo(k),-re,re);return new f(w,M)}}class U1e extends r7{constructor(l){super(l),this.requiresDraping=!0,this.supportsWorldCopies=!1,this.supportsFog=!0,this.zAxisUnit="pixels",this.unsupportedLayers=["debug"],this.range=[3,5]}projectTilePoint(l,d,p){const y=fN(l,d,p);return ut(y,y,nA(rd(p))),{x:y[0],y:y[1],z:y[2]}}locationPoint(l,d,p){const y=Dg(d.lat,d.lng),b=Oe([],y),w=p?l._centerAltitude+p:l.elevation?l.elevation.getAtPointOrZero(l.locationCoordinate(d),l._centerAltitude):l._centerAltitude;pt(y,y,b,q(1,0)*mr*w);const k=I(new Float64Array(16));return R(k,l.pixelMatrix,l.globeMatrix),ut(y,y,k),new Wt(y[0],y[1])}pixelsPerMeter(l,d){return q(1,0)*d}pixelSpaceConversion(l,d,p){const y=q(1,l)*d,b=fn(q(1,45)*d,y,p);return this.pixelsPerMeter(l,d)/b}createTileMatrix(l,d,p){const y=B4(rd(p.canonical));return R(new Float64Array(16),l.globeMatrix,y)}createInversionMatrix(l,d){const{center:p}=l,y=nA(rd(d));return K(y,y,Xn(p.lng)),V(y,y,Xn(p.lat)),W(y,y,[l._pixelsPerMercatorPixel,l._pixelsPerMercatorPixel,1]),Float32Array.from(y)}pointCoordinate(l,d,p,y){return Fg(l,d,p,!0)||new Ne(0,0)}pointCoordinate3D(l,d,p){const y=this.pointCoordinate(l,d,p,0);return[y.x,y.y,y.z]}isPointAboveHorizon(l,d){return!Fg(l,d.x,d.y,!1)}farthestPixelDistance(l){const d=function(y,b){const w=y.cameraToCenterDistance,k=y._centerAltitude*b,M=y._camera,F=y._camera.forward(),$=Se([],Ye([],F,-w),[0,0,k]),U=y.worldSize/(2*Math.PI),H=[0,0,-U],Z=y.width/y.height,Y=Math.tan(y.fovAboveCenter),ne=Ye([],M.up(),Y),ce=Ye([],M.right(),Y*Z),le=Oe([],Se([],Se([],F,ne),ce)),ye=[];let we;if(new Fr($,le).closestPointOnSphere(H,U,ye)){const Ee=Se([],ye,H),Ue=Kt([],Ee,$);we=Math.cos(y.fovAboveCenter)*ge(Ue)}else{const Ee=Kt([],$,H),Ue=Kt([],H,$);Oe(Ue,Ue);const Le=ge(Ee)-U;we=Math.sqrt(Le*(Le+2*U));const Ke=Math.acos(we/(U+Le))-Math.acos(Ie(F,Ue));we*=Math.cos(Ke)}return 1.01*we}(l,this.pixelsPerMeter(l.center.lat,l.worldSize)),p=zg(l.zoom);if(p>0){const y=e7(l,q(1,l.center.lat)*l.worldSize),b=l.worldSize/(2*Math.PI),w=Math.max(l.width,l.height)/l.worldSize*Math.PI;return fn(d,y+b*(1-Math.cos(w)),Math.pow(p,10))}return d}upVector(l,d,p){return fN(d,p,l,1)}upVectorScale(l){return{metersToTile:$d(rA(rd(l)))}}}function a7(h){const l=h.parallels,d=!!l&&Math.abs(l[0]+l[1])<.01;switch(h.name){case"mercator":return new r7(h);case"equirectangular":return new F1e(h);case"naturalEarth":return new B1e(h);case"equalEarth":return new L1e(h);case"winkelTripel":return new $1e(h);case"albers":return d?new i7(h):new D1e(h);case"lambertConformalConic":return d?new i7(h):new z1e(h);case"globe":return new U1e(h)}throw new Error(`Invalid projection name: ${h.name}`)}const V1e=ot.types,q1e=[{name:"a_fade_opacity",components:1,type:"Uint8",offset:0}];function VN(h,l,d,p,y,b,w,k,M,F,$,U,H){const Z=k?Math.min(cm,Math.round(k[0])):0,Y=k?Math.min(cm,Math.round(k[1])):0;h.emplaceBack(l,d,Math.round(32*p),Math.round(32*y),b,w,(Z<<1)+(M?1:0),0+(Y<<1),16*F,16*$,256*U,256*H)}function qN(h,l,d){h.emplaceBack(l,d)}function HN(h,l,d,p,y,b,w){h.emplaceBack(l,d,p,y,b,w)}const OA=(h,l,d,p)=>{for(let y=0;y0&&(this.iconTransitioningVertexBuffer=l.createVertexBuffer(this.iconTransitioningVertexArray,Qwe.members,!0)),this.globeExtVertexArray.length>0&&(this.globeExtVertexBuffer=l.createVertexBuffer(this.globeExtVertexArray,Kwe.members,!0)),!this.zOffsetVertexBuffer&&(this.zOffsetVertexArray.length>0||b)&&(this.zOffsetVertexBuffer=l.createVertexBuffer(this.zOffsetVertexArray,Ywe.members,!0)),!this.orientationVertexBuffer&&this.orientationVertexArray&&this.orientationVertexArray.length>0&&(this.orientationVertexBuffer=l.createVertexBuffer(this.orientationVertexArray,Xwe.members,!0)),this.opacityVertexBuffer.itemSize=1),(p||y)&&this.programConfigurations.upload(l))}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.dynamicLayoutVertexBuffer.destroy(),this.opacityVertexBuffer.destroy(),this.iconTransitioningVertexBuffer&&this.iconTransitioningVertexBuffer.destroy(),this.globeExtVertexBuffer&&this.globeExtVertexBuffer.destroy(),this.zOffsetVertexBuffer&&this.zOffsetVertexBuffer.destroy(),this.orientationVertexBuffer&&this.orientationVertexBuffer.destroy())}}Lr(D3,"SymbolBuffers");class L3{constructor(l,d,p){this.layoutVertexArray=new l,this.layoutAttributes=d,this.indexArray=new p,this.segments=new Hi,this.collisionVertexArray=new QS,this.collisionVertexArrayExt=new Gf}upload(l){this.layoutVertexBuffer=l.createVertexBuffer(this.layoutVertexArray,this.layoutAttributes),this.indexBuffer=l.createIndexBuffer(this.indexArray),this.collisionVertexBuffer=l.createVertexBuffer(this.collisionVertexArray,Jwe.members,!0),this.collisionVertexBufferExt=l.createVertexBuffer(this.collisionVertexArrayExt,e1e.members,!0)}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.collisionVertexBuffer.destroy(),this.collisionVertexBufferExt.destroy())}}Lr(L3,"CollisionBuffers");class RA{constructor(l){this.collisionBoxArray=l.collisionBoxArray,this.zoom=l.zoom,this.overscaling=l.overscaling,this.layers=l.layers,this.layerIds=this.layers.map(w=>w.fqid),this.index=l.index,this.pixelRatio=l.pixelRatio,this.sourceLayerIndex=l.sourceLayerIndex,this.hasPattern=!1,this.hasRTLText=!1,this.fullyClipped=!1,this.hasAnyIconTextFit=!1,this.sortKeyRanges=[],this.collisionCircleArray=[],this.placementInvProjMatrix=I([]),this.placementViewportMatrix=I([]);const d=this.layers[0]._unevaluatedLayout._values;this.worldview=l.worldview,this.localizable=l.localizable,this.textSizeData=$b(this.zoom,d["text-size"],this.worldview),this.iconSizeData=$b(this.zoom,d["icon-size"],this.worldview);const p=this.layers[0].layout,y=p.get("symbol-sort-key"),b=p.get("symbol-z-order");this.lut=l.lut,this.canOverlap=p.get("text-allow-overlap")||p.get("icon-allow-overlap")||p.get("text-ignore-placement")||p.get("icon-ignore-placement"),this.sortFeaturesByKey=b!=="viewport-y"&&y.constantOr(1)!==void 0,this.sortFeaturesByY=(b==="viewport-y"||b==="auto"&&!this.sortFeaturesByKey)&&this.canOverlap,this.writingModes=p.get("text-writing-mode").map(w=>Gc[w]),this.stateDependentLayerIds=this.layers.filter(w=>w.isStateDependent()).map(w=>w.id),this.sourceID=l.sourceID,this.projection=l.projection,this.hasAnyZOffset=!1,this.zOffsetSortDirty=!1,this.zOffsetBuffersNeedUpload=!1,this.elevationType="none",this.elevationStateComplete=!1,this.activeReplacements=[],this.replacementUpdateTime=0,this.hasAnySecondaryIcon=!1,this.hasAppearances=null,this.lastActiveApperance=null,this.featureToAppearanceIndex={}}hasAnyAppearanceProperty(l){const d=this.layers[0].getAppearances();return!(!d||d.length===0)&&d.some(p=>p.getProperty(l)!=null)}createArrays(){this.text=new D3(new ed(this.layers,{zoom:this.zoom,lut:this.lut},l=>l.startsWith("text")||l.startsWith("symbol"))),this.icon=new D3(new ed(this.layers,{zoom:this.zoom,lut:this.lut},l=>l.startsWith("icon")||l.startsWith("symbol"))),this.glyphOffsetArray=new jb,this.lineVertexArray=new XE,this.symbolInstances=new iN}calculateGlyphDependencies(l,d,p,y,b){for(const w of l){const k=w.codePointAt(0);if(k===void 0)break;if(d[k]=!0,y&&b&&k<=65535){const M=IN[w];M&&(d[M.charCodeAt(0)]=!0)}}}calculateEffectiveAppearanceIconSize(l,d,p,y,b,w){let k=1;const M=l.getUnevaluatedProperties()._values["icon-size"],F=$b(this.zoom,M,this.worldview),$=Ub(F,d);if(F.kind!=="constant"&&F.kind!=="camera"||(k=$.uSize),F.kind==="composite"){const{minZoom:U,maxZoom:H}=F,Z=M.possiblyEvaluate(new wi(U,{worldview:this.worldview}),y),Y=M.possiblyEvaluate(new wi(H,{worldview:this.worldview}),y),ne=Z.evaluate(p,{},y,b);k=ne+(Y.evaluate(p,{},y,b)-ne)*$.uSizeT}return F.kind==="source"&&(k=M.possiblyEvaluate(new wi(this.zoom,{worldview:this.worldview}),y).evaluate(p,{},y,b)),k*w}updateFootprints(l,d){}updateReplacement(l,d){if(d.updateTime===this.replacementUpdateTime)return!1;this.replacementUpdateTime=d.updateTime;const p=d.getReplacementRegionsForTile(l.toUnwrapped(),!0);return!cA(this.activeReplacements,p)&&(this.activeReplacements=p,!0)}getResolvedImageFromTokens(l){return typeof l=="string"?Ml.build(l):l}populate(l,d,p,y){const b=this.layers[0],w=b.layout,k=this.projection.name==="globe",M=w.get("text-font"),F=w.get("text-field"),$=w.get("icon-image"),[U,H]=w.get("icon-size-scale-range"),Z=ue(d.scaleFactor||1,U,H),Y=(F.value.kind!=="constant"||F.value.value instanceof Il&&!F.value.value.isEmpty()||F.value.value.toString().length>0)&&(M.value.kind!=="constant"||M.value.value.length>0),ne=$.value.kind!=="constant"||!!$.value.value||Object.keys($.parameters).length>0,ce=this.hasAnyAppearanceProperty("icon-image"),le=w.get("symbol-sort-key");if(this.features=[],this.appearanceFeatureData=[],!Y&&!ne&&!ce)return;const ye=d.iconDependencies,we=d.glyphDependencies,Ee=d.availableImages,Ue=new wi(this.zoom,{worldview:this.worldview,activeFloors:d.activeFloors}),Le=Ke=>{const Je=Ke.id.toString();ye.has(Je)?ye.get(Je).push(Ke):ye.set(Je,[Ke])};for(const Ke of l){const{feature:Je,id:it,index:Pt,sourceLayerIndex:ft}=Ke,Ft=b._featureFilter.needGeometry,Vt=ht(Je,Ft);if(!b._featureFilter.filter(Ue,Vt,p))continue;if(Ft||(Vt.geometry=Qe(Je,p,y)),k&&Je.type!==1&&p.z<=5){const Jt=Vt.geometry,gr=.98078528056,cr=(Gr,Er)=>Ie(fN(Gr.x,Gr.y,p,1),fN(Er.x,Er.y,p,1)){if(!Jt.getProperty("icon-image"))return;const gr=this.getCombinedIconPrimary(Jt,nr,Vt,p,Ee,Rt,Z);gr&&Le(gr)}),qt){const Jt=M.evaluate(Vt,{},p).join(","),gr=w.get("text-rotation-alignment")==="map"&&w.get("symbol-placement")!=="point";this.allowVerticalPlacement=this.writingModes&&this.writingModes.indexOf(Gc.vertical)>=0;for(const cr of qt.sections)if(cr.image){const Gr=cr.image.getPrimary().scaleSelf(this.pixelRatio),Er=Gr.id.toString(),Or=ye.get(Er)||[];Or.push(Gr),ye.set(Er,Or)}else{const Gr=nv(qt.toString()),Er=cr.fontStack||Jt,Or=we[Er]=we[Er]||{};this.calculateGlyphDependencies(cr.text,Or,gr,this.allowVerticalPlacement,Gr)}}}if(w.get("symbol-placement")==="line"&&(this.features=function(Ke){const Je={},it={},Pt=[];let ft=0;function Ft(nr){Pt.push(Ke[nr]),ft++}function Vt(nr,Yt,Xt){const Rt=it[nr];return delete it[nr],it[Yt]=Rt,Pt[Rt].geometry[0].pop(),Pt[Rt].geometry[0]=Pt[Rt].geometry[0].concat(Xt[0]),Rt}function qt(nr,Yt,Xt){const Rt=Je[Yt];return delete Je[Yt],Je[nr]=Rt,Pt[Rt].geometry[0].shift(),Pt[Rt].geometry[0]=Xt[0].concat(Pt[Rt].geometry[0]),Rt}function er(nr,Yt,Xt){const Rt=Xt?Yt[0][Yt[0].length-1]:Yt[0][0];return`${nr}:${Rt.x}:${Rt.y}`}for(let nr=0;nrnr.geometry)}(this.features)),w.get("symbol-elevation-reference")==="hd-road-markup"){if(this.elevationType="road",d.elevationFeatures){!this.elevationFeatures&&d.elevationFeatures.length>0&&(this.elevationFeatures=[],this.elevationFeatureIdToIndex=new Map);for(const Ke of d.elevationFeatures)this.elevationFeatureIdToIndex.set(Ke.id,this.elevationFeatures.length),this.elevationFeatures.push(Ke)}}else w.get("symbol-z-elevate")&&(this.elevationType="offset");this.elevationType!=="none"&&(this.zOffsetBuffersNeedUpload=!0),this.sortFeaturesByKey&&this.features.sort((Ke,Je)=>Ke.sortKey-Je.sortKey)}getCombinedIconPrimary(l,d,p,y,b,w,k){let M,F;const $=l.getUnevaluatedProperties();if($._values["icon-image"].value!==void 0){const U=d.getAppearanceValueAndResolveTokens(l,"icon-image",p,y,b);M=this.getResolvedImageFromTokens(U)}else{const U=d.getValueAndResolveTokens("icon-image",p,y,b);M=this.getResolvedImageFromTokens(U)}if(M){const U=$._values["icon-size"]||d._unevaluatedLayout._values["icon-size"];F=DN(M,$b(this.zoom,U,this.worldview),U,y,this.zoom,w,this.pixelRatio,k,this.worldview).iconPrimary}return F}updateAppearanceBasedIconTextures(l,d,p,y){if(!this.appearanceFeatureData||!this.icon.layoutVertexArray||this.icon.layoutVertexArray.length===0)return!1;const b=this.layers[0];let w=!1,k=0;const M=b.layout,[F,$]=M.get("icon-size-scale-range"),U=ue(1,F,$);for(let H=0;H=0){const ce=ne.id,le=d&&ce!==void 0?d[String(ce)]:void 0,ye={type:"Point",id:ne.id,properties:ne.properties,geometry:[]},we=this.layers[0].appearances&&this.layers[0].appearances.find(Ee=>Ee.isActive({globals:y,feature:ye,canonical:l,featureState:le}));if(ne.activeAppearance===we){k+=Z.numIconVertices;continue}if(we){ne.activeAppearance=we;const Ee=this.getCombinedIconPrimary(we,b,ye,l,p,{sortKey:void 0,text:void 0,icon:null,index:Z.featureIndex,sourceLayerIndex:Z.featureIndex,geometry:[],properties:ne.properties,type:"Point",id:ne.id},U);if(!Ee)continue;const Ue=Ee.toString(),Le=this.iconAtlasPositions&&this.iconAtlasPositions.get(Ue);if(Le){const Ke=b.getAppearanceValueAndResolveTokens(we,"icon-offset",ye,l,p),Je=Ke&&Array.isArray(Ke)?Ke:[0,0];let it=NA(Le,void 0,Je,b.layout.get("icon-anchor").evaluate(ye,{},l));const Pt=b.getAppearanceValueAndResolveTokens(we,"icon-rotate",ye,l,p),ft=typeof Pt=="number"?Pt:0,Ft=Le.sdf,Vt=b.layout.get("icon-text-fit").constantOr("none");Vt!=="none"&&ne.textShaping&&ne.iconTextFitPadding&&ne.fontScale&&(it=T3(it,ne.textShaping,Vt,ne.iconTextFitPadding,Je,ne.fontScale));const qt=this.calculateEffectiveAppearanceIconSize(we,y.zoom,ye,l,p,U),er=0,nr=1+(Math.min(cm,Math.round(qt*Uh))<<1),Yt=I3(it,ft,Ft,Vt!=="none",U);ne.isUsingAppearanceVertexData||(ne.isUsingAppearanceVertexData=!0,ne.layoutBasedVertexData=this.icon.getIconVertexData(k,Z.numIconVertices));for(let Rt=0;Rt0&&(this.icon.updateIconVertexData(k,0,0,0,0,0,0,0,0,0,0,0,0),this.icon.updateIconVertexData(k+1,0,0,0,0,0,0,0,0,0,0,0,0),this.icon.updateIconVertexData(k+2,0,0,0,0,0,0,0,0,0,0,0,0),this.icon.updateIconVertexData(k+3,0,0,0,0,0,0,0,0,0,0,0,0),w=!0),k+=Z.numIconVertices,ne.activeAppearance=null;else if(ne.isUsingAppearanceVertexData){const Ue=ne.layoutBasedVertexData.length/12;for(let Le=0;Le0||H>0,ce=Z>0,le=this.elevationFeatures[M.elevationFeatureIndex];if(le){const ye=new Wt(M.tileAnchorX,M.tileAnchorY),we=.075+le.pointElevation(ye);M.zOffset!==we&&(d=!0,M.zOffset=we),we!==0&&(this.hasAnyZOffset=!0);const Ee=le.computeSlopeNormal(ye,y),Ue=Xo(pr(),ke(0,0,1),Ee);$t(F,F,Ue),$t($,$,Ue),F[2]*=p,$[2]*=p,F[0]===1&&F[1]===0&&F[2]===0&&$[0]===0&&$[1]===1&&$[2]===0||(b=b||ne,w=w||ce)}if(ne&&(OA(this.text.orientationVertexArray,U,F,$),OA(this.text.orientationVertexArray,H,F,$)),ce){const{placedIconSymbolIndex:ye,verticalPlacedIconSymbolIndex:we}=M;ye>=0&&OA(this.icon.orientationVertexArray,Z,F,$),we>=0&&OA(this.icon.orientationVertexArray,Y,F,$)}}b||(this.text.orientationVertexArray=void 0),w||(this.icon.orientationVertexArray=void 0),d&&(this.zOffsetBuffersNeedUpload=!0,this.zOffsetSortDirty=!0)}updateZOffset(){const l=(b,w,k)=>{p+=w,p>b.length&&b.resize(p);for(let M=-w;M<0;M++)b.emplace(M+p,k)},d=(b,w,k)=>{y+=w,y>b.length&&b.resize(y);for(let M=-w;M<0;M++)b.emplace(M+y,k)};if(!this.zOffsetBuffersNeedUpload)return;this.zOffsetBuffersNeedUpload=!1;let p=0,y=0;for(let b=0;b0;if((k>0||M>0)&&(l(this.text.zOffsetVertexArray,k,$),l(this.text.zOffsetVertexArray,M,$)),U){const{placedIconSymbolIndex:H,verticalPlacedIconSymbolIndex:Z}=w;H>=0&&d(this.icon.zOffsetVertexArray,F,$),Z>=0&&d(this.icon.zOffsetVertexArray,w.numVerticalIconVertices,$)}}this.text.zOffsetVertexBuffer&&this.text.zOffsetVertexBuffer.updateData(this.text.zOffsetVertexArray),this.icon.zOffsetVertexBuffer&&this.icon.zOffsetVertexBuffer.updateData(this.icon.zOffsetVertexArray)}isEmpty(){return this.symbolInstances.length===0&&!this.hasRTLText}uploadPending(){return!this.uploaded||this.text.programConfigurations.needsUpload||this.icon.programConfigurations.needsUpload}upload(l,d,p,y,b){!this.uploaded&&this.hasDebugData()&&(this.textCollisionBox.upload(l),this.iconCollisionBox.upload(l)),this.text.upload(l,this.sortFeaturesByY,!this.uploaded,this.text.programConfigurations.needsUpload,this.zOffsetBuffersNeedUpload,!1),this.hasAppearances===null&&(this.hasAppearances=this.layers.some(w=>w.appearances&&w.appearances.length>0)),this.icon.upload(l,this.sortFeaturesByY,!this.uploaded,this.icon.programConfigurations.needsUpload,this.zOffsetBuffersNeedUpload,this.hasAppearances),this.uploaded=!0}updateAppearances(l,d,p,y){return!!(l&&d&&p)&&!(!this.icon.layoutVertexArray||this.icon.layoutVertexArray.length===0)&&!!this.icon.layoutVertexArray.arrayBuffer&&void(this.updateAppearanceBasedIconTextures(l,d,p,y)&&this.icon.layoutVertexBuffer&&this.icon.layoutVertexArray.arrayBuffer!==null&&this.icon.layoutVertexArray.length===this.icon.layoutVertexBuffer.length&&this.icon.layoutVertexBuffer.updateData(this.icon.layoutVertexArray))}destroyDebugData(){this.textCollisionBox.destroy(),this.iconCollisionBox.destroy()}getProjection(){return this.projectionInstance||(this.projectionInstance=a7(this.projection)),this.projectionInstance}destroy(){this.text.destroy(),this.icon.destroy(),this.hasDebugData()&&this.destroyDebugData()}addToLineVertexArray(l,d){const p=this.lineVertexArray.length;if(l.segment!==void 0)for(const{x:y,y:b}of d)this.lineVertexArray.emplaceBack(y,b);return{lineStartIndex:p,lineLength:this.lineVertexArray.length-p}}addSymbols(l,d,p,y,b,w,k,M,F,$,U,H,Z,Y,ne,ce,le,ye){const we=l.indexArray,Ee=l.layoutVertexArray,Ue=l.globeExtVertexArray,Le=l.segments.prepareSegment(4*ye,Ee,we,this.canOverlap?w.sortKey:void 0),Ke=this.glyphOffsetArray.length,Je=Le.vertexLength,it=this.allowVerticalPlacement&&k===Gc.vertical?Math.PI/2:0,Pt=w.text&&w.text.sections;for(let Vt=0;Vt=0?d.rightJustifiedTextSymbolIndex:d.centerJustifiedTextSymbolIndex>=0?d.centerJustifiedTextSymbolIndex:d.leftJustifiedTextSymbolIndex>=0?d.leftJustifiedTextSymbolIndex:d.verticalPlacedTextSymbolIndex>=0?d.verticalPlacedTextSymbolIndex:y),w=E3(this.textSizeData,l,b)/uo;return this.tilePixelRatio*w}getSymbolInstanceIconSize(l,d,p){const y=this.icon.placedSymbolArray.get(p),b=E3(this.iconSizeData,l,y);return this.tilePixelRatio*b}_commitDebugCollisionVertexUpdate(l,d,p,y){l.emplaceBack(d,-p,-p,y),l.emplaceBack(d,p,-p,y),l.emplaceBack(d,p,p,y),l.emplaceBack(d,-p,p,y)}_updateTextDebugCollisionBoxes(l,d,p,y,b,w,k){for(let M=y;M0}hasIconData(){return this.icon.segments.get().length>0}hasDebugData(){return this.textCollisionBox&&this.iconCollisionBox}hasTextCollisionBoxData(){return this.hasDebugData()&&this.textCollisionBox.segments.get().length>0}hasIconCollisionBoxData(){return this.hasDebugData()&&this.iconCollisionBox.segments.get().length>0}hasIconTextFit(){return this.hasAnyIconTextFit}addIndicesForPlacedSymbol(l,d){const p=l.placedSymbolArray.get(d),y=p.vertexStartIndex+4*p.numGlyphs;for(let b=p.vertexStartIndex;by[k]-y[M]||b[M]-b[k]),w}getSortedIndexesByZOffset(){if(!this.zOffsetSortDirty)return this.symbolInstanceIndexesSortedZOffset;if(!this.symbolInstanceIndexesSortedZOffset){this.symbolInstanceIndexesSortedZOffset=[];for(let l=0;lthis.symbolInstances.get(d).zOffset-this.symbolInstances.get(l).zOffset)}addToSortKeyRanges(l,d){const p=this.sortKeyRanges[this.sortKeyRanges.length-1];p&&p.sortKey===d?p.symbolInstanceEnd=l+1:this.sortKeyRanges.push({sortKey:d,symbolInstanceStart:l,symbolInstanceEnd:l+1})}sortFeatures(l){if(this.sortFeaturesByY&&this.sortedAngle!==l&&!(this.text.segments.get().length>1||this.icon.segments.get().length>1)){this.symbolInstanceIndexes=this.getSortedSymbolIndexes(l),this.sortedAngle=l,this.text.indexArray.clear(),this.icon.indexArray.clear(),this.featureSortOrder=[];for(const d of this.symbolInstanceIndexes){const p=this.symbolInstances.get(d);this.featureSortOrder.push(p.featureIndex);const{rightJustifiedTextSymbolIndex:y,centerJustifiedTextSymbolIndex:b,leftJustifiedTextSymbolIndex:w,verticalPlacedTextSymbolIndex:k,placedIconSymbolIndex:M,verticalPlacedIconSymbolIndex:F}=p;y>=0&&this.addIndicesForPlacedSymbol(this.text,y),b>=0&&b!==y&&this.addIndicesForPlacedSymbol(this.text,b),w>=0&&w!==b&&w!==y&&this.addIndicesForPlacedSymbol(this.text,w),k>=0&&this.addIndicesForPlacedSymbol(this.text,k),M>=0&&this.addIndicesForPlacedSymbol(this.icon,M),F>=0&&this.addIndicesForPlacedSymbol(this.icon,F)}this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray)}}getElevationFeatureForText(l){const d=this.symbolInstances.get(this.text.symbolInstanceIndices[l]).elevationFeatureIndex;let p;return this.elevationFeatures&&dp in h?String(h[p]):"")}let l7,c7,F3;Lr(RA,"SymbolBucket",{omit:["layers","collisionBoxArray","compareText","features"]}),RA.addDynamicAttributes=Wb;class u7{constructor(l){this.type=l.property.overrides?l.property.overrides.runtimeType:Zu,this.defaultValue=l}evaluate(l){if(l.formattedSection){const d=this.defaultValue.property.overrides;if(d&&d.hasOverride(l.formattedSection))return d.getOverride(l.formattedSection)}return l.feature&&l.featureState?this.defaultValue.evaluate(l.feature,l.featureState):this.defaultValue.property.specification.default}eachChild(l){this.defaultValue.isConstant()||l(this.defaultValue.value._styleExpression.expression)}outputDefined(){return!1}serialize(){return null}}Lr(u7,"FormatSectionOverride",{omit:["defaultValue"]});const z3=()=>F3||(F3={layout:l7||(l7=new ta({"symbol-placement":new hr(yt.layout_symbol["symbol-placement"]),"symbol-spacing":new hr(yt.layout_symbol["symbol-spacing"]),"symbol-avoid-edges":new hr(yt.layout_symbol["symbol-avoid-edges"]),"symbol-sort-key":new br(yt.layout_symbol["symbol-sort-key"]),"symbol-z-order":new hr(yt.layout_symbol["symbol-z-order"]),"symbol-z-elevate":new hr(yt.layout_symbol["symbol-z-elevate"]),"symbol-elevation-reference":new hr(yt.layout_symbol["symbol-elevation-reference"]),"icon-allow-overlap":new hr(yt.layout_symbol["icon-allow-overlap"]),"icon-ignore-placement":new hr(yt.layout_symbol["icon-ignore-placement"]),"icon-optional":new hr(yt.layout_symbol["icon-optional"]),"icon-rotation-alignment":new hr(yt.layout_symbol["icon-rotation-alignment"]),"icon-size":new br(yt.layout_symbol["icon-size"]),"icon-size-scale-range":new hr(yt.layout_symbol["icon-size-scale-range"]),"icon-text-fit":new br(yt.layout_symbol["icon-text-fit"]),"icon-text-fit-padding":new br(yt.layout_symbol["icon-text-fit-padding"]),"icon-image":new br(yt.layout_symbol["icon-image"]),"icon-image-use-theme":new hr({type:"string",default:"default","property-type":"data-constant"}),"icon-rotate":new br(yt.layout_symbol["icon-rotate"]),"icon-padding":new hr(yt.layout_symbol["icon-padding"]),"icon-keep-upright":new hr(yt.layout_symbol["icon-keep-upright"]),"icon-offset":new br(yt.layout_symbol["icon-offset"]),"icon-anchor":new br(yt.layout_symbol["icon-anchor"]),"icon-pitch-alignment":new hr(yt.layout_symbol["icon-pitch-alignment"]),"text-pitch-alignment":new hr(yt.layout_symbol["text-pitch-alignment"]),"text-rotation-alignment":new hr(yt.layout_symbol["text-rotation-alignment"]),"text-field":new br(yt.layout_symbol["text-field"]),"text-font":new br(yt.layout_symbol["text-font"]),"text-size":new br(yt.layout_symbol["text-size"]),"text-size-scale-range":new hr(yt.layout_symbol["text-size-scale-range"]),"text-max-width":new br(yt.layout_symbol["text-max-width"]),"text-line-height":new br(yt.layout_symbol["text-line-height"]),"text-letter-spacing":new br(yt.layout_symbol["text-letter-spacing"]),"text-justify":new br(yt.layout_symbol["text-justify"]),"text-radial-offset":new br(yt.layout_symbol["text-radial-offset"]),"text-variable-anchor":new hr(yt.layout_symbol["text-variable-anchor"]),"text-anchor":new br(yt.layout_symbol["text-anchor"]),"text-max-angle":new hr(yt.layout_symbol["text-max-angle"]),"text-writing-mode":new hr(yt.layout_symbol["text-writing-mode"]),"text-rotate":new br(yt.layout_symbol["text-rotate"]),"text-padding":new hr(yt.layout_symbol["text-padding"]),"text-keep-upright":new hr(yt.layout_symbol["text-keep-upright"]),"text-transform":new br(yt.layout_symbol["text-transform"]),"text-offset":new br(yt.layout_symbol["text-offset"]),"text-allow-overlap":new hr(yt.layout_symbol["text-allow-overlap"]),"text-ignore-placement":new hr(yt.layout_symbol["text-ignore-placement"]),"text-optional":new hr(yt.layout_symbol["text-optional"]),visibility:new hr(yt.layout_symbol.visibility)})),paint:c7||(c7=new ta({"icon-opacity":new br(yt.paint_symbol["icon-opacity"]),"icon-occlusion-opacity":new br(yt.paint_symbol["icon-occlusion-opacity"]),"icon-emissive-strength":new br(yt.paint_symbol["icon-emissive-strength"]),"text-emissive-strength":new br(yt.paint_symbol["text-emissive-strength"]),"icon-color":new br(yt.paint_symbol["icon-color"]),"icon-halo-color":new br(yt.paint_symbol["icon-halo-color"]),"icon-halo-width":new br(yt.paint_symbol["icon-halo-width"]),"icon-halo-blur":new br(yt.paint_symbol["icon-halo-blur"]),"icon-translate":new hr(yt.paint_symbol["icon-translate"]),"icon-translate-anchor":new hr(yt.paint_symbol["icon-translate-anchor"]),"icon-image-cross-fade":new hr(yt.paint_symbol["icon-image-cross-fade"]),"text-opacity":new br(yt.paint_symbol["text-opacity"]),"text-occlusion-opacity":new br(yt.paint_symbol["text-occlusion-opacity"]),"text-color":new br(yt.paint_symbol["text-color"],{runtimeType:sc,getOverride:h=>h.textColor,hasOverride:h=>!!h.textColor}),"text-halo-color":new br(yt.paint_symbol["text-halo-color"]),"text-halo-width":new br(yt.paint_symbol["text-halo-width"]),"text-halo-blur":new br(yt.paint_symbol["text-halo-blur"]),"text-translate":new hr(yt.paint_symbol["text-translate"]),"text-translate-anchor":new hr(yt.paint_symbol["text-translate-anchor"]),"icon-color-saturation":new hr(yt.paint_symbol["icon-color-saturation"]),"icon-color-contrast":new hr(yt.paint_symbol["icon-color-contrast"]),"icon-color-brightness-min":new hr(yt.paint_symbol["icon-color-brightness-min"]),"icon-color-brightness-max":new hr(yt.paint_symbol["icon-color-brightness-max"]),"symbol-z-offset":new br(yt.paint_symbol["symbol-z-offset"]),"icon-color-use-theme":new br({type:"string",default:"default","property-type":"data-driven"}),"icon-halo-color-use-theme":new br({type:"string",default:"default","property-type":"data-driven"}),"text-color-use-theme":new br({type:"string",default:"default","property-type":"data-driven"}),"text-halo-color-use-theme":new br({type:"string",default:"default","property-type":"data-driven"})}))},F3);class DA extends Dl{constructor(l,d,p,y){super(l,z3(),d,p,y,l.layout?l.layout["icon-image-use-theme"]:null),this._colorAdjustmentMatrix=I([]),this.hasOcclusionOpacityProperties=l.paint!==void 0&&("icon-occlusion-opacity"in l.paint||"text-occlusion-opacity"in l.paint)}_handleSpecialPaintPropertyUpdate(l){l!=="icon-occlusion-opacity"&&l!=="text-occlusion-opacity"||(this.hasOcclusionOpacityProperties=!0)}recalculate(l,d){super.recalculate(l,d),this.appearances&&this.appearances.forEach(y=>{y.recalculate(l,d,this.iconImageUseTheme)}),this.layout.get("icon-rotation-alignment")==="auto"&&(this.layout._values["icon-rotation-alignment"]=this.layout.get("symbol-placement")!=="point"?"map":"viewport"),this.layout.get("text-rotation-alignment")==="auto"&&(this.layout._values["text-rotation-alignment"]=this.layout.get("symbol-placement")!=="point"?"map":"viewport"),this.layout.get("text-pitch-alignment")==="auto"&&(this.layout._values["text-pitch-alignment"]=this.layout.get("text-rotation-alignment")),this.layout.get("icon-pitch-alignment")==="auto"&&(this.layout._values["icon-pitch-alignment"]=this.layout.get("icon-rotation-alignment"));const p=this.layout.get("text-writing-mode");if(p){const y=[];for(const b of p)y.indexOf(b)<0&&y.push(b);this.layout._values["text-writing-mode"]=y}else this.layout._values["text-writing-mode"]=this.layout.get("symbol-placement")==="point"?["horizontal"]:["horizontal","vertical"];this._setPaintOverrides()}getColorAdjustmentMatrix(l,d,p,y){return this._saturation===l&&this._contrast===d&&this._brightnessMin===p&&this._brightnessMax===y||(this._colorAdjustmentMatrix=function(b,w,k,M){b=Xi(b),w=_s(w);const F=P(),$=b/3,U=1-2*$,H=[U,$,$,0,$,U,$,0,$,$,U,0,0,0,0,1],Z=.5-.5*w,Y=M-k;return R(F,[Y,0,0,0,0,Y,0,0,0,0,Y,0,k,k,k,1],[w,0,0,0,0,w,0,0,0,0,w,0,Z,Z,Z,1]),R(F,F,H),F}(l,d,p,y),this._saturation=l,this._contrast=d,this._brightnessMin=p,this._brightnessMax=y),this._colorAdjustmentMatrix}getValueAndResolveTokens(l,d,p,y){const b=this.layout.get(l).evaluate(d,{},p,y),w=this._unevaluatedLayout._values[l];return w.isDataDriven()||tv(w.value)||!b?b:o7(d.properties,b)}getAppearanceValueAndResolveTokens(l,d,p,y,b){const w=l.getProperty(d);if(!w)return;const k=w.evaluate(p,{},y,b),M=l.getUnevaluatedProperties()._values[d];return M.isDataDriven()||tv(M.value)||!k||typeof k!="string"?k:o7(p.properties,k)}createBucket(l){return new RA(l)}queryRadius(){return 0}queryIntersectsFeature(){return!1}_setPaintOverrides(){for(const l of z3().paint.overridableProperties){if(!DA.hasPaintOverride(this.layout,l))continue;const d=this.paint.get(l),p=new u7(d),y=new J0(p,d.property.specification,this.scope,this.options,this.layout.get("icon-image-use-theme"));let b=null;b=d.value.kind==="constant"||d.value.kind==="source"?new kg("source",y):new Yp("composite",y,d.value.zoomStops,d.value.interpolationType),this.paint._values[l]=new Qp(d.property,b,d.parameters)}}_handleOverridablePaintPropertyUpdate(l,d,p){return!(!this.layout||d.isDataDriven()||p.isDataDriven())&&DA.hasPaintOverride(this.layout,l)}static hasPaintOverride(l,d){const p=l.get("text-field"),y=z3().paint.properties[d];let b=!1;const w=k=>{for(const M of k)if(y.overrides&&y.overrides.hasOverride(M))return void(b=!0)};if(p.value.kind==="constant"&&p.value.value instanceof Il)w(p.value.value.sections);else if(p.value.kind==="source"){const k=F=>{b||(F instanceof Ch&&co(F.value)===Bx?w(F.value.sections):F instanceof Md?w(F.sections):F.eachChild(k))},M=p.value;M._styleExpression&&k(M._styleExpression.expression)}return b}getProgramIds(){return["symbol"]}getDefaultProgramParams(l,d,p){return{config:new Zf(this,{zoom:d,lut:p}),overrideFog:!1}}hasElevation(){return this.layout&&this.layout.get("symbol-elevation-reference")==="hd-road-markup"}}let d7,h7,f7,p7;var B3=ts([{name:"a_pos",type:"Int16",components:2},{name:"a_texture_pos",type:"Int16",components:2}]);function LA(h,l,d,p,y,b,w,k){const M=[h,l,1,d,p,1,y,b,1],F=[w,k,1],$=N([],M),[U,H,Z]=jt(F,F,$);return C(M,M,[U,0,0,0,H,0,0,0,Z])}function m7(h,l,d,p,y,b,w,k){const M=function(F,$,U,H,Z,Y,ne,ce){const le=LA(0,0,1,0,1,1,0,1),ye=LA(F,$,U,H,Z,Y,ne,ce);return C(ye,ye,N([],le))}(h,l,d,p,y,b,w,k);return[M[2]/M[8]/mr,M[5]/M[8]/mr]}function FA(h){return[h[0],Math.min(Math.max(h[1],-re),re)]}class g7 extends qp{constructor(l,d,p,y){super(),this.id=l,this.dispatcher=p,this.coordinates=d.coordinates,this.type="image",this.minzoom=0,this.maxzoom=22,this.tileSize=512,this.tiles={},this._loaded=!1,this.onNorthPole=!1,this.onSouthPole=!1,this.setEventedParent(y),this.options=d,this._dirty=!1}load(l,d){if(this._loaded=d||!1,this.fire(new Pd("dataloading",{dataType:"source"})),this.url=this.options.url,!this.url)return l&&(this.coordinates=l),this._loaded=!0,void this._finishLoading();this._imageRequest=_0(this.map._requestManager.transformRequest(this.url,Mx.Image),(p,y)=>{this._imageRequest=null,this._loaded=!0,p?this.fire(new Lx(p)):y&&(this.image=y instanceof HTMLImageElement?lo.getImageData(y):y,this._dirty=!0,this.width=this.image.width,this.height=this.image.height,l&&(this.coordinates=l),this._finishLoading())})}loaded(){return this._loaded}updateImage(l){return l.url?(this._imageRequest&&l.url!==this.options.url&&(this._imageRequest.cancel(),this._imageRequest=null),this.options.url=l.url,this.load(l.coordinates,this._loaded),this):this}setTexture(l){if(!(l.handle instanceof WebGLTexture))throw new Error("The provided handle is not a WebGLTexture instance");return this.texture=new EN(this.map.painter.context,l.handle),this.width=l.dimensions[0],this.height=l.dimensions[1],this._dirty=!1,this._loaded=!0,this._finishLoading(),this}_finishLoading(){this.map&&(this.setCoordinates(this.coordinates),this.fire(new Pd("data",{dataType:"source",sourceDataType:"metadata"})))}onAdd(l){this.map=l,this.load()}onRemove(l){this._imageRequest&&(this._imageRequest.cancel(),this._imageRequest=null),!this.texture||this.texture instanceof EN||this.texture.destroy(),this.boundsBuffer&&(this.boundsBuffer.destroy(),this.elevatedGlobeVertexBuffer&&this.elevatedGlobeVertexBuffer.destroy(),this.elevatedGlobeIndexBuffer&&this.elevatedGlobeIndexBuffer.destroy())}setCoordinates(l){if(this.coordinates=l,this._boundsArray=void 0,this._unsupportedCoords=!1,!l.length)return this;this.onNorthPole=!1,this.onSouthPole=!1;let d=l[0][1],p=l[0][1];for(const b of l)b[1]>p&&(p=b[1]),b[1]re?this.onNorthPole=!0:y<-re&&(this.onSouthPole=!0),!this.onNorthPole&&!this.onSouthPole){const b=l.map(Ne.fromLngLat);this.tileID=function(w){let k=1/0,M=1/0,F=-1/0,$=-1/0;for(const ne of w)k=Math.min(k,ne.x),M=Math.min(M,ne.y),F=Math.max(F,ne.x),$=Math.max($,ne.y);const U=Math.max(F-k,$-M),H=Math.max(0,Math.floor(-Math.log2(U))),Z=Math.pow(2,H);let Y=Math.floor((k+F)/2*Z);return Y>1&&(Y-=1),new ui(H,Y,Math.floor((M+$)/2*Z))}(b),this.minzoom=this.maxzoom=this.tileID.z}return this.fire(new Pd("data",{dataType:"source",sourceDataType:"content"})),this}_clear(){!this.texture||this.texture instanceof EN||(this.texture.destroy(),this._dirty=!0),this.texture=null,this._boundsArray=void 0,this._unsupportedCoords=!1}_prepareData(l){for(const le in this.tiles){const ye=this.tiles[le];ye.state!=="loaded"&&(ye.state="loaded",ye.texture=this.texture)}if(this._boundsArray||this.onNorthPole||this.onSouthPole||this._unsupportedCoords)return;const d=FN(new ui(0,0,0),this.map.transform.projection),p=[d.projection.project(this.coordinates[0][0],this.coordinates[0][1]),d.projection.project(this.coordinates[1][0],this.coordinates[1][1]),d.projection.project(this.coordinates[2][0],this.coordinates[2][1]),d.projection.project(this.coordinates[3][0],this.coordinates[3][1])];if(!function(le){const ye=le[1].x-le[0].x,we=le[1].y-le[0].y,Ee=le[2].x-le[1].x,Ue=le[2].y-le[1].y,Le=le[3].x-le[2].x,Ke=le[3].y-le[2].y,Je=le[0].x-le[3].x,it=le[0].y-le[3].y,Pt=ye*Ue-Ee*we,ft=Ee*Ke-Le*Ue,Ft=Le*it-Je*Ke,Vt=Je*we-ye*it;return Pt>0&&ft>0&&Ft>0&&Vt>0||Pt<0&&ft<0&&Ft<0&&Vt<0}(p))return console.warn("Image source coordinates are defining non-convex area in the Mercator projection"),void(this._unsupportedCoords=!0);const y=FN(this.tileID,this.map.transform.projection),[b,w,k,M]=this.coordinates.map(le=>{const ye=y.projection.project(le[0],le[1]);return t7(y,ye)._round()});this.perspectiveTransform=m7(b.x,b.y,w.x,w.y,k.x,k.y,M.x,M.y);const F=this._boundsArray=new Pg;F.emplaceBack(b.x,b.y,0,0),F.emplaceBack(w.x,w.y,mr,0),F.emplaceBack(M.x,M.y,0,mr),F.emplaceBack(k.x,k.y,mr,mr),this.boundsBuffer&&(this.boundsBuffer.destroy(),this.elevatedGlobeVertexBuffer&&this.elevatedGlobeVertexBuffer.destroy(),this.elevatedGlobeIndexBuffer&&this.elevatedGlobeIndexBuffer.destroy()),this.boundsBuffer=l.createVertexBuffer(F,B3.members),this.boundsSegments=Hi.simpleSegment(0,0,4,2);const $=[],U=[FA((H=this.coordinates)[0]),FA(H[1]),FA(H[2]),FA(H[3])];var H;const[Z,Y,ne,ce]=function(le){let ye=le[0][0],we=ye,Ee=le[0][1],Ue=Ee;for(let Le=1;Lewe&&(we=le[Le][0]),le[Le][1]Ue&&(Ue=le[Le][1]);return[ye,Ee,we-ye,Ue-Ee]}(U);{const le=new Pg,[ye,we,Ee,Ue]=function(Yt){let Xt=Yt[0].x,Rt=Xt,It=Yt[0].y,Jt=It;for(let gr=1;grRt&&(Rt=Yt[gr].x),Yt[gr].yJt&&(Jt=Yt[gr].y);return[Xt,It,Rt-Xt,Jt-It]}(p),Le=Yt=>[(Yt.x-ye)/Ee,(Yt.y-we)/Ue],[Ke,Je,it,Pt]=p.map(Le),ft=function(Yt,Xt,Rt,It,Jt,gr,cr,Gr){const Er=LA(0,0,1,0,1,1,0,1);return C(Er,Er,N([],LA(Yt,Xt,Rt,It,Jt,gr,cr,Gr)))}(Ke[0],Ke[1],Je[0],Je[1],it[0],it[1],Pt[0],Pt[1]);this.elevatedGlobePerspectiveTransform=m7(Ke[0],Ke[1],Je[0],Je[1],it[0],it[1],Pt[0],Pt[1]);const Ft=(Yt,Xt)=>{$.push(Yt.lng);const Rt=Math.round((Yt.lng-Z)/ne*mr),It=Math.round((Yt.lat-Y)/ce*mr),Jt=Le(Xt),gr=jt([],[Jt[0],Jt[1],1],ft),cr=Math.round(gr[0]/gr[2]*mr),Gr=Math.round(gr[1]/gr[2]*mr);le.emplaceBack(Rt,It,cr,Gr)},Vt=p[3].x-p[0].x,qt=p[3].y-p[0].y,er=p[2].x-p[1].x,nr=p[2].y-p[1].y;for(let Yt=0;Yt<65;Yt++){const Xt=Yt/64,Rt=[p[0].x+Xt*Vt,p[0].y+Xt*qt],It=[p[1].x+Xt*er,p[1].y+Xt*nr],Jt=It[0]-Rt[0],gr=It[1]-Rt[1];for(let cr=0;cr<65;cr++){const Gr=cr/64,Er={x:Rt[0]+Jt*Gr,y:Rt[1]+gr*Gr};Ft(d.projection.unproject(Er.x,Er.y),Er)}}this.elevatedGlobeVertexBuffer=l.createVertexBuffer(le,B3.members)}{this.maxLongitudeTriangleSize=0;let le=[],ye=new Fa;const we=(Ee,Ue,Le)=>{ye.emplaceBack(Ee,Ue,Le);const Ke=$[Ee],Je=$[Ue],it=$[Le],Pt=Math.min(Math.min(Ke,Je),it),ft=Math.max(Math.max(Ke,Je),it)-Pt;ft>this.maxLongitudeTriangleSize&&(this.maxLongitudeTriangleSize=ft),le.push(Pt+ft/2)};for(let Ee=0;Ee<64;Ee++)for(let Ue=0;Ue<64;Ue++){const Le=65*Ee+Ue,Ke=Le+1,Je=Le+65,it=Je+1;we(Le,Je,Ke),we(Ke,Je,it)}[le,ye]=function(Ee,Ue){const Le=Array.from({length:Ee.length},(it,Pt)=>Pt);Le.sort((it,Pt)=>Ee[it]-Ee[Pt]);const Ke=[],Je=new Fa;for(let it=0;it{w.segments.push({vertexOffset:0,primitiveOffset:U,vertexLength:d.segments[0].vertexLength,primitiveLength:H,sortKey:void 0,vaos:{}})},M=.51*this.maxLongitudeTriangleSize;if(Math.abs(p[0]-y)<=M){const U=Yi(p,0,p.length,y+M);return U===p.length||k(U,Oa(p,U+1,p.length,y+360-M)-U),w}ymr?y-mr:y,new Wt(Math.trunc(y),Math.trunc(p[d+1]))}translationForInstance(l){const d=16*l,p=this.instancedDataArray.float32;return[p[d+4],p[d+5],p[d+6]]}rotationScaleForInstance(l){const d=16*l,p=this.instancedDataArray.float32;return[p[d+7],p[d+8],p[d+9],p[d+10],p[d+11],p[d+12],p[d+13],p[d+14],p[d+15]]}transformForInstance(l){const d=16*l,p=this.instancedDataArray.float32;return[p[d+7],p[d+8],p[d+9],p[d+4],p[d+10],p[d+11],p[d+12],p[d+5],p[d+13],p[d+14],p[d+15],p[d+6],0,0,0,1]}}class V3{constructor(l){this.zoom=l.zoom,this.canonical=l.canonical,this.overscaledZ=this.canonical.z+Math.log2(l.overscaling),this.layers=l.layers,this.layerIds=this.layers.map(d=>d.fqid),this.projection=l.projection,this.index=l.index,this.worldview=l.worldview,this.hasZoomDependentProperties=this.layers[0].isZoomDependent(),this.stateDependentLayerIds=this.layers.filter(d=>d.isStateDependent()).map(d=>d.id),this.hasPattern=!1,this.instancesPerModel={},this.validForExaggeration=0,this.maxVerticalOffset=0,this.maxScale=0,this.maxHeight=0,this.lookupDim=this.zoom>this.canonical.z+1?0:this.zoom>this.canonical.z?256:this.zoom>15?75:100,this.instanceCount=0,this.terrainElevationMin=0,this.terrainElevationMax=0,this.validForDEMTile={id:null,timestamp:0},this.modelUris=[],this.modelsRequested=!1,this.activeReplacements=[],this.replacementUpdateTime=0,this.styleDefinedModelURLs=l.styleDefinedModelURLs,this.hasAppearances=null}updateFootprints(l,d){}updateAppearances(l,d,p,y){}populate(l,d,p,y){this.tileToMeter=fe(p);const b=this.layers[0]._featureFilter.needGeometry;this.lookup=new Uint8Array(this.lookupDim*this.lookupDim);for(const{feature:w,id:k,index:M,sourceLayerIndex:F}of l){const $=k??(w.properties&&w.properties.hasOwnProperty("id")?w.properties.id:void 0),U=ht(w,b);if(!this.layers[0]._featureFilter.filter(new wi(this.zoom,{worldview:this.worldview,activeFloors:d.activeFloors}),U,p))continue;const H={id:$,sourceLayerIndex:F,index:M,geometry:b?U.geometry:Qe(w,p,y),properties:w.properties,type:w.type,patterns:{}},Z=this.addFeature(H,H.geometry,U);Z&&d.featureIndex.insert(w,H.geometry,M,F,this.index,this.instancesPerModel[Z].instancedDataArray.length,mr/32)}this.lookup=null}evaluateQueryRenderedFeaturePadding(){const l=this.layers[0].modelManager,d=this.layers[0].scope;let p=0;for(const y of this.modelUris){const b=l.getModel(y,d);if(!b)continue;const w=this.instancesPerModel[y];if(w){const k=.5*nt(b.aabb.max,b.aabb.min)*w.maxScale+w.maxXYTranslationDistance,M=Math.min(mr,Math.max(k/this.tileToMeter,mr/32));p=Math.max(M,p)}}return p}update(l,d,p,y){for(const b in this.instancesPerModel){const w=this.instancesPerModel[b];for(const k in l)w.idToFeaturesIndex.hasOwnProperty(k)&&(this.evaluate(w.features[w.idToFeaturesIndex[k]],l[k],w,!0),this.uploaded=!1)}this.maxHeight=0}updateZoomBasedPaintProperties(){if(!this.hasZoomDependentProperties)return!1;let l=!1;for(const d in this.instancesPerModel){const p=this.instancesPerModel[d];for(const y of p.features){const b=this.layers[0],w=y.feature,k=this.canonical,M=b.paint.get("model-rotation").evaluate(w,{},k),F=b.paint.get("model-scale").evaluate(w,{},k),$=b.paint.get("model-translation").evaluate(w,{},k);Lt(y.rotation,M)&&Lt(y.scale,F)&&Lt(y.translation,$)||(this.evaluate(y,y.featureStates,p,!0),l=!0)}}return l}updateReplacement(l,d,p,y){if(d.updateTime===this.replacementUpdateTime)return!1;this.replacementUpdateTime=d.updateTime;const b=d.getReplacementRegionsForTile(l.toUnwrapped(),!0);if(cA(this.activeReplacements,b))return!1;this.activeReplacements=b;let w=!1;for(const k in this.instancesPerModel){const M=this.instancesPerModel[k],F=M.instancedDataArray;for(const $ of M.features){const U=$.instancedDataOffset,H=$.instancedDataCount;for(let Z=0;Zmr;ne=ce?ne-mr:ne;const le=Math.floor(ne),ye=Math.floor(F.float32[Y+1]);let we=!1;for(const Ee of this.activeReplacements)if(!hG(Ee,p,S7.Model,y)&&!(Ee.min.x>le||le>Ee.max.x||Ee.min.y>ye||ye>Ee.max.y)&&(we=yG(gG(le,ye,l.canonical,Ee.footprintTileId.canonical),Ee.footprint),we))break;F.float32[Y]=we?ne+mr:ne,w=w||we!==ce}}}return w}isEmpty(){for(const l in this.instancesPerModel)if(this.instancesPerModel[l].instancedDataArray.length!==0)return!1;return!0}uploadPending(){return!this.uploaded}upload(l){if(!this.uploaded)for(const d in this.instancesPerModel){const p=this.instancesPerModel[d];p.instancedDataArray.length<0||p.instancedDataArray.length===0||(p.instancedDataBuffer?p.instancedDataBuffer.updateData(p.instancedDataArray):p.instancedDataBuffer=l.createVertexBuffer(p.instancedDataArray,gwe.members,!0,void 0,this.instanceCount))}this.uploaded=!0}destroy(l){for(const p in this.instancesPerModel){const y=this.instancesPerModel[p];y.instancedDataArray.length!==0&&y.instancedDataBuffer&&y.instancedDataBuffer.destroy()}const d=this.layers[0].modelManager;if(l&&d&&this.modelUris&&this.modelsRequested)for(const p of this.modelUris)d.removeModel(p,"",!0)}addFeature(l,d,p){const y=this.layers[0],b=y.layout.get("model-id").evaluate(p,{},this.canonical);if(!b)return Ge(`modelId is not evaluated for layer ${y.id} and it is not going to get rendered.`),b;(U3(b,!1)||this.styleDefinedModelURLs[b]!==void 0)&&(this.modelUris.includes(b)||this.modelUris.push(b)),this.instancesPerModel[b]||(this.instancesPerModel[b]=new C7);const w=this.instancesPerModel[b],k=w.instancedDataArray,M=new N7(p,k.length);for(const F of d)for(const $ of F){if($.x<0||$.x>=mr||$.y<0||$.y>=mr)continue;if(this.lookupDim!==0){const H=(this.lookupDim-1)/mr,Z=this.lookupDim*($.y*H|0)+$.x*H|0;if(this.lookup){if(this.lookup[Z]!==0)continue;this.lookup[Z]=1}}this.instanceCount++;const U=k.length;k.resize(U+1),w.instancesEvaluatedElevation.push(0),k.float32[16*U]=$.x,k.float32[16*U+1]=$.y}return M.instancedDataCount=w.instancedDataArray.length-M.instancedDataOffset,M.instancedDataCount>0&&(l.id&&(w.idToFeaturesIndex[l.id]=w.features.length),w.features.push(M),this.evaluate(M,{},w,!1)),b}getModelUris(){return this.modelUris}evaluate(l,d,p,y){const b=this.layers[0],w=l.feature,k=this.canonical,M=l.rotation=b.paint.get("model-rotation").evaluate(w,d,k),F=l.scale=b.paint.get("model-scale").evaluate(w,d,k),$=l.translation=b.paint.get("model-translation").evaluate(w,d,k),U=Object.assign({},b.paint.get("model-color").evaluate(w,d,k));U.a=b.paint.get("model-color-mix-intensity").evaluate(w,d,k);const H=[];this.maxVerticalOffset<$[2]&&(this.maxVerticalOffset=$[2]);const Z=$[0]*$[0]+$[1]*$[1],Y=Z>0?Math.sqrt(Z):0;p.maxScale=Math.max(Math.max(p.maxScale,F[0]),Math.max(F[1],F[2])),p.maxXYTranslationDistance=Math.max(p.maxXYTranslationDistance,Y),this.maxScale=Math.max(Math.max(this.maxScale,F[0]),Math.max(F[1],F[2])),n9(H,M,F);const ne=Math.round(100*U.a)+U.b/1.05;for(let ce=0;ce10?this.tileToMeter:fe(k,Ue)),we[ye+4]=$[0],we[ye+5]=$[1],we[ye+6]=$[2]+Ee,we[ye+7]=H[0],we[ye+8]=H[1],we[ye+9]=H[2],we[ye+10]=H[4],we[ye+11]=H[5],we[ye+12]=H[6],we[ye+13]=H[8],we[ye+14]=H[9],we[ye+15]=H[10],p.instancesEvaluatedElevation[le]=$[2]}}}let k7,T7;Lr(V3,"ModelBucket",{omit:["layers"]}),Lr(C7,"PerModelAttributes"),Lr(N7,"ModelFeature");class Gb{constructor(l,d,p){this._demTile=l,this._dem=this._demTile.dem,this._scale=d,this._offset=p}static create(l,d,p){const y=p||l.findDEMTileFor(d);if(!y||!y.dem)return;const b=y.dem,w=y.tileID,k=1<F.fqid),this.stateDependentLayerIds=this.layers.filter(F=>F.isStateDependent()).map(F=>F.id),this.modelTraits|=Fb.CoordinateSpaceTile,this.uploaded=!1,this.hasPattern=!1,y&&(this.modelTraits|=Fb.HasMapboxMeshFeatures),b&&(this.modelTraits|=Fb.HasMeshoptCompression),this.zoom=-1,this.terrainExaggeration=1,this.projection={name:"mercator"},this.replacementUpdateTime=0,this.elevationReadFromZ=255,this.brightness=w,this.worldview=M,this.dirty=!0,this.needsUpload=!1,this.filter=null,this.nodesInfo=[];for(const F of d)this.nodesInfo.push(new I7(F)),A7(F,k.featureIndexArray.length,k.grid),k.featureIndexArray.emplaceBack(this.nodesInfo.length-1,0,k.bucketLayerIDs.length-1,0);this.states={},this.hasAppearances=null}updateFootprints(l,d){for(const p of this.getNodesInfo()){const y=p.node;y.footprint&&d.push({footprint:y.footprint,id:l})}}updateAppearances(l,d,p,y){}update(l){const d=Object.keys(l).length!==0;if(d&&!this.stateDependentLayers.length)return;const p=d?this.stateDependentLayers:this.layers;if(!xo(l,this.states))for(const y of p)this.evaluate(y,l);this.states=structuredClone(l)}populate(){console.log("populate 3D model bucket")}uploadPending(){return!this.uploaded||this.needsUpload}upload(l){if(!this.needsUpload)return;const d=this.getNodesInfo();for(const p of d){const y=p.node;this.uploaded?this.updatePbrBuffer(y):p3(y,l,!0)}for(const p of d)bA(p.node);this.uploaded=!0,this.needsUpload=!1}updatePbrBuffer(l){let d=!1;if(!l.meshes)return d;for(const p of l.meshes)p.pbrBuffer&&(p.pbrBuffer.updateData(p.featureArray),d=!0);return d}needsReEvaluation(l,d,p){const y=l.transform.projectionOptions,b=l.style.getBrightness(),w=this.brightness!==b;if(!this.uploaded||this.dirty||y.name!==this.projection.name||WN(p.paint.get("model-color").value,w)||WN(p.paint.get("model-color-mix-intensity").value,w)||WN(p.paint.get("model-roughness").value,w)||WN(p.paint.get("model-emissive-strength").value,w)||WN(p.paint.get("model-height-based-emissive-strength-multiplier").value,w)){this.projection=y,this.brightness=b;const k=this.getNodesInfo();for(const M of k)M.state=null;return!0}return!1}evaluateTransform(l,d){if(l.transform.zoom===this.zoom)return;this.zoom=l.transform.zoom;const p=this.getNodesInfo(),y=this.id.canonical;for(const b of p){const w=b.feature;b.evaluatedTranslation=d.paint.get("model-translation").evaluate(w,{},y),b.evaluatedScale=d.paint.get("model-scale").evaluate(w,{},y)}}evaluate(l,d){const p=this.getNodesInfo();for(const y of p){if(!y.node.meshes)continue;const b=y.feature,w=d&&d[b.id];if(xo(w,y.state))continue;y.state=structuredClone(w);const k=y.node.meshes&&y.node.meshes[0].featureData,M=y.evaluatedColor[2],F=y.evaluatedRMEA[2],$=this.id.canonical;if(y.hasTranslucentParts=!1,k){for(let U=0;U=Le)continue;const Yt=q3[nr],Xt=Math.abs(Yt);Xt>ft&&(Pt=Yt,ft=Xt,Ft=er,Vt=qt)}if(ft>.1){const qt=1-(Le+.5*Math.abs(Ft*Vt))/Y;let er=d._dem.get(Je,Ke)+Pt*qt;const nr=d._dem.get(Je+Ft,Ke+Vt),Yt=d._dem.get(Je-Ft,Ke-Vt,!0);(er-nr)*(er-Yt)>0&&(er=(nr+Yt)/2),q3[it]=d._dem.set(Je,Ke,er),jv[it]=Le}}}}}k&&(d._demTile.needsDEMTextureUpload=!0,d._dem._timestamp=lo.now())}setFilter(l){this.filter=l?lb(l):null}getNodesInfo(){return this.filter?this.nodesInfo.filter(l=>this.filter.filter(new wi(this.id.overscaledZ,{worldview:this.worldview}),l.feature,this.id.canonical)):this.nodesInfo}destroy(){const l=this.getNodesInfo();for(const d of l)bA(d.node),m3(d.node)}isEmpty(){return!this.nodesInfo.length}updateReplacement(l,d){if(d.updateTime===this.replacementUpdateTime)return;this.replacementUpdateTime=d.updateTime;const p=d.getReplacementRegionsForTile(l.toUnwrapped());for(const y of this.getNodesInfo()){const b=y.node.footprint;y.hiddenByReplacement=!!b&&!p.find(w=>w.footprint===b)}}getHeightAtTileCoord(l,d){const p=[],y=[0,0,0],b=I([]);for(const w of this.getNodesInfo()){const k=w.node.meshes[0],M=k.transformedAabb;if(lM.max[0]||d>M.max[1])continue;if(w.node.hidden===!0)return{height:1/0,maxHeight:w.feature.properties.height,hidden:!1,verticalScale:w.evaluatedScale[2]};O(b,w.node.globalMatrix),y[0]=l,y[1]=d,ut(y,y,b);const F=(y[0]-k.aabb.min[0])/(k.aabb.max[0]-k.aabb.min[0])*_v|0,$=Math.min(63,(y[1]-k.aabb.min[1])/(k.aabb.max[1]-k.aabb.min[1])*_v|0)*_v+Math.min(63,F),U=k.heightmap[$];if(!(U<0&&w.node.footprint))return w.hiddenByReplacement?void 0:{height:U,maxHeight:w.feature.properties.height,hidden:!1,verticalScale:w.evaluatedScale[2]};if(w.node.footprint.grid.query(new Wt(l,d),new Wt(l,d),p),p.length>0)return{height:void 0,maxHeight:w.feature.properties.height,hidden:w.hiddenByReplacement,verticalScale:w.evaluatedScale[2]}}}}function WN(h,l){return h instanceof kg&&!h.isLightConstant&&l}function K1e(h,l,d,p,y,b,w,k){let M=(61440&l|(61440&l)>>4)>>8,F=(3840&l|(3840&l)>>4)>>4,$=240&l|(240&l)>>4;d[3]>0&&(M=fn(M,255*d[0],d[3]),F=fn(F,255*d[1],d[3]),$=fn($,255*d[2],d[3]));const U=M<<8|F,H=$<<8|Math.floor(255*p[3]),Z=function(Le){const Ke=ue(Le,0,2);return Math.min(Math.round(.5*Ke*255),255)}(p[2])<<8|15*p[0]<<4|15*p[1],Y=ue(y[0],0,1),ne=ue(y[1],0,1),ce=ue(y[2],0,1),le=ue(y[3],0,1);let ye,we,Ee,Ue;if(Y!==ne&&w!==b&&ne!==Y){const Le=w-b;we=1/(Le*(ne-Y)),Ee=-(b+Le*Y)/(Le*(ne-Y));const Ke=ue(y[4],-1,1);Ue=Math.pow(10,Ke),ye=255*ce<<8|255*le}else ye=65535,we=0,Ee=1,Ue=1;if(h.emplaceBack(U,H,Z,ye,we,Ee,Ue),k){const Le=k.length;k.clear();for(let Ke=0;Ke>16&65535,$=b?M>>16&65535:65535&M,U=(15&$)<8?15&$:0,H=h.evaluatedRMEA[U],Z=h.evaluatedColor[U],Y=h.emissionHeightBasedParams[U];let ne;if(k&&U===2&&p.lights&&(ne=new vb,ne.resize(10*p.lights.length)),K1e(w.featureArray,F,Z,H,Y,w.aabb.min[2],w.aabb.max[2],ne),ne&&k){k=!1;const ce=p.meshes[p.lightMeshIndex];ce.featureArray=ne,ce.featureArray._trim()}}w.featureArray._trim(),y++}}Lr(BA,"Tiled3dModelBucket",{omit:["layers"]}),Lr(I7,"Tiled3dModelFeature");const Y1e=["id","tile","layer","source","sourceLayer","state"];class Sv{constructor(l,d,p,y,b){this.type="Feature",this._vectorTileFeature=l,this._z=d,this._x=p,this._y=y,this.properties=l?l.properties:{},this.id=b}clone(){const l=new Sv(this._vectorTileFeature,this._z,this._x,this._y,this.id);return this.state&&(l.state=Object.assign({},this.state)),this.layer&&(l.layer=Object.assign({},this.layer)),this.source&&(l.source=this.source),this.sourceLayer&&(l.sourceLayer=this.sourceLayer),l}get geometry(){return this._geometry===void 0&&this._vectorTileFeature&&(this._geometry=this._vectorTileFeature.toGeoJSON(this._x,this._y,this._z).geometry),this._geometry}set geometry(l){this._geometry=l}toJSON(){const l={type:"Feature",state:void 0,geometry:this.geometry,properties:this.properties};for(const d of Y1e)this[d]!==void 0&&(l[d]=this[d]);return l}}class Nv extends qp{constructor(l,d,p,y){super(),this.id=l,this.type="model",this.models=[],this._loaded=!1,this._options=d,this._modelsInfo=new Map}load(){const l=[];for(const d in this._options.models){const p=this._options.models[d],y=this._modelsInfo.get(d);if(y){const b=y.model;b.position=p.position!=null?new f(p.position[0],p.position[1]):new f(0,0),b.orientation=p.orientation!=null?p.orientation:[0,0,0],y.modelSpec=p,Nv.applyModelSpecification(b,p),b.computeBoundsAndApplyParent(),this.models.push(b)}else{const b=JG(this.map._requestManager.transformRequest(p.uri,Mx.Model).url).then(w=>{if(!w)return;const k=y3(w),M=new s9(d,p.uri,p.position,p.orientation,k);Nv.applyModelSpecification(M,p),M.computeBoundsAndApplyParent(),this.models.push(M),this._modelsInfo.set(d,{modelSpec:p,model:M})}).catch(w=>{this.fire(new Lx(new Error(`Could not load model ${d} from ${p.uri}: ${w.message}`)))});l.push(b)}}Promise.allSettled(l).then(()=>{this._loaded=!0,this.fire(new Pd("data",{dataType:"source",sourceDataType:"metadata"}))}).catch(d=>{this._loaded=!0,this.fire(new Lx(new Error(`Could not load models: ${d.message}`)))})}static applyModelSpecification(l,d){d.nodeOverrides&&Nv.convertNodeOverrides(l,d.nodeOverrides),d.materialOverrides&&Nv.convertMaterialOverrides(l,d.materialOverrides),d.nodeOverrideNames&&(l.nodeOverrideNames=[...d.nodeOverrideNames]),d.materialOverrideNames&&(l.materialOverrideNames=[...d.materialOverrideNames]),d.featureProperties&&(l.featureProperties=d.featureProperties)}static convertNodeOverrides(l,d){if(Array.isArray(d)&&d.every(p=>typeof p=="string")){l.nodeOverrideNames=[];for(const p of d)l.nodeOverrideNames.push(p)}else Object.entries(d).forEach(([p,y])=>{const b={orientation:[0,0,0]};if(y.hasOwnProperty("orientation")){const w=y.orientation;w&&(b.orientation=w)}l.nodeOverrides.set(p,b)})}static convertMaterialOverrides(l,d){if(Array.isArray(d)&&d.every(p=>typeof p=="string")){l.materialOverrideNames=[];for(const p of d)l.materialOverrideNames.push(p)}else Object.entries(d).forEach(([p,y])=>{const b={color:new Us(1,1,1),colorMix:0,emissionStrength:0,opacity:1},w=y["model-color"];w!==void 0&&(b.color.r=w[0],b.color.g=w[1],b.color.b=w[2]);const k=y["model-color-mix-intensity"];k!==void 0&&(b.colorMix=k);const M=y["model-emissive-strength"];M!==void 0&&(b.emissionStrength=M);const F=y["model-opacity"];F!==void 0&&(b.opacity=F),l.materialOverrides.set(p,b)})}onAdd(l){this.map=l,this.load()}hasTransition(){return!1}loaded(){return this._loaded}getModels(){return this.models}loadTile(l,d){}serialize(){return this._options}setProperty(l,d){return!1}reload(){const l=Ju(this.id,this.scope);this.map.style.clearSource(l),this.models=[],this._modelsInfo.clear(),this._loaded=!1,this.load()}setModels(l){this.models=[];const d=new Map;for(const p in l){const y=l[p];if(this._modelsInfo.has(p)){const b=this._modelsInfo.get(p);b&&b.modelSpec.uri===y.uri&&d.set(p,b)}}this._modelsInfo=d,this._options.models=l,this._loaded=!1,this.load()}}function H3(h,l,d,p){const y=1<Ee.polygon).flat());const ce=Z?k:null,[le,ye]=$G(b,p,U,$,F,w,ce,H,Y,b.center.lat,h.tileID.canonical),we=h.queryGeometry;return BG(le,ye,we.isPointQuery()?we.screenBounds:we.screenGeometry)}},building:class extends Dl{constructor(h,l,d,p){super(h,{layout:d9||(d9=new ta({visibility:new hr(yt.layout_building.visibility),"building-facade":new br(yt.layout_building["building-facade"]),"building-facade-floors":new br(yt.layout_building["building-facade-floors"]),"building-facade-unit-width":new br(yt.layout_building["building-facade-unit-width"]),"building-facade-window":new br(yt.layout_building["building-facade-window"]),"building-roof-shape":new br(yt.layout_building["building-roof-shape"]),"building-height":new br(yt.layout_building["building-height"]),"building-base":new br(yt.layout_building["building-base"]),"building-flood-light-wall-radius":new br(yt.layout_building["building-flood-light-wall-radius"]),"building-flood-light-ground-radius":new br(yt.layout_building["building-flood-light-ground-radius"]),"building-flip-roof-orientation":new br(yt.layout_building["building-flip-roof-orientation"])})),paint:h9||(h9=new ta({"building-opacity":new hr(yt.paint_building["building-opacity"]),"building-ambient-occlusion-intensity":new hr(yt.paint_building["building-ambient-occlusion-intensity"]),"building-ambient-occlusion-ground-intensity":new hr(yt.paint_building["building-ambient-occlusion-ground-intensity"]),"building-ambient-occlusion-ground-radius":new hr(yt.paint_building["building-ambient-occlusion-ground-radius"]),"building-ambient-occlusion-ground-attenuation":new hr(yt.paint_building["building-ambient-occlusion-ground-attenuation"]),"building-vertical-scale":new hr(yt.paint_building["building-vertical-scale"]),"building-cast-shadows":new hr(yt.paint_building["building-cast-shadows"]),"building-color":new br(yt.paint_building["building-color"]),"building-emissive-strength":new br(yt.paint_building["building-emissive-strength"]),"building-facade-emissive-chance":new hr(yt.paint_building["building-facade-emissive-chance"]),"building-cutoff-fade-range":new hr(yt.paint_building["building-cutoff-fade-range"]),"building-flood-light-color":new hr(yt.paint_building["building-flood-light-color"]),"building-flood-light-intensity":new hr(yt.paint_building["building-flood-light-intensity"]),"building-flood-light-ground-attenuation":new hr(yt.paint_building["building-flood-light-ground-attenuation"]),"building-color-use-theme":new br({type:"string",default:"default","property-type":"data-driven"}),"building-flood-light-color-use-theme":new br({type:"string",default:"default","property-type":"data-driven"})}))},l,d,p),this._stats={numRenderedVerticesInShadowPass:0,numRenderedVerticesInTransparentPass:0}}createBucket(h){return new u9(h)}cutoffRange(){return this.paint.get("building-cutoff-fade-range")}hasShadowPass(){return this.paint.get("building-cast-shadows")}hasLightBeamPass(){return!0}canCastShadows(){return!0}is3D(h){return!0}queryRadius(h){return 0}queryIntersectsFeature(h,l,d,p,y,b,w,k,M){let F=this.layout.get("building-height").evaluate(l,d);const $=this.layout.get("building-base").evaluate(l,d),U=h.tile.getBucket(this).getFootprint(l);if(U){if(U.hiddenFlags!==0)return!1;F=U.height}const[H,Z]=$G(b,p,$,F,new Wt(0,0),w,null,[0,0],1,b.center.lat,h.tileID.canonical),Y=h.queryGeometry;return BG(H,Z,Y.isPointQuery()?Y.screenBounds:Y.screenGeometry)}},line:class extends Dl{constructor(h,l,d,p){const y=w9();super(h,y,l,d,p),y.layout&&(this.layout=new Jp(y.layout)),this.gradientVersion=0,this.hasElevatedBuckets=!1,this.hasNonElevatedBuckets=!1}_handleSpecialPaintPropertyUpdate(h){if(h==="line-gradient"){const l=this._transitionablePaint._values["line-gradient"].value.expression;this.stepInterpolant=l._styleExpression&&l._styleExpression.expression instanceof Zx,this.gradientVersion=(this.gradientVersion+1)%Number.MAX_SAFE_INTEGER}}gradientExpression(){return this._transitionablePaint._values["line-gradient"].value.expression}widthExpression(){return this._transitionablePaint._values["line-width"].value.expression}emissiveStrengthExpression(){return this._transitionablePaint._values["line-emissive-strength"].value.expression}recalculate(h,l){super.recalculate(h,l),this.paint._values["line-floorwidth"]=(()=>{if(PN)return PN;const d=w9();return PN=new Wwe(d.paint.properties["line-width"].specification),PN.useIntegerZoom=!0,PN})().possiblyEvaluate(this._transitioningPaint._values["line-width"].value,h)}createBucket(h){return new _3(h)}getProgramIds(){return[this.paint.get("line-pattern").constantOr(1)?"linePattern":"line"]}getDefaultProgramParams(h,l,d){const p=_9(this);return{config:new Zf(this,{zoom:l,lut:d}),defines:p,overrideFog:!1}}queryRadius(h){const l=h,d=j9(sl("line-width",this,l),sl("line-gap-width",this,l)),p=sl("line-offset",this,l);return d/2+Math.abs(p)+To(this.paint.get("line-translate"))}queryIntersectsFeature(h,l,d,p,y,b){if(h.queryGeometry.isAboveHorizon)return!1;const w=Hc(h.tilespaceGeometry,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),b.angle,h.pixelToTileUnitsFactor),k=h.pixelToTileUnitsFactor/2*j9(this.paint.get("line-width").evaluate(l,d),this.paint.get("line-gap-width").evaluate(l,d)),M=this.paint.get("line-offset").evaluate(l,d);return M&&(p=function(F,$){const U=[],H=new Wt(0,0);for(let Z=0;Z=3){for(let Y=0;Y>16&255)/255,(h>>8&255)/255,(255&h)/255,1)}function dje(h,l,d){h===1?(l.rgb_color=qA(d.readVarint()),l.paint="rgb_color"):h===2?(l.linear_gradient_idx=d.readVarint(),l.paint="linear_gradient_idx"):h===3?(l.radial_gradient_idx=d.readVarint(),l.paint="radial_gradient_idx"):h===5?d.readPackedFloat(l.dasharray):h===6?l.dashoffset=d.readFloat():h===7?l.miterlimit=d.readFloat():h===8?l.opacity=d.readVarint():h===9?l.width=d.readFloat():h===10?l.linecap=d.readVarint():h===11&&(l.linejoin=d.readVarint())}function hje(h,l,d){h===1?l.transform=VA(d,d.readVarint()+d.pos):h===2?l.spread_method=d.readVarint():h===3?l.stops.push(D7(d,d.readVarint()+d.pos)):h===4?l.x1=d.readFloat():h===5?l.y1=d.readFloat():h===6?l.x2=d.readFloat():h===7&&(l.y2=d.readFloat())}function D7(h,l){return h.readFields(fje,{offset:0,opacity:255,rgb_color:W3},l)}function fje(h,l,d){h===1?l.offset=d.readFloat():h===2?l.opacity=d.readVarint():h===3&&(l.rgb_color=qA(d.readVarint()))}function pje(h,l,d){h===1?l.transform=VA(d,d.readVarint()+d.pos):h===2?l.spread_method=d.readVarint():h===3?l.stops.push(D7(d,d.readVarint()+d.pos)):h===4?l.cx=d.readFloat():h===5?l.cy=d.readFloat():h===6?l.r=d.readFloat():h===7?l.fx=d.readFloat():h===8?l.fy=d.readFloat():h===9&&(l.fr=d.readFloat())}function mje(h,l,d){h===1?l.transform=VA(d,d.readVarint()+d.pos):h===2?l.clip_path_idx=d.readVarint():h===3&&l.children.push(UA(d,d.readVarint()+d.pos))}function gje(h,l,d){h===1?l.left=l.top=d.readFloat():h===2?l.width=l.height=d.readFloat():h===3?l.top=d.readFloat():h===4?l.height=d.readFloat():h===5?l.mask_type=d.readVarint():h===6?l.mask_idx=d.readVarint():h===7&&l.children.push(UA(d,d.readVarint()+d.pos))}class yje{static calculate(l={},d=[]){const p=new Map,y=new Map;if(Object.keys(l).length===0)return p;d.forEach(b=>{y.set(b.name,b.rgb_color||new Us(0,0,0))});for(const[b,w]of Object.entries(l))y.has(b)?p.set(y.get(b).toString(),w):console.warn(`Ignoring unknown image variable "${b}"`);return p}}function Kb(h,l=255,d){const p=l/255,y=h.toString(),b=d.has(y)?d.get(y).clone():h.clone();return b.a*=p,b.toString()}function KN(h,l){if(!Td()){const d=document.createElement("canvas");return d.width=h,d.height=l,d}return new OffscreenCanvas(h,l)}let Z3,ZN=null;function Y3(h,l,d,p,y){for(const b of p.children)L7(h,l,d,b,y)}function L7(h,l,d,p,y){p.group?(h.save(),function(b,w,k,M,F){const $=M.mask_idx!=null?k.masks[M.mask_idx]:null,U=M.clip_path_idx!=null?k.clip_paths[M.clip_path_idx]:null;if(M.transform&&(w=Zb(M.transform).preMultiplySelf(w)),!function(Y,ne,ce){return Y.opacity!==255||ne||ce}(M,U!=null,$!=null))return void Y3(b,w,k,M,F);const H=KN(b.canvas.width,b.canvas.height),Z=H.getContext("2d");Y3(Z,w,k,M,F),U&&q7(Z,w,k,U),$&&H7(Z,w,k,$,F),b.globalAlpha=M.opacity/255,b.drawImage(H,0,0)}(h,l,d,p.group,y),h.restore()):p.path&&(h.save(),function(b,w,k,M,F){b.setTransform(w),M.paint_order===J1e.PAINT_ORDER_FILL_AND_STROKE?(F7(b,k,M,F),B7(b,k,M,F)):(B7(b,k,M,F),F7(b,k,M,F))}(h,l,d,p.path,y),h.restore())}function F7(h,l,d,p){const y=d.fill;if(!y)return;const b=y.opacity/255;switch(h.save(),h.beginPath(),W7(d,h),y.paint){case"rgb_color":h.fillStyle=Kb(y.rgb_color,y.opacity,p);break;case"linear_gradient_idx":{const w=l.linear_gradients[y.linear_gradient_idx];w.transform&&h.setTransform(Zb(w.transform).preMultiplySelf(h.getTransform())),h.fillStyle=$7(h,w,b,p);break}case"radial_gradient_idx":{const w=l.radial_gradients[y.radial_gradient_idx];w.transform&&h.setTransform(Zb(w.transform).preMultiplySelf(h.getTransform())),h.fillStyle=U7(h,w,b,p)}}h.fill(z7(d)),h.restore()}function z7(h){return h.rule===G3.PATH_RULE_NON_ZERO?"nonzero":h.rule===G3.PATH_RULE_EVEN_ODD?"evenodd":void 0}function B7(h,l,d,p){const y=d.stroke;if(!y)return;const b=G7(d);h.lineWidth=y.width,h.miterLimit=y.miterlimit,h.setLineDash(y.dasharray),h.lineDashOffset=y.dashoffset;const w=y.opacity/255;switch(y.paint){case"rgb_color":h.strokeStyle=Kb(y.rgb_color,y.opacity,p);break;case"linear_gradient_idx":h.strokeStyle=$7(h,l.linear_gradients[y.linear_gradient_idx],w,p,!0);break;case"radial_gradient_idx":h.strokeStyle=U7(h,l.radial_gradients[y.radial_gradient_idx],w,p,!0)}switch(y.linejoin){case $A.LINE_JOIN_MITER_CLIP:case $A.LINE_JOIN_MITER:h.lineJoin="miter";break;case $A.LINE_JOIN_ROUND:h.lineJoin="round";break;case $A.LINE_JOIN_BEVEL:h.lineJoin="bevel"}switch(y.linecap){case K3.LINE_CAP_BUTT:h.lineCap="butt";break;case K3.LINE_CAP_ROUND:h.lineCap="round";break;case K3.LINE_CAP_SQUARE:h.lineCap="square"}h.stroke(b)}function $7(h,l,d,p,y=!1){if(l.stops.length===1){const H=l.stops[0];return Kb(H.rgb_color,H.opacity*d,p)}const{x1:b,y1:w,x2:k,y2:M}=l;let F=new DOMPoint(b,w),$=new DOMPoint(k,M);if(y){const H=Zb(l.transform);F=H.transformPoint(F),$=H.transformPoint($)}const U=h.createLinearGradient(F.x,F.y,$.x,$.y);for(const H of l.stops)U.addColorStop(H.offset,Kb(H.rgb_color,H.opacity*d,p));return U}function U7(h,l,d,p,y=!1){if(l.stops.length===1){const le=l.stops[0];return Kb(le.rgb_color,le.opacity*d,p)}const b=Zb(l.transform),{fx:w,fy:k,fr:M,cx:F,cy:$,r:U}=l;let H=new DOMPoint(w,k),Z=new DOMPoint(F,$),Y=M,ne=U;if(y){H=b.transformPoint(H),Z=b.transformPoint(Z);const le=(b.a+b.d)/2;Y=M*le,ne=l.r*le}const ce=h.createRadialGradient(H.x,H.y,Y,Z.x,Z.y,ne);for(const le of l.stops)ce.addColorStop(le.offset,Kb(le.rgb_color,le.opacity*d,p));return ce}function V7(h,l,d,p){const y=p.transform?Zb(p.transform).preMultiplySelf(l):l,b=KN(h.canvas.width,h.canvas.height),w=b.getContext("2d");for(const M of p.children)if(M.group)V7(w,y,d,M.group);else if(M.path){const F=M.path,$=new Path2D;$.addPath(G7(F),y),w.fill($,z7(F))}const k=p.clip_path_idx!=null?d.clip_paths[p.clip_path_idx]:null;k&&q7(w,y,d,k),h.globalCompositeOperation="source-over",h.drawImage(b,0,0)}function q7(h,l,d,p){const y=KN(h.canvas.width,h.canvas.height);V7(y.getContext("2d"),l,d,p),h.globalCompositeOperation="destination-in",h.drawImage(y,0,0)}function H7(h,l,d,p,y){if(p.children.length===0)return;const b=p.mask_idx!=null?d.masks[p.mask_idx]:null;b&&H7(h,l,d,b,y);const w=h.canvas.width,k=h.canvas.height,M=KN(w,k),F=M.getContext("2d"),$=p.width,U=p.height,H=p.left,Z=p.top,Y=new Path2D,ne=new Path2D;ne.rect(H,Z,$,U),Y.addPath(ne,l),F.clip(Y);for(const ye of p.children)L7(F,l,d,ye,y);const ce=F.getImageData(0,0,w,k),le=ce.data;if(p.mask_type===M7.MASK_TYPE_LUMINANCE)for(let ye=0;yel[w])return null}else{const k=1/p[w];let M=(h[w]-d[w])*k,F=(l[w]-d[w])*k;if(M>F){const $=M;M=F,F=$}if(M>y&&(y=M),Fb)return null}return y}function Y7(h,l,d,p,y,b,w,k,M,F,$){const U=p-h,H=y-l,Z=b-d,Y=w-h,ne=k-l,ce=M-d,le=$[1]*ce-$[2]*ne,ye=$[2]*Y-$[0]*ce,we=$[0]*ne-$[1]*Y,Ee=U*le+H*ye+Z*we;if(Math.abs(Ee)<1e-15)return null;const Ue=1/Ee,Le=F[0]-h,Ke=F[1]-l,Je=F[2]-d,it=(Le*le+Ke*ye+Je*we)*Ue;if(it<0||it>1)return null;const Pt=Ke*Z-Je*H,ft=Je*U-Le*Z,Ft=Le*H-Ke*U,Vt=($[0]*Pt+$[1]*ft+$[2]*Ft)*Ue;return Vt<0||it+Vt>1?null:(Y*Pt+ne*ft+ce*Ft)*Ue}function X7(h,l,d){return(h-l)/(d-l)}function Q7(h,l,d,p,y,b,w,k,M){const F=1<{const ye=ce?1:0,we=(Z+1)*ne-ye,Ee=Y*ne,Ue=(Y+1)*ne-ye;le[0]=Z*ne,le[1]=Ee,le[2]=we,le[3]=Ue};let U=new K7(M);const H=[];for(let Z=0;Z=1;M/=2){const Z=k[k.length-1];U=new K7(M);for(let Y=0;Y0;){const{idx:Y,t:ne,nodex:ce,nodey:le,depth:ye}=Z.pop();if(this.leaves[Y]){Q7(ce,le,ye,l,d,p,y,U,H);const Ee=1<=nr[2])return ne}continue}let we=0;for(let Ee=0;Ee=F[$[Je]]&&($.splice(Je,0,Ee),Ke=!0);Ke||($[we]=Ee),we++}}for(let Ee=0;Ee=this.dim+1||d<-1||d>=this.dim+1)throw new RangeError("out of range source coordinates for DEM data");return(d+1)*this.stride+(l+1)}static pack(l,d){const p=[0,0,0,0],y=WA.getUnpackVector(d);let b=Math.floor((l+y[3])/y[2]);return p[2]=b%256,b=Math.floor(b/256),p[1]=b%256,b=Math.floor(b/256),p[0]=b,p}getPixels(){return new KW({width:this.stride,height:this.stride},this.pixels)}backfillBorder(l,d,p){if(this.dim!==l.dim)throw new Error("dem dimension mismatch");let y=d*this.dim,b=d*this.dim+this.dim,w=p*this.dim,k=p*this.dim+this.dim;switch(d){case-1:y=b-1;break;case 1:b=y+1}switch(p){case-1:w=k-1;break;case 1:k=w+1}const M=-d*this.dim,F=-p*this.dim;for(let $=w;$=1;p--){const y=p===1?1:0,b=p===2?1:0;for(let w=0;w>>1^-(1&h[l]);return h}function Pje(h,l){switch(l){case"uint32":return h;case"uint16":for(let d=0;d>4|(61440&p)>>8|(240&y)<<4|61440&y,h[d+1]=15&p|(3840&p)>>4|(15&y)<<8|(3840&y)<<4}return h;case"uint8":for(let d=0;d>6|(192&y)>>4|(192&b)>>2|192&w,h[d+1]=(48&p)>>4|(48&y)>>2|48&b|(48&w)<<2,h[d+2]=(12&p)>>2|12&y|(12&b)<<2|(12&w)<<4,h[d+3]=3&p|(3&y)<<2|(3&b)<<4|(3&w)<<6}return h;default:throw new Error(`Invalid pixel format, "${l}"`)}}Lr(WA,"DEMData"),Lr(J7,"DemMinMaxQuadTree",{omit:["dem"]});var nd=Uint8Array,YN=Uint16Array,Ije=Int32Array,tK=new nd([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]),rK=new nd([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]),Mje=new nd([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),nK=function(h,l){for(var d=new YN(31),p=0;p<31;++p)d[p]=l+=1<>1|(21845&Xa)<<1;aK[Xa]=((65280&(Yb=(61680&(Yb=(52428&Yb)>>2|(13107&Yb)<<2))>>4|(3855&Yb)<<4))>>8|(255&Yb)<<8)>>1}var XN=function(h,l,d){for(var p=h.length,y=0,b=new YN(l);y>M]=F;return w},QN=new nd(288);for(Xa=0;Xa<144;++Xa)QN[Xa]=8;for(Xa=144;Xa<256;++Xa)QN[Xa]=9;for(Xa=256;Xa<280;++Xa)QN[Xa]=7;for(Xa=280;Xa<288;++Xa)QN[Xa]=8;var oK=new nd(32);for(Xa=0;Xa<32;++Xa)oK[Xa]=5;var Dje=XN(QN,9),Lje=XN(oK,5),Q3=function(h){for(var l=h[0],d=1;dl&&(l=h[d]);return l},qh=function(h,l,d){var p=l/8|0;return(h[p]|h[p+1]<<8)>>(7&l)&d},J3=function(h,l){var d=l/8|0;return(h[d]|h[d+1]<<8|h[d+2]<<16)>>(7&l)},Fje=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],Hh=function(h,l,d){var p=new Error(l||Fje[h]);if(p.code=h,Error.captureStackTrace&&Error.captureStackTrace(p,Hh),!d)throw p;return p},zje=new nd(0),Bje=typeof TextDecoder<"u"&&new TextDecoder;try{Bje.decode(zje,{stream:!0})}catch{}const $je={gzip_data:"gzip"};class Ud extends Error{constructor(l){super(l),this.name="MRTError"}}const Uje={0:"uint32",1:"uint32",2:"uint16",3:"uint8"},lK={uint32:1,uint16:2,uint8:4},Vje={uint32:Uint32Array,uint16:Uint16Array,uint8:Uint8Array};let eF;class GA{constructor(l=5){this.x=NaN,this.y=NaN,this.z=NaN,this.layers={},this._cacheSize=l}getLayer(l){const d=this.layers[l];if(!d)throw new Ud(`Layer '${l}' not found`);return d}getHeaderLength(l){const d=new Uint8Array(l),p=new DataView(l);if(d[0]!==13)throw new Ud("File is not a valid MRT.");return p.getUint32(1,!0)}parseHeader(l){const d=new Uint8Array(l),p=this.getHeaderLength(l);if(d.length= ${p} but got buffer of length ${d.length}`);const y=new eF(d.subarray(0,p)).readFields(bje,{headerLength:0,x:0,y:0,z:0,layers:[]},void 0);if(!isNaN(this.x)&&(this.x!==y.x||this.y!==y.y||this.z!==y.z))throw new Ud(`Invalid attempt to parse header ${y.z}/${y.x}/${y.y} for tile ${this.z}/${this.x}/${this.y}`);this.x=y.x,this.y=y.y,this.z=y.z;for(const b of y.layers)this.layers[b.name]=new cK(b,{cacheSize:this._cacheSize});return this}createDecodingTask(l){const d=[],p=this.getLayer(l.layerName);for(let y of l.blockIndices){const b=p.dataIndex[y],w=b.firstByte-l.firstByte,k=b.lastByte-l.firstByte;if(p._blocksInProgress.has(y))continue;const M={layerName:p.name,firstByte:w,lastByte:k,pixelFormat:p.pixelFormat,blockIndex:y,blockShape:[b.bands.length].concat(p.bandShape),buffer:p.buffer,codec:b.codec.codec,filters:b.filters.map(F=>F.filter)};p._blocksInProgress.add(y),d.push(M)}return new uK(d,()=>{d.forEach(y=>p._blocksInProgress.delete(y.blockIndex))},(y,b)=>{if(d.forEach(w=>p._blocksInProgress.delete(w.blockIndex)),y)throw y;b.forEach(w=>{this.getLayer(w.layerName).processDecodedData(w)})})}}class cK{constructor({version:l,name:d,units:p,tileSize:y,pixelFormat:b,buffer:w,dataIndex:k},M){if(this.version=l,this.version!==1)throw new Ud(`Cannot parse raster layer encoded with MRT version ${l}`);this.name=d,this.units=p,this.tileSize=y,this.buffer=w,this.pixelFormat=Uje[b],this.dataIndex=k,this.bandShape=[y+2*w,y+2*w,lK[this.pixelFormat]],this._decodedBlocks=new HA(M?M.cacheSize:5),this._blocksInProgress=new Set}get dimension(){return lK[this.pixelFormat]}get cacheSize(){return this._decodedBlocks.capacity}getBandList(){return this.dataIndex.map(({bands:l})=>l).flat()}processDecodedData(l){const d=l.blockIndex.toString();this._decodedBlocks.get(d)||this._decodedBlocks.put(d,l.data)}getBlockForBand(l){let d=0;switch(typeof l){case"string":for(const[p,y]of this.dataIndex.entries()){for(const[b,w]of y.bands.entries())if(w===l)return{bandIndex:d+b,blockIndex:p,blockBandIndex:b};d+=y.bands.length}break;case"number":for(const[p,y]of this.dataIndex.entries()){if(l>=d&&lthis.cacheSize)throw new Ud(`Number of blocks to decode (${b.size}) exceeds cache size (${this.cacheSize}).`);return{layerName:this.name,firstByte:d,lastByte:p,blockIndices:y}}hasBand(l){const{blockIndex:d}=this.getBlockForBand(l);return d>=0}hasDataForBand(l){const{blockIndex:d}=this.getBlockForBand(l);return d>=0&&!!this._decodedBlocks.get(d.toString())}getBandView(l){const{blockIndex:d,blockBandIndex:p}=this.getBlockForBand(l);if(d<0)throw new Ud(`Band not found: ${JSON.stringify(l)}`);const y=this._decodedBlocks.get(d.toString());if(!y)throw new Ud(`Data for band ${JSON.stringify(l)} of layer "${this.name}" not decoded.`);const b=this.dataIndex[d],w=this.bandShape.reduce((F,$)=>F*$,1),k=p*w,M=y.subarray(k,k+w);return{data:M,bytes:new Uint8Array(M.buffer).subarray(M.byteOffset,M.byteOffset+M.byteLength),tileSize:this.tileSize,buffer:this.buffer,pixelFormat:this.pixelFormat,dimension:this.dimension,offset:b.offset,scale:b.scale}}}GA.setPbf=function(h){eF=h};class uK{constructor(l,d,p){this.tasks=l,this._onCancel=d,this._onComplete=p,this._finalized=!1}cancel(){this._finalized||(this._onCancel(),this._finalized=!0)}complete(l,d){this._finalized||(this._onComplete(l,d),this._finalized=!0)}}GA.performDecoding=function(h,l){const d=new Uint8Array(h);return Promise.all(l.tasks.map(p=>{const{layerName:y,firstByte:b,lastByte:w,pixelFormat:k,blockShape:M,blockIndex:F,filters:$,codec:U}=p,H=d.subarray(b,w+1),Z=new Uint32Array(M[0]*M[1]*M[2]);let Y;if(U!=="gzip_data")throw new Ud(`Unhandled codec: ${U}`);return Y=function(ne,ce){if(!globalThis.DecompressionStream&&ce==="gzip_data")return Promise.resolve(((Ee=function(Ke){Ke[0]==31&&Ke[1]==139&&Ke[2]==8||Hh(6,"invalid gzip data");var Je=Ke[3],it=10;4&Je&&(it+=2+(Ke[10]|Ke[11]<<8));for(var Pt=(Je>>3&1)+(Je>>4&1);Pt>0;Pt-=!Ke[it++]);return it+(2&Je)}(we=ne))+8>we.length&&Hh(6,"invalid gzip data"),function(Ke,Je,it,Pt){var ft=Ke.length;if(!ft||Je.f&&!Je.l)return it||new nd(0);var Ft=!it,Vt=Ft||Je.i!=2,qt=Je.i;Ft&&(it=new nd(3*ft));var er,nr,Yt=function(ei){var Ms=it.length;if(ei>Ms){var Fs=new nd(Math.max(2*Ms,ei));Fs.set(it),it=Fs}},Xt=Je.f||0,Rt=Je.p||0,It=Je.b||0,Jt=Je.l,gr=Je.d,cr=Je.m,Gr=Je.n,Er=8*ft;do{if(!Jt){Xt=qh(Ke,Rt,1);var Or=qh(Ke,Rt+1,3);if(Rt+=3,!Or){var Br=Ke[(zt=4+((Rt+7)/8|0))-4]|Ke[zt-3]<<8,$n=zt+Br;if($n>ft){qt&&Hh(0);break}Vt&&Yt(It+Br),it.set(Ke.subarray(zt,$n),It),Je.b=It+=Br,Je.p=Rt=8*$n,Je.f=Xt;continue}if(Or==1)Jt=Dje,gr=Lje,cr=9,Gr=5;else if(Or==2){var dr=qh(Ke,Rt,31)+257,$r=qh(Ke,Rt+10,15)+4,wn=dr+qh(Ke,Rt+5,31)+1;Rt+=14;for(var ls=new nd(wn),hs=new nd(19),Tn=0;Tn<$r;++Tn)hs[Mje[Tn]]=qh(Ke,Rt+3*Tn,7);Rt+=3*$r;var Js=Q3(hs),Fe=(1<>4)<16)ls[Tn++]=zt;else{var Nr=0,Cr=0;for(zt==16?(Cr=3+qh(Ke,Rt,3),Rt+=2,Nr=ls[Tn-1]):zt==17?(Cr=3+qh(Ke,Rt,7),Rt+=3):zt==18&&(Cr=11+qh(Ke,Rt,127),Rt+=7);Cr--;)ls[Tn++]=Nr}}var Kr=ls.subarray(0,dr),Xr=ls.subarray(dr);cr=Q3(Kr),Gr=Q3(Xr),Jt=XN(Kr,cr),gr=XN(Xr,Gr)}else Hh(1);if(Rt>Er){qt&&Hh(0);break}}Vt&&Yt(It+131072);for(var kn=(1<>4;if((Rt+=15&Nr)>Er){qt&&Hh(0);break}if(Nr||Hh(2),rs<256)it[It++]=rs;else{if(rs==256){zn=Rt,Jt=null;break}var un=rs-254;rs>264&&(un=qh(Ke,Rt,(1<<(ks=tK[Tn=rs-257]))-1)+iK[Tn],Rt+=ks);var bn=gr[J3(Ke,Rt)&In],ys=bn>>4;if(bn||Hh(3),Rt+=15&bn,Xr=Rje[ys],ys>3){var ks=rK[ys];Xr+=J3(Ke,Rt)&(1<Er){qt&&Hh(0);break}Vt&&Yt(It+131072);var Ts=It+un;if(Iter.length)&&(nr=er.length),new nd(er.subarray(0,nr))):it.subarray(0,It)}(we.subarray(Ee,-8),{i:2},new nd(((le=we)[(ye=le.length)-4]|le[ye-3]<<8|le[ye-2]<<16|le[ye-1]<<24)>>>0))));var le,ye,we,Ee;const Ue=$je[ce];if(!Ue)throw new Error(`Unhandled codec: ${ce}`);const Le=new globalThis.DecompressionStream(Ue);return new Response(new Blob([ne]).stream().pipeThrough(Le)).arrayBuffer().then(Ke=>new Uint8Array(Ke))}(H,U).then(ne=>(function(ce,le){ce.readFields(kje,le)}(new eF(ne),Z),new Vje[k](Z.buffer))),Y.then(ne=>{for(let ce=$.length-1;ce>=0;ce--)switch($[ce]){case"delta_filter":Eje(ne,M);break;case"zigzag_filter":Aje(ne);break;case"bitshuffle_filter":Pje(ne,k);break;default:throw new Ud(`Unhandled filter "${$[ce]}"`)}return{layerName:y,blockIndex:F,data:ne}}).catch(ne=>{throw ne})}))},Lr(uK,"MRTDecodingBatch",{omit:["_onCancel","_onComplete"]}),Lr(GA,"MapboxRasterTile"),Lr(cK,"MapboxRasterLayer",{omit:["_blocksInProgress"]});class dK{constructor(l){this._stringToNumber={},this._numberToString=[];for(let d=0;d=0&&H[3]>=0&&F.insert(M,H[0],H[1],H[2],H[3])}}loadVTLayers(){if(!this.vtLayers){this.vtLayers=new wt(new jA(this.rawTileData)).layers,this.sourceLayerCoder=new dK(this.vtLayers?Object.keys(this.vtLayers).sort():["_geojsonTileLayer"]),this.vtFeatures={};for(const l in this.vtLayers)this.vtFeatures[l]=[]}return this.vtLayers}query(l,d){const{tilespaceGeometry:p,transform:y,tileTransform:b,pixelPosMatrix:w,availableImages:k,worldview:M}=d;this.loadVTLayers(),this.serializedLayersCache.clear();const F=d.queryRadius?d.queryRadius:0,$=p.bufferedTilespaceBounds,U=this.grid.query($.min.x,$.min.y,$.max.x,$.max.y,(ne,ce,le,ye)=>Ll(p.bufferedTilespaceGeometry,ne-F,ce-F,le+F,ye+F));U.sort(qje);let H=null;y.elevation&&U.length>0&&(H=Gb.create(y.elevation,this.tileID));const Z={};let Y;for(let ne=0;ne(ye||(ye=Qe(we,this.tileID.canonical,b)),Ee.queryIntersectsFeature(p,we,Ue,ye,this.z,y,w,H,Le)))}return Z}loadMatchingFeature(l,d,p,y,b,w){const{featureIndex:k,bucketIndex:M,sourceLayerIndex:F,layoutVertexArrayOffset:$}=d,U=this.bucketLayerIDs[M],H=p.layers,Z=Object.keys(H);if(Z.length&&!Ir(Z,U))return;const Y=p.sourceCache,ne=this.sourceLayerCoder.decode(F),ce=this.vtLayers[ne].feature(k),le=this.getId(ce,ne);for(let ye=0;ye`${k.key}: ${k.message}`).join(", ");return void Ge(`Failed to create expression for promoteId: ${w}`)}this.promoteIdExpression=b.value}p=this.promoteIdExpression.evaluate({zoom:0},l)}else p=l.properties[y];typeof p=="boolean"&&(p=Number(p))}return p}}function fK(h,l,d,p,y){return St(h,(b,w)=>{const k=l instanceof Jp?l.get(w):null;return k&&k.evaluate?k.evaluate(d,p,void 0,y):k})}function qje(h,l){return l-h}Lr(hK,"FeatureIndex",{omit:["rawTileData","sourceLayerCoder"]});const pK=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];class tF{static from(l){if(!(l instanceof ArrayBuffer))throw new Error("Data must be an instance of ArrayBuffer.");const[d,p]=new Uint8Array(l,0,2);if(d!==219)throw new Error("Data does not appear to be in a KDBush format.");const y=p>>4;if(y!==1)throw new Error(`Got v${y} data when expected v1.`);const b=pK[15&p];if(!b)throw new Error("Unrecognized array type.");const[w]=new Uint16Array(l,2,1),[k]=new Uint32Array(l,4,1);return new tF(k,w,b,l)}constructor(l,d=64,p=Float64Array,y){if(isNaN(l)||l<0)throw new Error(`Unpexpected numItems value: ${l}.`);this.numItems=+l,this.nodeSize=Math.min(Math.max(+d,2),65535),this.ArrayType=p,this.IndexArrayType=l<65536?Uint16Array:Uint32Array;const b=pK.indexOf(this.ArrayType),w=2*l*this.ArrayType.BYTES_PER_ELEMENT,k=l*this.IndexArrayType.BYTES_PER_ELEMENT,M=(8-k%8)%8;if(b<0)throw new Error(`Unexpected typed array class: ${p}.`);y&&y instanceof ArrayBuffer?(this.data=y,this.ids=new this.IndexArrayType(this.data,8,l),this.coords=new this.ArrayType(this.data,8+k+M,2*l),this._pos=2*l,this._finished=!0):(this.data=new ArrayBuffer(8+w+k+M),this.ids=new this.IndexArrayType(this.data,8,l),this.coords=new this.ArrayType(this.data,8+k+M,2*l),this._pos=0,this._finished=!1,new Uint8Array(this.data,0,2).set([219,16+b]),new Uint16Array(this.data,2,1)[0]=d,new Uint32Array(this.data,4,1)[0]=l)}add(l,d){const p=this._pos>>1;return this.ids[p]=p,this.coords[this._pos++]=l,this.coords[this._pos++]=d,p}finish(){const l=this._pos>>1;if(l!==this.numItems)throw new Error(`Added ${l} items when expected ${this.numItems}.`);return rF(this.ids,this.coords,this.nodeSize,0,this.numItems-1,0),this._finished=!0,this}range(l,d,p,y){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:b,coords:w,nodeSize:k}=this,M=[0,b.length-1,0],F=[];for(;M.length;){const $=M.pop()||0,U=M.pop()||0,H=M.pop()||0;if(U-H<=k){for(let ce=H;ce<=U;ce++){const le=w[2*ce],ye=w[2*ce+1];le>=l&&le<=p&&ye>=d&&ye<=y&&F.push(b[ce])}continue}const Z=H+U>>1,Y=w[2*Z],ne=w[2*Z+1];Y>=l&&Y<=p&&ne>=d&&ne<=y&&F.push(b[Z]),($===0?l<=Y:d<=ne)&&(M.push(H),M.push(Z-1),M.push(1-$)),($===0?p>=Y:y>=ne)&&(M.push(Z+1),M.push(U),M.push(1-$))}return F}within(l,d,p){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:y,coords:b,nodeSize:w}=this,k=[0,y.length-1,0],M=[],F=p*p;for(;k.length;){const $=k.pop()||0,U=k.pop()||0,H=k.pop()||0;if(U-H<=w){for(let ce=H;ce<=U;ce++)gK(b[2*ce],b[2*ce+1],l,d)<=F&&M.push(y[ce]);continue}const Z=H+U>>1,Y=b[2*Z],ne=b[2*Z+1];gK(Y,ne,l,d)<=F&&M.push(y[Z]),($===0?l-p<=Y:d-p<=ne)&&(k.push(H),k.push(Z-1),k.push(1-$)),($===0?l+p>=Y:d+p>=ne)&&(k.push(Z+1),k.push(U),k.push(1-$))}return M}}function rF(h,l,d,p,y,b){if(y-p<=d)return;const w=p+y>>1;mK(h,l,w,p,y,b),rF(h,l,d,p,w-1,1-b),rF(h,l,d,w+1,y,1-b)}function mK(h,l,d,p,y,b){for(;y>p;){if(y-p>600){const F=y-p+1,$=d-p+1,U=Math.log(F),H=.5*Math.exp(2*U/3),Z=.5*Math.sqrt(U*H*(F-H)/F)*($-F/2<0?-1:1);mK(h,l,d,Math.max(p,Math.floor(d-$*H/F+Z)),Math.min(y,Math.floor(d+(F-$)*H/F+Z)),b)}const w=l[2*d+b];let k=p,M=y;for(JN(h,l,p,d),l[2*y+b]>w&&JN(h,l,p,y);kw;)M--}l[2*p+b]===w?JN(h,l,p,M):(M++,JN(h,l,M,y)),M<=d&&(p=M+1),d<=M&&(y=M-1)}}function JN(h,l,d,p){nF(h,d,p),nF(l,2*d,2*p),nF(l,2*d+1,2*p+1)}function nF(h,l,d){const p=h[l];h[l]=h[d],h[d]=p}function gK(h,l,d,p){const y=h-d,b=l-p;return y*y+b*b}a.$=k0,a.A=Nh,a.B=Ju,a.C=2,a.D=Ob,a.E=qp,a.F=ON,a.G=U9,a.H=C0,a.I=vl,a.J=zE,a.K=Wr,a.L=mg,a.M=X0,a.N=ev,a.O=CE,a.P=Wt,a.Q=tv,a.R=Mx,a.S=ob,a.T=d3,a.U=qf,a.V=zA,a.W=$S,a.X=_g,a.Y=vg,a.Z=Kx,a._=Ol,a.a=function(h){return is.API_CDN_URL_REGEX.test(h)},a.a$=ee,a.a0=_n,a.a1=xu,a.a2=Ld,a.a3=class extends zA{},a.a4=Q0,a.a5=NE,a.a6=yt,a.a7=function(h){const l=h.value;return l?_n(l)?U3(l,!0)?[]:[new zA(h.key,l,`invalid url "${l}"`)]:[new zA(h.key,l,`string expected, "${Wr(l)}" found`)]:[]},a.a8=RE,a.a9=ta,a.aA=ue,a.aB=R,a.aC=rr,a.aD=rl,a.aE=ci,a.aF=L,a.aG=Te,a.aH=function(h,l){const d={};for(let p=0;p{p(b,w)},l):p(b,w),()=>{}}return y.callbacks.push(p),y.cancel||(y.cancel=d((b,w)=>{y.result=[b,w];for(const k of y.callbacks)this.scheduler?this.scheduler.add(()=>{k(b,w)},l):k(b,w);setTimeout(()=>delete this.entries[h],3e3)})),()=>{y.result||(y.callbacks=y.callbacks.filter(b=>b!==p),y.callbacks.length||(y.cancel(),delete this.entries[h]))}}},a.aL=function(h,l,d){const p=JSON.stringify(h.request);return h.data&&(this.deduped.entries[p]={result:[null,h.data]}),this.deduped.request(p,{type:"parseTile",isSymbolTile:h.isSymbolTile,zoom:h.tileZoom},y=>{const b=Sh(h.request,(w,k,M)=>{w?y(w):k&&y(null,{rawData:k,vectorTile:d?void 0:new wt(new jA(k)),responseHeaders:new Map(M.entries())})});return()=>{b.cancel(),y()}},l)},a.aM=function(h){return h?{cacheControl:h.get("Cache-Control"),expires:h.get("Expires")}:{cacheControl:void 0,expires:void 0}},a.aN=jc,a.aO=function(h){yu++,yu>g0&&(h.getActor().send("enforceCacheSizeLimit",m0),yu=0)},a.aP=function(h){return h<=1?1:Math.pow(2,Math.floor(Math.log2(h)))},a.aQ=Ji,a.aR=y7,a.aS=j7,a.aT=f,a.aU=g7,a.aV=function(h,l){const d=document.createElement("video");d.muted=!0,d.onloadstart=function(){l(null,d)};for(let p=0;p{}}},a.aW=EN,a.aX=Nv,a.aY=dt,a.aZ=FN,a.a_=G,a.aa=hr,a.ab=class{constructor(h){this.specification=h}possiblyEvaluate(h,l){return Vr(h.expression.evaluate(l))}interpolate(h,l,d){return{x:fn(h.x,l.x,d),y:fn(h.y,l.y,d),z:fn(h.z,l.z,d),azimuthal:fn(h.azimuthal,l.azimuthal,d),polar:fn(h.polar,l.polar,d)}}},a.ac=wi,a.ad=Yp,a.ae=Ne,a.af=ut,a.ag=ge,a.ah=be,a.ai=Jp,a.aj=zg,a.ak=fn,a.al=mr,a.am=uS,a.an=Xn,a.ao=Us,a.ap=class{constructor(h){this.specification=h}possiblyEvaluate(h,l){return function([d,p]){const y=Vr([1,d,p]);return{x:y.x,y:y.y,z:y.z}}(h.expression.evaluate(l))}interpolate(h,l,d){return{x:fn(h.x,l.x,d),y:fn(h.y,l.y,d),z:fn(h.z,l.z,d)}}},a.aq=function(h,l,d=0,p=!0){const y=new Wt(d,d),b=h.sub(y),w=l.add(y),k=[b,new Wt(w.x,b.y),w,new Wt(b.x,w.y)];return p&&k.push(b.clone()),k},a.ar=function(h,l){const d=[];for(let p=0;p1)return!1;const d=l.getSource().maxzoom,p=1<1)return l;const y=p.getSource().maxzoom,b=1<{const k=this.getAtTileOffset(h,y,b,w),M=p.upVector(h.canonical,y.x,y.y);return Ye(M,M,k*p.upVectorScale(h.canonical,l,d).metersToTile),M}}getForTilePoints(h,l,d,p){if(this.isUsingMockSource())return!1;const y=Gb.create(this,h,p);return!!y&&(l.forEach(b=>{b[2]=this.exaggeration()*y.getElevationAt(b[0],b[1],d)}),!0)}getMinMaxForTile(h){if(this.isUsingMockSource())return null;const l=this.findDEMTileFor(h);if(!l||!l.dem)return null;const d=l.dem.tree,p=l.tileID,y=1<0&&(p+=(h[y]-0)*(h[y]-0)),l[y]<0&&(p+=(0-l[y])*(0-l[y]));return p},a.c0=yG,a.c1=C3,a.c2=Z9,a.c3=O3,a.c4=tF,a.c5=Ye,a.c6=rt,a.c7=kr,a.c8=function(h,l,d){d*=.5;var p=l[0],y=l[1],b=l[2],w=l[3],k=Math.sin(d),M=Math.cos(d);return h[0]=p*M+y*k,h[1]=y*M-p*k,h[2]=b*M+w*k,h[3]=w*M-b*k,h},a.c9=Hr,a.cA=pe,a.cB=Is,a.cC=t9,a.cD=ui,a.cE=IW,a.cF=function(h,l,d,p,y,b,w,k,M){if(M.name==="globe")return IW(h,l,new ui(d,p,y),!1);const F=FN({z:d,x:p,y},M);return new qr([(b+F.x/F.scale)*l,l*(F.y/F.scale),w],[(b+F.x2/F.scale)*l,l*(F.y2/F.scale),k])},a.cG=function(h,l,d){return h[0]=Math.min(l[0],d[0]),h[1]=Math.min(l[1],d[1]),h[2]=Math.min(l[2],d[2]),h[3]=Math.min(l[3],d[3]),h},a.cH=function(h,l,d){return h[0]=Math.max(l[0],d[0]),h[1]=Math.max(l[1],d[1]),h[2]=Math.max(l[2],d[2]),h[3]=Math.max(l[3],d[3]),h},a.cI=function(h){const l=Math.round((h+45+360)%360/90)%4;return Px[l]},a.cJ=re,a.cK=_t,a.cL=Pb,a.cM=function(h){const l=I(new Float64Array(16));R(l,h.pixelMatrix,h.globeMatrix);const d=[0,Su,0],p=[0,Nu,0];return ut(d,d,l),ut(p,p,l),[d[0]>0&&d[0]<=h.width&&d[1]>0&&d[1]<=h.height&&!U4(h,new f(h.center.lat,90)),p[0]>0&&p[0]<=h.width&&p[1]>0&&p[1]<=h.height&&!U4(h,new f(h.center.lat,-90))]},a.cN=function(h,l){const{scale:d}=h.tileTransform,p=d*mr/(h.tileSize*Math.pow(2,l.zoom-h.tileID.overscaledZ+h.tileID.canonical.z));return function(y,b,w){var k=b[1],M=b[2],F=b[3],$=w[0],U=w[1];return y[0]=b[0]*$,y[1]=k*$,y[2]=M*U,y[3]=F*U,y}(new Float32Array(4),l.inverseAdjustmentMatrix,[p,p])},a.cO=yA,a.cP=xe,a.cQ=e9,a.cR=function(h){const l=e9(h,!0);return _([],[l[0],l[1],l[4],l[5]])},a.cS=W,a.cT=Tr,a.cU=V,a.cV=function(h){const{x:l,y:d}=h.point,{lng:p,lat:y}=h._center;return RW(l,d,h.worldSize,p,y)},a.cW=et,a.cX=Bo,a.cY=Gi,a.cZ=Uo,a.c_=ju,a.ca=Zi,a.cb=function(h,l){return h[0]=-l[0],h[1]=-l[1],h[2]=-l[2],h[3]=l[3],h},a.cc=he,a.cd=function(h,l,d,p,y){var b=1/Math.tan(l/2);if(h[0]=b/d,h[1]=0,h[2]=0,h[3]=0,h[4]=0,h[5]=b,h[6]=0,h[7]=0,h[8]=0,h[9]=0,h[11]=-1,h[12]=0,h[13]=0,h[15]=0,y!=null&&y!==1/0){var w=1/(p-y);h[10]=(y+p)*w,h[14]=2*y*p*w}else h[10]=-1,h[14]=-2*p;return h},a.ce=function(h,l,d,p,y,b,w){var k=1/(l-d),M=1/(p-y),F=1/(b-w);return h[0]=-2*k,h[1]=0,h[2]=0,h[3]=0,h[4]=0,h[5]=-2*M,h[6]=0,h[7]=0,h[8]=0,h[9]=0,h[10]=2*F,h[11]=0,h[12]=(l+d)*k,h[13]=(y+p)*M,h[14]=(w+b)*F,h[15]=1,h},a.cf=q,a.cg=function(h,l,d){h[4*l+0]=d[0],h[4*l+1]=d[1],h[4*l+2]=d[2],h[4*l+3]=d[3]},a.ch=kb,a.ci=uv,a.cj=za,a.ck=Bd,a.cl=hv,a.cm=a7,a.cn=function(){var h=new g(4);return g!=Float32Array&&(h[1]=0,h[2]=0),h[0]=1,h[3]=1,h},a.co=function(h,l,d){var p=l[0],y=l[1],b=l[2],w=l[3],k=Math.sin(d),M=Math.cos(d);return h[0]=p*M+b*k,h[1]=y*M+w*k,h[2]=p*-k+b*M,h[3]=y*-k+w*M,h},a.cp=function(h,l){return h[0]===l[0]&&h[1]===l[1]&&h[2]===l[2]&&h[3]===l[3]},a.cq=Lt,a.cr=function(h){var l=h[0],d=h[1],p=h[2],y=h[3];return Math.sqrt(l*l+d*d+p*p+y*y)},a.cs=zo,a.ct=$t,a.cu=wa,a.cv=3,a.cw=2,a.cx=7,a.cy=6,a.cz=Pe,a.d=function(h){return is.API_TILEJSON_REGEX.test(h)},a.d$=class{constructor(h,l,d,p){this.context=h,this.format=p,this.size=d,this.texture=h.gl.createTexture();const[y,b,w]=this.size,{gl:k}=h;k.bindTexture(k.TEXTURE_3D,this.texture),h.pixelStoreUnpackFlipY.set(!1),h.pixelStoreUnpack.set(1),h.pixelStoreUnpackPremultiplyAlpha.set(!1),"data"in l&&l.data&&k.texImage3D(k.TEXTURE_3D,0,this.format,y,b,w,0,c3(this.format),u3(this.format),l.data)}bind(h,l){const{context:d}=this,{gl:p}=d;p.bindTexture(p.TEXTURE_3D,this.texture),h!==this.minFilter&&(p.texParameteri(p.TEXTURE_3D,p.TEXTURE_MAG_FILTER,h),p.texParameteri(p.TEXTURE_3D,p.TEXTURE_MIN_FILTER,h),this.minFilter=h),l!==this.wrapS&&(p.texParameteri(p.TEXTURE_3D,p.TEXTURE_WRAP_S,l),p.texParameteri(p.TEXTURE_3D,p.TEXTURE_WRAP_T,l),this.wrapS=l)}destroy(){const{gl:h}=this.context;h.deleteTexture(this.texture),this.texture=null}},a.d0=function(h){return h*h*h*h*h},a.d1=E,a.d2=45,a.d3=Tb,a.d4=function(h,l,d){const p=Math.sqrt(h*h+l*l+d*d),y=p>0?Math.acos(d/p)*oo:0;let b=h!==0||l!==0?Math.atan2(-l,-h)*oo+90:0;return b<0&&(b+=360),[p,b,y]},a.d5=ke,a.d6=Vr,a.d7=fe,a.d8=Se,a.d9=qr,a.dA=function(h){return h({pluginStatus:Rl,pluginURL:Ph}),ib.on("pluginStateChange",h),h},a.dB=dv,a.dC=class extends Oh{constructor(h){super(h),this.current=Eb}set(h,l,d){if(this.fetchUniformLocation(h,l)){for(let p=0;p<9;p++)if(d[p]!==this.current[p]){this.current=d,this.gl.uniformMatrix3fv(this.location,!1,d);break}}}},a.dD=jh,a.dE=function(h,l,d){const p=zg(d.zoom),y=h.style.map._antialias,b=h.terrain&&h.terrain.exaggeration()>0;return p===0&&!y&&!b},a.dF=function(h){const l=h.pixelsPerMeter,d=l/q(1,h.center.lat),p=I(new Float64Array(16));return z(p,p,[h.point.x,h.point.y,0]),W(p,p,[d,d,l]),Float32Array.from(p)},a.dG=tA,a.dH=function(h){const l=re-5;h=ue(h,-l,l)/l*90;const d=Math.pow(Math.abs(Math.sin(Xn(h))),3);return Math.round(d*(hN.length-1))},a.dI=function(h,l,d,p){const y=l.getNorth(),b=l.getSouth(),w=l.getWest(),k=l.getEast(),M=1<0){const Y=180/p;C(Z,Z,[Y/F+1,0,0,0,Y/$+1,0,-.5*Y/U,.5*Y/H,1])}return Z[2]=M,Z[5]=h.x,Z[8]=h.y,Z},a.dJ=rd,a.dK=function(h,l,d){const p=I(new Float64Array(16)),y=(l/(1<({u_matrix:new hv(h),u_texsize:new Bd(h),u_pixels_to_tile_units:new Ab(h),u_device_pixel_ratio:new za(h),u_width_scale:new za(h),u_floor_width_scale:new za(h),u_image:new kb(h),u_units_to_pixels:new Bd(h),u_tile_units_to_pixels:new za(h),u_alpha_discard_threshold:new za(h),u_trim_offset:new Bd(h),u_trim_fade_range:new Bd(h),u_trim_color:new Tb(h),u_zbias_factor:new za(h),u_tile_to_meter:new za(h),u_ground_shadow_factor:new uv(h),u_pattern_transition:new za(h)}),a.dX=h=>({u_matrix:new hv(h),u_pixels_to_tile_units:new Ab(h),u_device_pixel_ratio:new za(h),u_width_scale:new za(h),u_floor_width_scale:new za(h),u_units_to_pixels:new Bd(h),u_dash_image:new kb(h),u_gradient_image:new kb(h),u_image_height:new za(h),u_texsize:new Bd(h),u_tile_units_to_pixels:new za(h),u_alpha_discard_threshold:new za(h),u_trim_offset:new Bd(h),u_trim_fade_range:new Bd(h),u_trim_color:new Tb(h),u_zbias_factor:new za(h),u_tile_to_meter:new za(h),u_ground_shadow_factor:new uv(h)}),a.dY=h=>({u_camera_to_center_distance:new za(h),u_extrude_scale:new Ab(h),u_device_pixel_ratio:new za(h),u_matrix:new hv(h),u_inv_rot_matrix:new hv(h),u_merc_center:new Bd(h),u_tile_id:new uv(h),u_zoom_transition:new za(h),u_up_dir:new uv(h),u_emissive_strength:new za(h)}),a.dZ=xb,a.d_=t1e,a.da=je,a.db=function(h){return[Math.pow(h[0],1/2.2),Math.pow(h[1],1/2.2),Math.pow(h[2],1/2.2)]},a.dc=JG,a.dd=y3,a.de=s9,a.df=U3,a.dg=function(h,l){return h.readFields(eje,{icons:[]},l)},a.dh=fA,a.di=Vb,a.dj=P3,a.dk=v0,a.dl=sv,a.dm=hg,a.dn=b0,a.dp=Ut,a.dq=function(h){const l=h.indexOf(rm);return l>=0?h.slice(0,l):h},a.dr=function(h){return h.indexOf(rm)>=0},a.ds=function(h){const l=h.lastIndexOf(rm);return l>=0?h.slice(l+1):""},a.dt=function(h){const l=[],d=h.id;return d===void 0&&l.push({message:`layers.${d}: missing required property "id"`}),h.render===void 0&&l.push({message:`layers.${d}: missing required method "render"`}),h.renderingMode&&h.renderingMode!=="2d"&&h.renderingMode!=="3d"&&l.push({message:`layers.${d}: property "renderingMode" must be either "2d" or "3d"`}),l},a.du=function(h,l,d,p){return h.type==="custom"?new G1e(h,l):new Q1e[h.type](h,l,d,p)},a.dv=sr,a.dw=function(h){const l=h.indexOf(rm);return l>=0?h.slice(l+1):""},a.dx=class extends Sv{constructor(h,l){super(h._vectorTileFeature,h._z,h._x,h._y,h.id),h.state&&(this.state=Object.assign({},h.state)),this.target=l.target,this.namespace=l.namespace,l.properties&&(this.properties=l.properties),this.target&&("featuresetId"in this.target&&!this.target.importId||"layerId"in this.target)&&(this.source=h.source,this.sourceLayer=h.sourceLayer,this.layer=h.layer)}toJSON(){const h=super.toJSON();return h.target=this.target,h.namespace=this.namespace,h}},a.dy=ib,a.dz=Vp,a.e=is,a.e$=Ce,a.e0=FW,a.e1=(h,l,d,p,y,b)=>{const w=h.transform,k=w.projection.name==="globe";let M;if(b.paint.get("circle-pitch-alignment")==="map")if(k){const $=OW(w.zoom,l.canonical)*w._pixelsPerMercatorPixel;M=Float32Array.from([$,0,0,$])}else M=w.calculatePixelsToTileUnitsMatrix(d);else M=new Float32Array([w.pixelsToGLUnits[0],0,0,w.pixelsToGLUnits[1]]);const F={u_camera_to_center_distance:h.transform.getCameraToCenterDistance(w.projection),u_matrix:h.translatePosMatrix(l.projMatrix,d,b.paint.get("circle-translate"),b.paint.get("circle-translate-anchor")),u_device_pixel_ratio:lo.devicePixelRatio,u_extrude_scale:M,u_inv_rot_matrix:ybe,u_merc_center:[0,0],u_tile_id:[0,0,0],u_zoom_transition:0,u_up_dir:[0,0,0],u_emissive_strength:b.paint.get("circle-emissive-strength")};if(k){F.u_inv_rot_matrix=p,F.u_merc_center=y,F.u_tile_id=[l.canonical.x,l.canonical.y,1<{const $=h.transform,U=$.pitch<15?y9(.07,.7,ue((14-$.zoom)/5,0,1)):.07,H=d.paint.get("line-trim-color-use-theme").constantOr("default")==="none";return{u_matrix:v9(h,l,d,p),u_texsize:l.imageAtlasTexture?l.imageAtlasTexture.size:[0,0],u_pixels_to_tile_units:$.calculatePixelsToTileUnitsMatrix(l),u_device_pixel_ratio:y,u_width_scale:b,u_floor_width_scale:w,u_image:0,u_tile_units_to_pixels:x9(l,$),u_units_to_pixels:[1/$.pixelsToGLUnits[0],1/$.pixelsToGLUnits[1]],u_alpha_discard_threshold:0,u_trim_offset:k,u_trim_fade_range:d.paint.get("line-trim-fade-range"),u_trim_color:d.paint.get("line-trim-color").toPremultipliedRenderColor(H?null:d.lut).toArray01(),u_zbias_factor:U,u_tile_to_meter:fe(l.tileID.canonical,0),u_ground_shadow_factor:M,u_pattern_transition:F}},a.e5=(h,l,d,p,y,b,w,k,M,F)=>{const $=h.transform,U=$.calculatePixelsToTileUnitsMatrix(l),H=d.paint.get("line-trim-color-use-theme").constantOr("default")==="none",Z=$.pitch<15?y9(.07,.7,ue((14-$.zoom)/5,0,1)):.07;return{u_matrix:v9(h,l,d,p),u_pixels_to_tile_units:U,u_device_pixel_ratio:b,u_width_scale:w,u_floor_width_scale:k,u_units_to_pixels:[1/$.pixelsToGLUnits[0],1/$.pixelsToGLUnits[1]],u_dash_image:0,u_gradient_image:1,u_image_height:y,u_texsize:b9(d)&&l.lineAtlasTexture?l.lineAtlasTexture.size:[0,0],u_tile_units_to_pixels:x9(l,h.transform),u_alpha_discard_threshold:0,u_trim_offset:M,u_trim_fade_range:d.paint.get("line-trim-fade-range"),u_trim_color:d.paint.get("line-trim-color").toPremultipliedRenderColor(H?null:d.lut).toArray01(),u_zbias_factor:Z,u_tile_to_meter:fe(l.tileID.canonical,0),u_ground_shadow_factor:F}},a.e6=Ct,a.e7=pN,a.e8=J,a.e9=ku,a.eA=function(h,l){var d=2*Math.acos(l[3]),p=Math.sin(d/2);return p>m?(h[0]=l[0]/p,h[1]=l[1]/p,h[2]=l[2]/p):(h[0]=1,h[1]=0,h[2]=0),d},a.eB=H3,a.eC=_A,a.eD=vA,a.eE=[1,1,1],a.eF=Gb,a.eG=We,a.eH=function(h,l,d,p){var y=l[0],b=l[1],w=l[2],k=l[3];return h[0]=y+p*(d[0]-y),h[1]=b+p*(d[1]-b),h[2]=w+p*(d[2]-w),h[3]=k+p*(d[3]-k),h},a.eI=Fb,a.eJ=qc,a.eK=zd,a.eL=function(h,l,d,p,y,b,w,k,M,F,$,U,H,Z,Y,ne){var ce=new g(16);return ce[0]=h,ce[1]=l,ce[2]=d,ce[3]=p,ce[4]=y,ce[5]=b,ce[6]=w,ce[7]=k,ce[8]=M,ce[9]=F,ce[10]=$,ce[11]=U,ce[12]=H,ce[13]=Z,ce[14]=Y,ce[15]=ne,ce},a.eM=x,a.eN=Mg,a.eO=rN,a.eP=class{constructor(){this._updateTime=0,this._sourceIds=[],this._activeRegions=[],this._prevRegions=[],this._globalClipBounds={min:new Wt(1/0,1/0),max:new Wt(-1/0,-1/0)}}clear(){this._activeRegions.length>0&&++this._updateTime,this._activeRegions=[],this._prevRegions=[]}get updateTime(){return this._updateTime}getReplacementRegionsForTile(h,l=!1){const d=pG(new Wt(0,0),new Wt(mr,mr),h),p=[];if(l&&!X4(d,this._globalClipBounds))return p;for(const y of this._activeRegions){if(y.hiddenByOverlap||!X4(d,y))continue;const b=Wbe(y.min,y.max,h);p.push({min:b.min,max:b.max,sourceId:this._sourceIds[y.priority],footprint:y.footprint,footprintTileId:y.tileId,order:y.order,clipMask:y.clipMask,clipScope:y.clipScope})}return p}setSources(h){this._setSources(h.map(l=>({getSourceId:()=>l.cache.id,getFootprints:()=>{const d=[];for(const p of l.cache.getVisibleCoordinates()){const y=l.cache.getTile(p).buckets[l.layer];y&&y.updateFootprints(p.toUnwrapped(),d)}return d},getOrder:()=>l.order,getClipMask:()=>l.clipMask,getClipScope:()=>l.clipScope})))}_addSource(h){const l=h.getFootprints();if(l.length===0)return;const d=h.getOrder(),p=h.getClipMask(),y=h.getClipScope();for(const b of l){if(!b.footprint)continue;const w=pG(b.footprint.min,b.footprint.max,b.id);this._activeRegions.push({min:w.min,max:w.max,hiddenByOverlap:!1,priority:this._sourceIds.length,tileId:b.id,footprint:b.footprint,order:d,clipMask:p,clipScope:y})}this._sourceIds.push(h.getSourceId())}_computeReplacement(){this._activeRegions.sort((l,d)=>l.priority-d.priority||lA(l.min,d.min)||lA(l.max,d.max)||l.order-d.order||l.clipMask-d.clipMask||function(p,y){const b=(w,k)=>w+k;return p.length-y.length||p.reduce(b,"").localeCompare(y.reduce(b,""))}(l.clipScope,d.clipScope));let h=this._activeRegions.length!==this._prevRegions.length;if(!h){let l=0;for(;!h&&l!==this._activeRegions.length;){const d=this._activeRegions[l],p=this._prevRegions[l];h=d.priority!==p.priority||!fG(d,p)||d.order!==p.order||d.clipMask!==p.clipMask||!xo(d.clipScope,p.clipScope),this._activeRegions[l].hiddenByOverlap=p.hiddenByOverlap,++l}}if(h){++this._updateTime;for(const d of this._activeRegions)d.order!==_N&&(this._globalClipBounds.min.x=Math.min(this._globalClipBounds.min.x,d.min.x),this._globalClipBounds.min.y=Math.min(this._globalClipBounds.min.y,d.min.y),this._globalClipBounds.max.x=Math.max(this._globalClipBounds.max.x,d.max.x),this._globalClipBounds.max.y=Math.max(this._globalClipBounds.max.y,d.max.y));const l=d=>{const p=this._activeRegions;if(d>=p.length)return d;const y=p[d].priority;for(;d1){let d=0,p=l(d);for(;d!==p;){let y=d;const b=d;for(;y!==p;){const w=this._activeRegions[y];w.hiddenByOverlap=!1;for(let k=0;k=0;l--)this._addSource(h[l]);this._computeReplacement()}},a.eQ=_N,a.eR=class{constructor(h){this._createGrid(h),this._createPoles(h)}destroy(){this._poleIndexBuffer.destroy(),this._gridBuffer.destroy(),this._gridIndexBuffer.destroy(),this._poleNorthVertexBuffer.destroy(),this._poleSouthVertexBuffer.destroy();for(const h of this._poleSegments)h.destroy();for(const h of this._gridSegments)h.withSkirts.destroy(),h.withoutSkirts.destroy()}_fillGridMeshWithLods(h,l){const d=new Wf,p=new Fa,y=[],b=h+1+2,w=l[0]+1,k=l[0]+1+(1+l.length),M=(F,$,U)=>{let H=F===b-1?F-2:F===0?F:F-1;return H+=U?24575:0,[H,$]};for(let F=0;F0?(ce=2*Math.sqrt(ne+1),h[3]=.25*ce,h[0]=(U-Z)/ce,h[1]=(H-M)/ce,h[2]=(k-F)/ce):w>$&&w>Y?(ce=2*Math.sqrt(1+w-$-Y),h[3]=(U-Z)/ce,h[0]=.25*ce,h[1]=(k+F)/ce,h[2]=(H+M)/ce):$>Y?(ce=2*Math.sqrt(1+$-w-Y),h[3]=(H-M)/ce,h[0]=(k+F)/ce,h[1]=.25*ce,h[2]=(U+Z)/ce):(ce=2*Math.sqrt(1+Y-w-$),h[3]=(k-F)/ce,h[0]=(H+M)/ce,h[1]=(U+Z)/ce,h[2]=.25*ce),h},a.f=function(h){return btoa(encodeURIComponent(h).replace(/%([0-9A-F]{2})/g,(l,d)=>String.fromCharCode(+("0x"+d))))},a.f0=function([h,l,d]){const p=Math.hypot(h,l,d),y=Math.atan2(h,d),b=.5*Math.PI-Math.acos(-l/p);return new f(Bo(y),Bo(b))},a.f1=Gt,a.f2=h3,a.f3=function(h){const l=h.navigator?h.navigator.userAgent:null;return!!function(d){if(Mi==null){const p=d.navigator?d.navigator.userAgent:null;Mi=!!d.safari||!(!p||!(/\b(iPad|iPhone|iPod)\b/.test(p)||p.match("Safari")&&!p.match("Chrome")))}return Mi}(h)&&!(!l||!(l.match("Version/15.4")||l.match("Version/15.5")||l.match(/CPU (OS|iPhone OS) (15_4|15_5) like Mac OS X/)))},a.f4=function(h,l){m0=h,g0=l},a.f5=U4,a.f6=DW,a.f7=function(h){const l=[0,0,0],d=I(new Float64Array(16));return R(d,h.pixelMatrix,h.globeMatrix),ut(l,l,d),new Wt(l[0],l[1])},a.f8=function(){const h=CN;h&&(h.isPreloaded()&&h.numActive()===1?(h.release(n3),CN=null):console.warn("Could not clear WebWorkers since there are active Map instances that still reference it. The pre-warmed WebWorker pool can only be cleared when all map instances have been removed with map.remove()"))},a.f9=function(){fA().acquire(n3)},a.fA=WA,a.fB=ot,a.fC=function(h){let l=0;if(new Uint32Array(h,0,1)[0]!==KG){const d=new Uint32Array(h,0,7),[,,p,y,b,w]=d;l=d.byteLength+y+b+w+b,(p!==h.byteLength||l>=h.byteLength)&&Ge("Invalid b3dm header information.")}return QG(h,l)},a.fD=function(h,l){const d=y3(h);for(const p of d){for(const y of p.meshes)jwe(y);p.lights&&(p.lightMeshIndex=p.meshes.length,p.meshes.push(Swe(p.lights,l)))}return d},a.fE=BA,a.fF=cn,a.fG=VG,a.fH=Ih,a.fI=Sc,a.fJ=function(h){Ku(),Ed!=null&&Ed.then(l=>{l.keys().then(d=>{for(let p=0;pGe(y.message))}).catch(d=>Ge(d.message))}).catch(l=>Ge(l.message))},a.fa=iv,a.fb=function(h,l,d=!1){if(Rl===Sc.deferred||Rl===Sc.loading||Rl===Sc.loaded)throw new Error("setRTLTextPlugin cannot be called multiple times.");Ph=lo.resolveURL(h),Rl=Sc.deferred,HS=l,sb(),d||OE()},a.fc=function(h){Rb=lo.resolveURL(h),Db||(Db=new Ob(fA(),new qp)),Db.broadcast("setMeshoptUrl",Rb)},a.fd=WG,a.fe=function(h){a3=lo.resolveURL(h),Db||(Db=new Ob(fA(),new qp)),Db.broadcast("setDracoUrl",a3)},a.ff=HG,a.fg=NN,a.fh=function(h){const l=Gu();if(!l)return;const d=l.delete(p0);h&&d.then(()=>h()).catch(h)},a.fi=vv,a.fj=Lr,a.fk=Bg,a.fl=Vh,a.fm=dK,a.fn=hK,a.fo=f9,a.fp=Mt,a.fq="hd_road_elevation",a.fr=Ds,a.fs=St,a.ft=am,a.fu=A3,a.fv=wv,a.fw=function(h,l,d,p,y,b,w,k=1,M,F,$){h.createArrays(),h.tilePixelRatio=mr/(512*h.overscaling),h.compareText={},h.iconsNeedLinear=!1;const U=h.layers[0].layout,H=h.layers[0]._unevaluatedLayout._values,Z={};Z.scaleFactor=k,Z.textSizeScaleRange=U.get("text-size-scale-range"),Z.iconSizeScaleRange=U.get("icon-size-scale-range");const[Y,ne]=Z.textSizeScaleRange,[ce,le]=Z.iconSizeScaleRange;Z.textScaleFactor=ue(Z.scaleFactor,Y,ne),Z.iconScaleFactor=ue(Z.scaleFactor,ce,le);const ye=H["text-size"],we=H["icon-size"];if(h.textSizeData.kind==="composite"){const{minZoom:it,maxZoom:Pt}=h.textSizeData;Z.compositeTextSizes=[ye.possiblyEvaluate(new wi(it,{worldview:$}),b),ye.possiblyEvaluate(new wi(Pt,{worldview:$}),b)]}if(h.iconSizeData.kind==="composite"){const{minZoom:it,maxZoom:Pt}=h.iconSizeData;Z.compositeIconSizes=[we.possiblyEvaluate(new wi(it,{worldview:$}),b),we.possiblyEvaluate(new wi(Pt,{worldview:$}),b)]}Z.layoutTextSize=ye.possiblyEvaluate(new wi(w+1,{worldview:$}),b),Z.layoutIconSize=we.possiblyEvaluate(new wi(w+1,{worldview:$}),b),Z.textMaxSize=ye.possiblyEvaluate(new wi(18,{worldview:$}),b);const Ee=U.get("symbol-placement"),Ue=U.get("text-rotation-alignment")==="map"&&Ee!=="point",Le=U.get("text-size");let Ke=!1;const Je=[];for(const it of h.features){const Pt=U.get("text-font").evaluate(it,{},b).join(","),ft=Le.evaluate(it,{},b)*Z.textScaleFactor,Ft=Z.layoutTextSize.evaluate(it,{},b)*Z.textScaleFactor,Vt=Z.layoutIconSize.evaluate(it,{},b)*Z.iconScaleFactor,qt={horizontal:{},vertical:void 0},er=it.text;let nr,Yt=[0,0];if(er){const Tn=er.toString(),Js=U.get("text-letter-spacing").evaluate(it,{},b)*uo,Fe=U.get("text-line-height").evaluate(it,{},b)*uo,qe=VS(Tn)?Js:0,zt=U.get("text-anchor").evaluate(it,{},b),tr=U.get("text-variable-anchor");if(!tr){const kn=U.get("text-radial-offset").evaluate(it,{},b);if(kn)Yt=Z9(zt,[kn*uo,M3]);else{const In=U.get("text-offset").evaluate(it,{},b);Yt=[In[0]*uo,In[1]*uo]}}let Nr=Ue?"center":U.get("text-justify").evaluate(it,{},b);const Cr=Ee==="point",Kr=Cr?U.get("text-max-width").evaluate(it,{},b)*uo:1/0,Xr=kn=>{h.allowVerticalPlacement&&nv(Tn)&&(qt.vertical=N3(er,l,d,y,Pt,Kr,Fe,zt,kn,qe,Yt,Gc.vertical,!0,Ft,ft,M))};if(!Ue&&tr){const kn=Nr==="auto"?tr.map(zn=>O3(zn)):[Nr];let In=!1;for(let zn=0;zn=0||!nv(Tn)){const kn=N3(er,l,d,y,Pt,Kr,Fe,zt,Nr,qe,Yt,Gc.horizontal,!1,Ft,ft,M);kn&&(qt.horizontal[Nr]=kn)}Xr(Cr?"left":Nr)}}let Xt,Rt,It,Jt,gr,cr,Gr=!1;const Er=U.get("icon-text-fit").evaluate(it,{},b);if(it.icon&&it.icon.hasPrimary()){const Tn=DN(it.icon,h.iconSizeData,H["icon-size"],b,h.zoom,it,M,Z.iconScaleFactor,$);Xt=Tn.iconPrimary,It=Tn.iconSecondary;const Js=Xt.toString();if(Rt=p.get(Js),Rt&&(gr=U.get("icon-offset").evaluate(it,{},b),cr=U.get("icon-anchor").evaluate(it,{},b),nr=NA(y.get(Js),It?y.get(It.toString()):void 0,gr,cr),Gr=Rt.sdf,h.sdfIcons===void 0?h.sdfIcons=Rt.sdf:h.sdfIcons!==Rt.sdf&&Ge("Style sheet warning: Cannot mix SDF and non-SDF icons in one buffer"),(Rt.pixelRatio!==h.pixelRatio||U.get("icon-rotate").constantOr(1)!==0)&&(h.iconsNeedLinear=!0)),It){const Fe=It.toString();Jt=p.get(Fe)}}Ke=Ke||!(!it.icon||!it.icon.hasSecondary());const Or=AA(qt.horizontal)||qt.vertical;h.iconsInText||(h.iconsInText=!!Or&&Or.iconsInText);const Br=Ft*Z.textScaleFactor/uo,{defaultShapedIcon:$n,verticallyShapedIcon:dr}=I1e(h,nr,U,it,b,qt,Br,gr,Er);Er!=="none"&&nr&&(O9(nr)||R9(nr))&&(EA(0,Rt,Xt,nr,$n,Er,F,p,y),EA(0,Jt,It,nr,$n,Er,F,p,y),dr&&(EA(0,Rt,Xt,nr,dr,Er,F,p,y),EA(0,Jt,It,nr,dr,Er,F,p,y))),nr=$n;const{iconBBox:$r,iconVerticalBBox:wn,textBBox:ls,textVerticalBBox:hs}=k1e(h,nr,dr,U,it,b,Vt,gr,Z,y,cr,qt,Ft,Yt);Je.push({feature:it,shapedTextOrientations:qt,shapedText:Or,shapedIcon:nr,iconPrimary:Xt,iconSecondary:It,iconOffset:gr,iconAnchor:cr,verticallyShapedIcon:dr,layoutTextSize:Ft,layoutIconSize:Vt,textOffset:Yt,isSDFIcon:Gr,iconTextFit:Er,iconCollisionBounds:$r,iconVerticalCollisionBounds:wn,textCollisionBounds:ls,textVerticalCollisionBounds:hs})}return{featureData:Je,sizes:Z,hasAnySecondaryIcon:Ke,textAlongLine:Ue,symbolPlacement:Ee}},a.fx=V9,a.fy=function(h,l,d,p,y,b,w,k,M,F){h.iconAtlasPositions=F.iconPositions;const{featureData:$,hasAnySecondaryIcon:U,sizes:H,textAlongLine:Z,symbolPlacement:Y}=l;for(const ne of $){const{shapedIcon:ce,verticallyShapedIcon:le,feature:ye,shapedTextOrientations:we,shapedText:Ee,layoutTextSize:Ue,textOffset:Le,isSDFIcon:Ke,iconPrimary:Je,iconSecondary:it,iconTextFit:Pt,iconOffset:ft,iconCollisionBounds:Ft,iconVerticalCollisionBounds:Vt,textCollisionBounds:qt}=ne;X9(ce,F.iconPositions,Je,it),X9(le,F.iconPositions,Je,it),P1e(we,F.iconPositions),A1e(Je,it,F.iconPositions),(Ee||ce)&&M1e(h,ye,we,ce,le,M,H,Ue,0,Le,Ke,p,y,w,k,U,Pt,ft,Z,Y,Ft,Vt,qt)}d&&h.generateCollisionDebugBuffers(b,h.collisionBoxArray,H.textScaleFactor)},a.fz=wt,a.g=function(h,l){return Vp(Object.assign(h,{method:"GET"}),l)},a.h=function(h){return h.indexOf("mapbox:")===0},a.i=function(h){return is.API_STYLE_REGEX.test(h)&&!$o(h)},a.j=ca,a.k=Ad,a.l=function(h){return decodeURIComponent(atob(h).split("").map(l=>"%"+("00"+l.charCodeAt(0).toString(16)).slice(-2)).join(""))},a.m=function(h,l){return Vp(Object.assign(h,{type:"json"}),l)},a.n=_0,a.o=lo,a.p=function(h,l){return Vp(Object.assign(h,{method:"POST"}),l)},a.q=il,a.r=Td,a.s=function(h){try{const l=self[h];return l.setItem("_mapbox_test_",1),l.removeItem("_mapbox_test_"),!0}catch{return!1}},a.t=function(){return s3||(s3=new vv("ImageRasterizer")),s3},a.u=function(){return function h(l){return l?(l^Math.random()*(16>>l/4)).toString(16):([1e7]+-[1e3]+-4e3+-8e3+-1e11).replace(/[018]/g,h)}()},a.v=function(h){return!!h&&/^[0-9a-f]{8}-[0-9a-f]{4}-[4][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(h)},a.w=Ge,a.x=X3,a.y=Lx,a.z=Pd}),o(["./shared"],function(a){function m(vt){const ue=vt?vt.url.toString():void 0;return ue?performance.getEntriesByName(ue):[]}function g(vt){if(typeof vt=="number"||typeof vt=="boolean"||typeof vt=="string"||vt==null)return JSON.stringify(vt);if(Array.isArray(vt)){let be="[";for(const Re of vt)be+=`${g(Re)},`;return`${be}]`}let ue="{";for(const be of Object.keys(vt).sort())ue+=`${be}:${g(vt[be])},`;return`${ue}}`}function _(vt){let ue="";for(const be of a.bx)ue+=`/${g(vt[be])}`;return ue}class j{constructor(ue){this.keyCache={},this._layers={},this._layerConfigs={},ue&&this.replace(ue)}replace(ue,be){this._layerConfigs={},this._layers={},this.update(ue,[],be)}update(ue,be,Re){this._options=Re;for(const Xe of ue)this._layerConfigs[Xe.id]=Xe,(this._layers[Xe.id]=a.du(Xe,this.scope,null,this._options)).compileFilter(Re),this.keyCache[Xe.id]&&delete this.keyCache[Xe.id];for(const Xe of be)delete this.keyCache[Xe],delete this._layerConfigs[Xe],delete this._layers[Xe];this.familiesBySource={};const tt=function(Xe,lt){const Ct={};for(let St=0;Stthis._layers[Ir.id]),Ct=lt[0];if(Ct.visibility==="none")continue;const dt=Ct.source||"";let St=this.familiesBySource[dt];St||(St=this.familiesBySource[dt]={});const sr=Ct.sourceLayer||"_geojsonTileLayer";let Ut=St[sr];Ut||(Ut=St[sr]=[]),Ut.push(lt)}}}const N=1*a.fl;class C{constructor(ue){const be={},Re=[];for(const Ct in ue){const dt=ue[Ct],St=be[Ct]={};for(const sr in dt.glyphs){const Ut=dt.glyphs[+sr];if(!Ut||Ut.bitmap.width===0||Ut.bitmap.height===0)continue;const Ir=Ut.metrics.localGlyph?N:1,en={x:0,y:0,w:Ut.bitmap.width+2*Ir,h:Ut.bitmap.height+2*Ir};Re.push(en),St[sr]=en}}const{w:tt,h:Xe}=a.G(Re),lt=new a.fk({width:tt||1,height:Xe||1});for(const Ct in ue){const dt=ue[Ct];for(const St in dt.glyphs){const sr=dt.glyphs[+St];if(!sr||sr.bitmap.width===0||sr.bitmap.height===0)continue;const Ut=be[Ct][St],Ir=sr.metrics.localGlyph?N:1;a.fk.copy(sr.bitmap,lt,{x:0,y:0},{x:Ut.x+Ir,y:Ut.y+Ir},sr.bitmap)}}this.image=lt,this.positions=be}}function P(vt,ue,be){vt[ue]?be&&(vt[ue].center=be):vt[ue]={floorIds:new Set,center:be||[0,0],floors:{}}}function A(vt,ue,be,Re){for(const tt of ue)P(vt,tt),vt[tt].floors[be]=Re,vt[tt].floorIds.add(be)}function I(vt){return{id:vt.properties.id.toString(),center:vt.properties.center.toString().split(";").map(Number)}}function O(vt){return{id:vt.properties.id.toString(),isDefault:!!vt.properties.is_default&&vt.properties.is_default,connections:vt.properties.connected_floor_ids?new Set(vt.properties.connected_floor_ids.toString().split(";")):new Set,conflicts:vt.properties.conflicted_floor_ids?new Set(vt.properties.conflicted_floor_ids.toString().split(";")):new Set,buildings:vt.properties.building_ids?new Set(vt.properties.building_ids.toString().split(";")):new Set,name:vt.properties.name.toString(),zIndex:vt.properties.z_index}}function R(vt,ue){return ue.every(be=>vt.properties&&vt.properties[be]!=null)}function z(vt){return R(vt,["type","id","name"])&&vt.properties.type==="building"}function W(vt){return R(vt,["type","id","name","z_index"])&&vt.properties.type==="floor"}a.fj(C,"GlyphAtlas");class V{constructor(ue){this.tileID=new a.aQ(ue.tileID.overscaledZ,ue.tileID.wrap,ue.tileID.canonical.z,ue.tileID.canonical.x,ue.tileID.canonical.y),this.tileZoom=ue.tileZoom,this.uid=ue.uid,this.zoom=ue.zoom,this.lut=ue.lut,this.canonical=ue.tileID.canonical,this.pixelRatio=ue.pixelRatio,this.tileSize=ue.tileSize,this.source=ue.source,this.scope=ue.scope,this.overscaling=this.tileID.overscaleFactor(),this.showCollisionBoxes=ue.showCollisionBoxes,this.collectResourceTiming=!!ue.request&&ue.request.collectResourceTiming,this.promoteId=ue.promoteId,this.isSymbolTile=ue.isSymbolTile,this.tileTransform=a.aZ(ue.tileID.canonical,ue.projection),this.projection=ue.projection,this.worldview=ue.worldview,this.localizableLayerIds=ue.localizableLayerIds,this.brightness=ue.brightness,this.extraShadowCaster=!!ue.extraShadowCaster,this.tessellationStep=ue.tessellationStep,this.scaleFactor=ue.scaleFactor,this.worldview=ue.worldview,this.indoor=ue.indoor}parse(ue,be,Re,tt,Xe,lt){this.status="parsing",this.data=ue,this.collisionBoxArray=new a.b3;const Ct=new a.fm(Object.keys(ue.layers).sort()),dt=new a.fn(this.tileID,this.promoteId);dt.bucketLayerIDs=[];const St={},sr=new a.fo(256,256),Ut={featureIndex:dt,iconDependencies:new Map,patternDependencies:new Map,glyphDependencies:{},lineAtlas:sr,availableImages:Re,brightness:this.brightness,scaleFactor:this.scaleFactor,elevationFeatures:void 0,activeFloors:void 0};if(this.indoor){const ur=this.indoor.indoorState.activeFloorsVisible,jr=function(Vr,cn,Ns){const Mi=function(Yi,_s){if(!Yi)return a.w("No source layers defined in indoor specification"),_s;if(Yi.size===0)return _s;const Xi=Yi.difference(_s);for(const gi of Xi)a.w(`Missing source layer required in indoor specification: ${gi}`);return _s.intersection(_s)}(cn.sourceLayers,new Set(Object.keys(Vr.layers))),Zi=cn.indoorState,Oa=function(Yi,_s,Xi,gi){const is=new Set,ca=new Set,$o=new Set,el=new Map,rc={},zp=vo=>{const Bc=el.get(vo)||new Set;for(const xl of is)if((el.get(xl)||new Set).has(vo)||Bc.has(xl))return!0;return!1};for(const vo of _s){const Bc=Yi.layers[vo];if(Bc)for(let xl=0;xl=Xi.maxzoom||Xi.visibility==="none")continue;K(_s,this.zoom,Ut.brightness,Re,this.worldview);const gi=St[Xi.id]=Xi.createBucket({index:dt.bucketLayerIDs.length,layers:_s,zoom:this.zoom,lut:this.lut,canonical:this.canonical,pixelRatio:this.pixelRatio,overscaling:this.overscaling,collisionBoxArray:this.collisionBoxArray,sourceLayerIndex:Mi,sourceID:this.source,projection:this.projection.spec,tessellationStep:this.tessellationStep,styleDefinedModelURLs:tt,worldview:this.worldview,localizable:Oa});dt.bucketLayerIDs.push(_s.map(ca=>a.B(ca.id,ca.scope)));let is=gi.prepare?gi.prepare():null;is!=null?(is=is.then(()=>gi.populate(Zi,Ut,this.tileID.canonical,this.tileTransform)),Ir.push(is)):gi.populate(Zi,Ut,this.tileID.canonical,this.tileTransform)}}const Ge=()=>{let ur,jr,Vr,cn,Ns,Mi;sr.trim();const Zi={type:"maybePrepare",isSymbolTile:this.isSymbolTile,zoom:this.zoom},Oa=()=>{if(ur)return this.status="done",lt(ur);if(this.extraShadowCaster)this.status="done",lt(null,{buckets:Object.values(St).filter(_s=>!_s.isEmpty()),featureIndex:dt,collisionBoxArray:null,glyphAtlasImage:null,lineAtlas:null,imageAtlas:null,brightness:Ut.brightness,glyphMap:null,iconMap:null,glyphPositions:null});else if(jr&&Vr&&cn){const _s=new C(jr),Xi=new Map;for(const[ca,$o]of Vr.entries()){const{imagePosition:el}=a.fu(ca,$o,a.fv);Xi.set(ca,el)}const gi={};for(const ca in St){const $o=St[ca];$o instanceof a.b4&&(K($o.layers,this.zoom,Ut.brightness,Re,this.worldview),gi[ca]=a.fw($o,jr,_s.positions,Vr,Xi,this.tileID.canonical,this.tileZoom,this.scaleFactor,this.pixelRatio,Ns,this.worldview))}const is={iconsPending:!0,patternsPending:!0};this.rasterizeIfNeeded(Xe,Vr,Ns,()=>{is.iconsPending=!1,Yi(gi,_s,is)}),this.rasterizeIfNeeded(Xe,cn,Mi,()=>{is.patternsPending=!1,Yi(gi,_s,is)})}},Yi=(_s,Xi,gi,is)=>{if(gi.iconsPending||gi.patternsPending)return;const ca=new a.fx(Vr,cn,this.lut);for(const $o in St){const el=St[$o];if($o in _s)a.fy(el,_s[$o],this.showCollisionBoxes,Re,this.tileID.canonical,this.tileZoom,this.projection,this.brightness,Vr,ca);else if(el.hasPattern&&(el instanceof a.ba||el instanceof a.bb||el instanceof a.ea)){K(el.layers,this.zoom,Ut.brightness,Re,this.worldview);const rc=Object.fromEntries(ca.patternPositions);el.addFeatures(Ut,this.tileID.canonical,rc,Re,this.tileTransform,this.brightness)}}this.status="done",lt(null,{buckets:Object.values(St).filter($o=>!$o.isEmpty()),featureIndex:dt,collisionBoxArray:this.collisionBoxArray,glyphAtlasImage:Xi.image,lineAtlas:sr,imageAtlas:ca,brightness:Ut.brightness})};if(!this.extraShadowCaster){const _s=a.fs(Ut.glyphDependencies,is=>Object.keys(is).map(Number));Object.keys(_s).length?Xe.send("getGlyphs",{uid:this.uid,stacks:_s},(is,ca)=>{ur||(ur=is,jr=ca,Oa())},void 0,!1,Zi):jr={};const Xi=Array.from(Ut.iconDependencies.keys()).map(is=>a.I.parse(is));Xi.length?Xe.send("getImages",{images:Xi,source:this.source,scope:this.scope,tileID:this.tileID,type:"icons"},(is,ca)=>{ur||(ur=is,Vr=new Map,Ns=this.updateImageMapAndGetImageTaskQueue(Vr,ca,Ut.iconDependencies),Oa())},void 0,!1,Zi):(Vr=new Map,Ns=new Map);const gi=Array.from(Ut.patternDependencies.keys()).map(is=>a.I.parse(is));gi.length?Xe.send("getImages",{images:gi,source:this.source,scope:this.scope,tileID:this.tileID,type:"patterns"},(is,ca)=>{ur||(ur=is,cn=new Map,Mi=this.updateImageMapAndGetImageTaskQueue(cn,ca,Ut.patternDependencies),Oa())},void 0,!1,Zi):(cn=new Map,Mi=new Map)}if(Ut.elevationFeatures&&Ut.elevationFeatures.length>0){const _s=[];for(const gi of Object.values(St))if(gi instanceof a.bb){const is=gi.getUnevaluatedPortalGraph();is&&_s.push(is)}const Xi=a.ft.evaluate(_s);for(const gi of Object.values(St))if(gi instanceof a.bb){const is=ue.layers[Ct.decode(gi.sourceLayerIndex)];gi.setEvaluatedPortalGraph(Xi,is,this.tileID.canonical,Ut.availableImages,Ut.brightness)}}Oa()};Ir.length>0?Promise.allSettled(Ir).then(Ge).catch(lt):Ge()}updateParameters(ue){this.scaleFactor=ue.scaleFactor,this.showCollisionBoxes=ue.showCollisionBoxes,this.projection=ue.projection,this.brightness=ue.brightness,this.tileTransform=a.aZ(ue.tileID.canonical,ue.projection),this.extraShadowCaster=ue.extraShadowCaster,this.lut=ue.lut,this.worldview=ue.worldview,this.indoor=ue.indoor}rasterizeIfNeeded(ue,be,Re,tt){Array.from(be.values()).some(Xe=>Xe.usvg)?this.rasterize(ue,be,Re,tt):tt()}updateImageMapAndGetImageTaskQueue(ue,be,Re){const tt=new Map;for(const Xe of be.keys()){const lt=Re.get(Xe)||[];for(const Ct of lt){const dt=Ct.toString(),St=be.get(Ct.id.toString());St.usvg?tt.has(dt)||(tt.set(dt,Ct),ue.set(dt,Object.assign({},St))):ue.set(dt,St)}}return tt}rasterize(ue,be,Re,tt){this.rasterizeTask=ue.send("rasterizeImages",{scope:this.scope,tasks:Re},(Xe,lt)=>{if(!Xe)for(const[Ct,dt]of lt.entries()){const St=Object.assign(be.get(Ct),{data:dt});be.set(Ct,St)}tt()})}cancelRasterize(){this.rasterizeTask&&this.rasterizeTask.cancel()}}function K(vt,ue,be,Re,tt){const Xe=new a.ac(ue,{brightness:be,worldview:tt});for(const lt of vt)lt.recalculate(Xe,Re)}class Q extends a.E{constructor(ue,be,Re,tt,Xe,lt,Ct){super(),this.actor=ue,this.layerIndex=be,this.availableImages=Re,this.availableModels=tt,this.loadVectorData=lt||a.aL,this.loading={},this.loaded={},this.deduped=new a.aK(ue.scheduler),this.isSpriteLoaded=Xe,this.scheduler=ue.scheduler,this.brightness=Ct}loadTile(ue,be){const Re=ue.uid,tt=ue&&ue.request,Xe=tt&&tt.collectResourceTiming,lt=this.loading[Re]=new V(ue);lt.abort=this.loadVectorData(ue,(Ct,dt)=>{const St=!this.loading[Re];if(delete this.loading[Re],lt.cancelRasterize(),St||Ct||!dt)return lt.status="done",St||(this.loaded[Re]=lt),be(Ct);const sr=dt.rawData,Ut={},Ir=a.aM(dt.responseHeaders);Ir&&Ir.expires&&(Ut.expires=Ir.expires),Ir&&Ir.cacheControl&&(Ut.cacheControl=Ir.cacheControl),lt.vectorTile=dt.vectorTile||new a.fz(new a.bt(sr));const en=()=>{lt.parse(lt.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,(Ge,ur)=>{if(Ge||!ur)return be(Ge);const jr={};if(Xe){const Vr=m(tt);Vr.length>0&&(jr.resourceTiming=JSON.parse(JSON.stringify(Vr)))}be(null,Object.assign({rawTileData:sr.slice(0),responseHeaders:dt.responseHeaders},ur,Ut,jr))})};this.isSpriteLoaded?en():this.once("isSpriteLoaded",()=>{this.scheduler?this.scheduler.add(en,{type:"parseTile",isSymbolTile:ue.isSymbolTile,zoom:ue.tileZoom}):en()}),this.loaded=this.loaded||{},this.loaded[Re]=lt})}reloadTile(ue,be){const Re=this.loaded,tt=ue.uid;if(Re&&Re[tt]){const Xe=Re[tt];Xe.updateParameters(ue);const lt=(Ct,dt)=>{const St=Xe.reloadCallback;St&&(delete Xe.reloadCallback,Xe.parse(Xe.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,St)),be(Ct,dt)};Xe.status==="parsing"?Xe.reloadCallback=lt:Xe.status==="done"&&(Xe.vectorTile?Xe.parse(Xe.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,lt):lt())}else be(null,void 0)}abortTile(ue,be){const Re=ue.uid,tt=this.loading[Re];tt&&(tt.abort&&tt.abort(),delete this.loading[Re]),be()}removeTile(ue,be){const Re=this.loaded,tt=ue.uid;Re&&Re[tt]&&delete Re[tt],be()}}class te{loadTile(ue,be){const{uid:Re,encoding:tt,rawImageData:Xe,padding:lt}=ue,Ct=ImageBitmap&&Xe instanceof ImageBitmap?this.getImageData(Xe,lt):Xe;be(null,new a.fA(Re,Ct,tt,lt<1))}reloadTile(ue,be){be(null,null)}abortTile(ue,be){be()}removeTile(ue,be){be()}getImageData(ue,be){this.offscreenCanvas&&this.offscreenCanvasContext||(this.offscreenCanvas=new OffscreenCanvas(ue.width,ue.height),this.offscreenCanvasContext=this.offscreenCanvas.getContext("2d",{willReadFrequently:!0})),this.offscreenCanvas.width=ue.width,this.offscreenCanvas.height=ue.height,this.offscreenCanvasContext.drawImage(ue,0,0,ue.width,ue.height);const Re=this.offscreenCanvasContext.getImageData(-be,-be,ue.width+2*be,ue.height+2*be);return this.offscreenCanvasContext.clearRect(0,0,this.offscreenCanvas.width,this.offscreenCanvas.height),Re}}a.bs.setPbf(a.bt);class X{constructor(ue){this._mrt=new a.bs(ue.partial?30:1/0),this._isHeaderLoaded=!1,this.uid=ue.uid,this.tileID=ue.tileID,this.source=ue.source}parse(ue,be){const Re=this._mrt;this.status="parsing",this._entireBuffer=ue;try{Re.parseHeader(ue),this._isHeaderLoaded=!0;const tt=[];for(const Xe in Re.layers){const lt=Re.getLayer(Xe),Ct=lt.getDataRange(lt.getBandList()),dt=Re.createDecodingTask(Ct),St=ue.slice(Ct.firstByte,Ct.lastByte+1),sr=a.bs.performDecoding(St,dt).then(Ut=>dt.complete(null,Ut)).catch(Ut=>dt.complete(Ut,null));tt.push(sr)}Promise.allSettled(tt).then(()=>be(null,Re)).catch(Xe=>be(Xe))}catch(tt){be(tt)}}}class ie{constructor(ue){this.actor=ue,this.loading={},this.loaded={}}loadTile(ue,be){const Re=ue.uid,tt=ue.request,Xe=this.loading[Re]=new X(ue),{cancel:lt}=a.bu(tt,(Ct,dt,St)=>{const sr=!this.loading[Re];if(delete this.loading[Re],sr||Ct||!dt)return Xe.status="done",sr||(this.loaded[Re]=Xe),be(Ct);Xe.parse(dt,(Ut,Ir)=>{if(Ut||!Ir)return be(Ut);be(null,Ir,St)}),this.loaded[Re]=Xe});Xe.abort=lt}reloadTile(ue,be){be(null,void 0)}abortTile(ue,be){const Re=ue.uid,tt=this.loading[Re];tt&&(tt.abort&&tt.abort(),delete this.loading[Re]),be()}removeTile(ue,be){const Re=ue.uid;this.loaded[Re]&&delete this.loaded[Re],be()}decodeRasterArray(ue,be){a.bs.performDecoding(ue.buffer,ue.task).then(Re=>be(null,Re)).catch(Re=>be(Re))}}const he=a.fB.prototype.toGeoJSON;class xe{constructor(ue){this._feature=ue,this.extent=a.al,this.type=ue.type,this.properties=ue.tags,"id"in ue&&!isNaN(ue.id)&&(this.id=parseInt(ue.id,10))}loadGeometry(){if(this._feature.type===1){const ue=[];for(const be of this._feature.geometry)ue.push([new a.P(be[0],be[1])]);return ue}{const ue=[];for(const be of this._feature.geometry){const Re=[];for(const tt of be)Re.push(new a.P(tt[0],tt[1]));ue.push(Re)}return ue}}toGeoJSON(ue,be,Re){return he.call(this,ue,be,Re)}}class pe{constructor(ue,be){this.name=ue,this.extent=a.al,this.length=be.length,this._jsonFeatures=be}feature(ue){return new xe(this._jsonFeatures[ue])}}class ve{constructor(ue){this.layers={},this.extent=a.al;for(const be of Object.keys(ue))this.layers[be]=new pe(be,ue[be])}}const ge=64/4096,ke=128;class Ce{constructor(){this.features=new Map}clear(){this.features.clear()}load(ue=[],be){for(const Re of ue){const tt=Re.id;if(tt==null)continue;let Xe=this.features.get(tt);Xe&&this.updateCache(Xe,be),Re.geometry?(Xe=je(Re),this.updateCache(Xe,be),this.features.set(tt,Xe)):this.features.delete(tt),this.updateCache(Xe,be)}}updateCache(ue,be){for(const{canonical:Re,uid:tt}of Object.values(be)){const{z:Xe,x:lt,y:Ct}=Re;Se(ue,Math.pow(2,Xe),lt,Ct)&&delete be[tt]}}getTile(ue,be,Re){const tt=Math.pow(2,ue),Xe=[];for(const lt of this.features.values())Se(lt,tt,be,Re)&&Xe.push(Ye(lt,tt,be,Re));return{features:Xe}}getFeatures(){return[...this.features.values()]}}function Se({minX:vt,minY:ue,maxX:be,maxY:Re},tt,Xe,lt){return vt<(Xe+1+ge)/tt&&ue<(lt+1+ge)/tt&&be>(Xe-ge)/tt&&Re>(lt-ge)/tt}function je(vt){const{id:ue,geometry:be,properties:Re}=vt;if(!be)return;if(be.type==="GeometryCollection")throw new Error("GeometryCollection not supported in dynamic mode.");const{type:tt,coordinates:Xe}=be,lt={id:ue,type:1,geometry:[],tags:Re,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0},Ct=lt.geometry;if(tt==="Point")et(Xe,Ct,lt);else if(tt==="MultiPoint")for(const dt of Xe)et(dt,Ct,lt);else if(tt==="LineString")lt.type=2,bt(Xe,Ct,lt);else if(tt==="MultiLineString")lt.type=2,_e(Xe,Ct,lt);else if(tt==="Polygon")lt.type=3,_e(Xe,Ct,lt,!0);else{if(tt!=="MultiPolygon")throw new Error("Input data is not a valid GeoJSON object.");lt.type=3;for(const dt of Xe)_e(dt,Ct,lt,!0)}return lt}function et([vt,ue],be,Re){const tt=a.aF(vt);let Xe=a.aJ(ue);Xe=Xe<0?0:Xe>1?1:Xe,be.push(tt,Xe),Re.minX=Math.min(Re.minX,tt),Re.minY=Math.min(Re.minY,Xe),Re.maxX=Math.max(Re.maxX,tt),Re.maxY=Math.max(Re.maxY,Xe)}function bt(vt,ue,be,Re=!1,tt=!1){const Xe=[];for(const lt of vt)et(lt,Xe,be);ue.push(Xe),Re&&function(lt,Ct){let dt=0;for(let St=0,sr=lt.length,Ut=sr-2;St0===Ct)for(let St=0,sr=lt.length;St=lt&&Ut>=lt||(St>=lt?(sr+=Math.round(Ge*((lt-St)/en)),St=lt):Ut>=lt&&(Ir=sr+Math.round(Ge*((lt-St)/en)),Ut=lt),sr>=lt&&Ir>=lt||(sr>=lt?(St+=Math.round(en*((lt-sr)/Ge)),sr=lt):Ir>=lt&&(Ut=St+Math.round(en*((lt-sr)/Ge)),Ir=lt),Ct&&St===Ct[Ct.length-1][0]&&sr===Ct[Ct.length-1][1]||(Ct=[[St,sr]],tt.push(Ct)),Ct.push([Ut,Ir])))))}}function nt(vt,ue,be,Re,tt){const Xe=(be-ge)/ue,lt=(Re-ge)/ue,Ct=(be+1+ge)/ue,dt=(Re+1+ge)/ue;function St(Ir,en){let Ge=0;return IrCt&&(Ge|=2),endt&&(Ge|=8),Ge}let sr=[];for(let Ir=1;Ir<=8;Ir*=2){let en=vt[vt.length-2],Ge=vt[vt.length-1],ur=!(St(en,Ge)&Ir);for(let jr=0;jr>31}function Be(vt,ue){const{geometry:be,type:Re}=vt;let tt=0,Xe=0;if(Re===1){ue.writeVarint(Oe(1,be.length));for(const lt of be){const Ct=lt[0]-tt,dt=lt[1]-Xe;ue.writeVarint(Ie(Ct)),ue.writeVarint(Ie(dt)),tt+=Ct,Xe+=dt}}else for(const lt of be){ue.writeVarint(Oe(1,1));const Ct=lt.length-(Re===3?1:0);for(let dt=0;dtvt},jt=Math.fround||($t=new Float32Array(1),vt=>($t[0]=+vt,$t[0]));var $t;const Ht=3,Lt=5,Kt=6;class Ar{constructor(ue){this.options=Object.assign(Object.create(ut),ue),this.trees=new Array(this.options.maxZoom+1),this.stride=this.options.reduce?7:6,this.clusterProps=[]}load(ue){const{log:be,minZoom:Re,maxZoom:tt}=this.options;be&&console.time("total time");const Xe=`prepare ${ue.length} points`;be&&console.time(Xe),this.points=ue;const lt=[];for(let dt=0;dt=Re;dt--){const St=+Date.now();Ct=this.trees[dt]=this._createTree(this._cluster(Ct,dt)),be&&console.log("z%d: %d clusters in %dms",dt,Ct.numItems,+Date.now()-St)}return be&&console.timeEnd("total time"),this}getClusters(ue,be){let Re=((ue[0]+180)%360+360)%360-180;const tt=Math.max(-90,Math.min(90,ue[1]));let Xe=ue[2]===180?180:((ue[2]+180)%360+360)%360-180;const lt=Math.max(-90,Math.min(90,ue[3]));if(ue[2]-ue[0]>=360)Re=-180,Xe=180;else if(Re>Xe){const Ut=this.getClusters([Re,tt,180,lt],be),Ir=this.getClusters([-180,tt,Xe,lt],be);return Ut.concat(Ir)}const Ct=this.trees[this._limitZoom(be)],dt=Ct.range(_t(Re),Gt(lt),_t(Xe),Gt(tt)),St=Ct.data,sr=[];for(const Ut of dt){const Ir=this.stride*Ut;sr.push(St[Ir+Lt]>1?rt(St,Ir,this.clusterProps):this.points[St[Ir+Ht]])}return sr}getChildren(ue){const be=this._getOriginId(ue),Re=this._getOriginZoom(ue),tt="No cluster with the specified id.",Xe=this.trees[Re];if(!Xe)throw new Error(tt);const lt=Xe.data;if(be*this.stride>=lt.length)throw new Error(tt);const Ct=this.options.radius/(this.options.extent*Math.pow(2,Re-1)),dt=Xe.within(lt[be*this.stride],lt[be*this.stride+1],Ct),St=[];for(const sr of dt){const Ut=sr*this.stride;lt[Ut+4]===ue&&St.push(lt[Ut+Lt]>1?rt(lt,Ut,this.clusterProps):this.points[lt[Ut+Ht]])}if(St.length===0)throw new Error(tt);return St}getLeaves(ue,be,Re){const tt=[];return this._appendLeaves(tt,ue,be=be||10,Re=Re||0,0),tt}getTile(ue,be,Re){const tt=this.trees[this._limitZoom(ue)],Xe=Math.pow(2,ue),{extent:lt,radius:Ct}=this.options,dt=Ct/lt,St=(Re-dt)/Xe,sr=(Re+1+dt)/Xe,Ut={features:[]};return this._addTileFeatures(tt.range((be-dt)/Xe,St,(be+1+dt)/Xe,sr),tt.data,be,Re,Xe,Ut),be===0&&this._addTileFeatures(tt.range(1-dt/Xe,St,1,sr),tt.data,Xe,Re,Xe,Ut),be===Xe-1&&this._addTileFeatures(tt.range(0,St,dt/Xe,sr),tt.data,-1,Re,Xe,Ut),Ut.features.length?Ut:null}getClusterExpansionZoom(ue){let be=this._getOriginZoom(ue)-1;for(;be<=this.options.maxZoom;){const Re=this.getChildren(ue);if(be++,Re.length!==1)break;ue=Re[0].properties.cluster_id}return be}_appendLeaves(ue,be,Re,tt,Xe){const lt=this.getChildren(be);for(const Ct of lt){const dt=Ct.properties;if(dt&&dt.cluster?Xe+dt.point_count<=tt?Xe+=dt.point_count:Xe=this._appendLeaves(ue,dt.cluster_id,Re,tt,Xe):Xe1;let sr,Ut,Ir;if(St)sr=We(be,dt,this.clusterProps),Ut=be[dt],Ir=be[dt+1];else{const ur=this.points[be[dt+Ht]];sr=ur.properties;const[jr,Vr]=ur.geometry.coordinates;Ut=_t(jr),Ir=Gt(Vr)}const en={type:1,geometry:[[Math.round(this.options.extent*(Ut*Xe-Re)),Math.round(this.options.extent*(Ir*Xe-tt))]],tags:sr};let Ge;Ge=St||this.options.generateId?be[dt+Ht]:this.points[be[dt+Ht]].id,Ge!==void 0&&(en.id=Ge),lt.features.push(en)}}_limitZoom(ue){return Math.max(this.options.minZoom,Math.min(Math.floor(+ue),this.options.maxZoom+1))}_cluster(ue,be){const{radius:Re,extent:tt,reduce:Xe,minPoints:lt}=this.options,Ct=Re/(tt*Math.pow(2,be)),dt=ue.data,St=[],sr=this.stride;for(let Ut=0;Utbe&&(jr+=dt[cn+Lt])}if(jr>ur&&jr>=lt){let Vr,cn=Ir*ur,Ns=en*ur,Mi=-1;const Zi=(Ut/sr<<5)+(be+1)+this.points.length;for(const Oa of Ge){const Yi=Oa*sr;if(dt[Yi+2]<=be)continue;dt[Yi+2]=be;const _s=dt[Yi+Lt];cn+=dt[Yi]*_s,Ns+=dt[Yi+1]*_s,dt[Yi+4]=Zi,Xe&&(Vr||(Vr=this._map(dt,Ut,!0),Mi=this.clusterProps.length,this.clusterProps.push(Vr)),Xe(Vr,this._map(dt,Yi)))}dt[Ut+4]=Zi,St.push(cn/jr,Ns/jr,1/0,Zi,-1,jr),Xe&&St.push(Mi)}else{for(let Vr=0;Vr1)for(const Vr of Ge){const cn=Vr*sr;if(!(dt[cn+2]<=be)){dt[cn+2]=be;for(let Ns=0;Ns>5}_getOriginZoom(ue){return(ue-this.points.length)%32}_map(ue,be,Re){if(ue[be+Lt]>1){const lt=this.clusterProps[ue[be+Kt]];return Re?Object.assign({},lt):lt}const tt=this.points[ue[be+Ht]].properties,Xe=this.options.map(tt);return Re&&Xe===tt?Object.assign({},Xe):Xe}}function rt(vt,ue,be){return{type:"Feature",id:vt[ue+Ht],properties:We(vt,ue,be),geometry:{type:"Point",coordinates:[(Re=vt[ue],360*(Re-.5)),rr(vt[ue+1])]}};var Re}function We(vt,ue,be){const Re=vt[ue+Lt],tt=Re>=1e4?`${Math.round(Re/1e3)}k`:Re>=1e3?Math.round(Re/100)/10+"k":Re,Xe=vt[ue+Kt],lt=Xe===-1?{}:Object.assign({},be[Xe]);return Object.assign(lt,{cluster:!0,cluster_id:vt[ue+Ht],point_count:Re,point_count_abbreviated:tt})}function _t(vt){return vt/360+.5}function Gt(vt){const ue=Math.sin(vt*Math.PI/180),be=.5-.25*Math.log((1+ue)/(1-ue))/Math.PI;return be<0?0:be>1?1:be}function rr(vt){const ue=(180-360*vt)*Math.PI/180;return 360*Math.atan(Math.exp(ue))/Math.PI-90}function pr(vt,ue,be,Re){let tt=Re;const Xe=ue+(be-ue>>1);let lt,Ct=be-ue;const dt=vt[ue],St=vt[ue+1],sr=vt[be],Ut=vt[be+1];for(let Ir=ue+3;Irtt)lt=Ir,tt=en;else if(en===tt){const Ge=Math.abs(Ir-Xe);GeRe&&(lt-ue>3&&pr(vt,ue,lt,Re),vt[lt+2]=tt,be-lt>3&&pr(vt,lt,be,Re))}function kr(vt,ue,be,Re,tt,Xe){let lt=tt-be,Ct=Xe-Re;if(lt!==0||Ct!==0){const dt=((vt-be)*lt+(ue-Re)*Ct)/(lt*lt+Ct*Ct);dt>1?(be=tt,Re=Xe):dt>0&&(be+=lt*dt,Re+=Ct*dt)}return lt=vt-be,Ct=ue-Re,lt*lt+Ct*Ct}function Hr(vt,ue,be,Re){const tt={id:vt??null,type:ue,geometry:be,tags:Re,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};if(ue==="Point"||ue==="MultiPoint"||ue==="LineString")Fn(tt,be);else if(ue==="Polygon")Fn(tt,be[0]);else if(ue==="MultiLineString")for(const Xe of be)Fn(tt,Xe);else if(ue==="MultiPolygon")for(const Xe of be)Fn(tt,Xe[0]);return tt}function Fn(vt,ue){for(let be=0;be0&&(lt+=Re?(tt*sr-St*Xe)/2:Math.sqrt(Math.pow(St-tt,2)+Math.pow(sr-Xe,2))),tt=St,Xe=sr}const Ct=ue.length-3;ue[2]=1,pr(ue,0,Ct,be),ue[Ct+2]=1,ue.size=Math.abs(lt),ue.start=0,ue.end=ue.size}function zo(vt,ue,be,Re){for(let tt=0;tt1?1:be}function Ma(vt,ue,be,Re,tt,Xe,lt,Ct){if(Re/=ue,Xe>=(be/=ue)&<=Re)return null;const dt=[];for(const St of vt){const sr=St.geometry;let Ut=St.type;const Ir=tt===0?St.minX:St.minY,en=tt===0?St.maxX:St.maxY;if(Ir>=be&&en=Re)continue;let Ge=[];if(Ut==="Point"||Ut==="MultiPoint")Qo(sr,Ge,be,Re,tt);else if(Ut==="LineString")ec(sr,Ge,be,Re,tt,!1,Ct.lineMetrics);else if(Ut==="MultiLineString")tc(sr,Ge,be,Re,tt,!1);else if(Ut==="Polygon")tc(sr,Ge,be,Re,tt,!0);else if(Ut==="MultiPolygon")for(const ur of sr){const jr=[];tc(ur,jr,be,Re,tt,!0),jr.length&&Ge.push(jr)}if(Ge.length){if(Ct.lineMetrics&&Ut==="LineString"){for(const ur of Ge)dt.push(Hr(St.id,Ut,ur,St.tags));continue}Ut!=="LineString"&&Ut!=="MultiLineString"||(Ge.length===1?(Ut="LineString",Ge=Ge[0]):Ut="MultiLineString"),Ut!=="Point"&&Ut!=="MultiPoint"||(Ut=Ge.length===3?"Point":"MultiPoint"),dt.push(Hr(St.id,Ut,Ge,St.tags))}}return dt.length?dt:null}function Qo(vt,ue,be,Re,tt){for(let Xe=0;Xe=be&<<=Re&&Jo(ue,vt[Xe],vt[Xe+1],vt[Xe+2])}}function ec(vt,ue,be,Re,tt,Xe,lt){let Ct=yl(vt);const dt=tt===0?wh:xa;let St,sr,Ut=vt.start;for(let jr=0;jrbe&&(sr=dt(Ct,Vr,cn,Mi,Zi,be),lt&&(Ct.start=Ut+St*sr)):Oa>Re?Yi=be&&(sr=dt(Ct,Vr,cn,Mi,Zi,be),_s=!0),Yi>Re&&Oa<=Re&&(sr=dt(Ct,Vr,cn,Mi,Zi,Re),_s=!0),!Xe&&_s&&(lt&&(Ct.end=Ut+St*sr),ue.push(Ct),Ct=yl(vt)),lt&&(Ut+=St)}let Ir=vt.length-3;const en=vt[Ir],Ge=vt[Ir+1],ur=tt===0?en:Ge;ur>=be&&ur<=Re&&Jo(Ct,en,Ge,vt[Ir+2]),Ir=Ct.length-3,Xe&&Ir>=3&&(Ct[Ir]!==Ct[0]||Ct[Ir+1]!==Ct[1])&&Jo(Ct,Ct[0],Ct[1],Ct[2]),Ct.length&&ue.push(Ct)}function yl(vt){const ue=[];return ue.size=vt.size,ue.start=vt.start,ue.end=vt.end,ue}function tc(vt,ue,be,Re,tt,Xe){for(const lt of vt)ec(lt,ue,be,Re,tt,Xe,!1)}function Jo(vt,ue,be,Re){vt.push(ue,be,Re)}function wh(vt,ue,be,Re,tt,Xe){const lt=(Xe-ue)/(Re-ue);return Jo(vt,Xe,be+(tt-be)*lt,1),lt}function xa(vt,ue,be,Re,tt,Xe){const lt=(Xe-be)/(tt-be);return Jo(vt,ue+(Re-ue)*lt,Xe,1),lt}function Qs(vt,ue){const be=[];for(let Re=0;Re0&&ue.size<(tt?lt:Re))return void(be.numPoints+=ue.length/3);const Ct=[];for(let dt=0;dtlt)&&(be.numSimplified++,Ct.push(ue[dt],ue[dt+1])),be.numPoints++;tt&&function(dt,St){let sr=0;for(let Ut=0,Ir=dt.length,en=Ir-2;Ut0===St)for(let Ut=0,Ir=dt.length;Ut24)throw new Error("maxZoom should be in the 0-24 range");if(be.promoteId&&be.generateId)throw new Error("promoteId and generateId cannot be used together.");let tt=function(Xe,lt){const Ct=[];if(Xe.type==="FeatureCollection")for(let dt=0;dt1&&console.time("creation"),en=this.tiles[Ir]=ki(ue,be,Re,tt,St),this.tileCoords.push({z:be,x:Re,y:tt}),sr)){sr>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",be,Re,tt,en.numFeatures,en.numPoints,en.numSimplified),console.timeEnd("creation"));const _s=`z${be}`;this.stats[_s]=(this.stats[_s]||0)+1,this.total++}if(en.source=ue,Xe==null){if(be===St.indexMaxZoom||en.numPoints<=St.indexMaxPoints)continue}else{if(be===St.maxZoom||be===Xe)continue;if(Xe!=null){const _s=Xe-be;if(Re!==lt>>_s||tt!==Ct>>_s)continue}}if(en.source=null,ue.length===0)continue;sr>1&&console.time("clipping");const Ge=.5*St.buffer/St.extent,ur=.5-Ge,jr=.5+Ge,Vr=1+Ge;let cn=null,Ns=null,Mi=null,Zi=null,Oa=Ma(ue,Ut,Re-Ge,Re+jr,0,en.minX,en.maxX,St),Yi=Ma(ue,Ut,Re+ur,Re+Vr,0,en.minX,en.maxX,St);ue=null,Oa&&(cn=Ma(Oa,Ut,tt-Ge,tt+jr,1,en.minY,en.maxY,St),Ns=Ma(Oa,Ut,tt+ur,tt+Vr,1,en.minY,en.maxY,St),Oa=null),Yi&&(Mi=Ma(Yi,Ut,tt-Ge,tt+jr,1,en.minY,en.maxY,St),Zi=Ma(Yi,Ut,tt+ur,tt+Vr,1,en.minY,en.maxY,St),Yi=null),sr>1&&console.timeEnd("clipping"),dt.push(cn||[],be+1,2*Re,2*tt),dt.push(Ns||[],be+1,2*Re,2*tt+1),dt.push(Mi||[],be+1,2*Re+1,2*tt),dt.push(Zi||[],be+1,2*Re+1,2*tt+1)}}getTile(ue,be,Re){ue=+ue,be=+be,Re=+Re;const tt=this.options,{extent:Xe,debug:lt}=tt;if(ue<0||ue>24)return null;const Ct=1<1&&console.log("drilling down to z%d-%d-%d",ue,be,Re);let St,sr=ue,Ut=be,Ir=Re;for(;!St&&sr>0;)sr--,Ut>>=1,Ir>>=1,St=this.tiles[oo(sr,Ut,Ir)];return St&&St.source?(lt>1&&(console.log("found parent tile z%d-%d-%d",sr,Ut,Ir),console.time("drilling down")),this.splitTile(St.source,sr,Ut,Ir,ue,be,Re),lt>1&&console.timeEnd("drilling down"),this.tiles[dt]?Ss(this.tiles[dt],Xe):null):null}}function oo(vt,ue,be){return 32*((1<St.tags&&"3d_elevation_id"in St.tags&&"source"in St.tags&&St.tags.source==="elevation",Xe=Re.features.filter(St=>tt(St));let lt={_geojsonTileLayer:Re.features};Xe.length>0&&(lt={_geojsonTileLayer:Re.features.filter(St=>!tt(St)),hd_road_elevation:Xe});const Ct=new ve(lt),dt=function(St){const sr=new a.bt;for(const Ut of Object.keys(St))sr.writeMessage(3,Qt,{name:Ut,features:St[Ut]});return sr.finish()}(lt).buffer;ue(null,{vectorTile:Ct,rawData:dt})}class Bo extends Q{constructor(ue,be,Re,tt,Xe,lt,Ct){super(ue,be,Re,tt,Xe,Xn,Ct),lt&&(this.loadGeoJSON=lt),this._dynamicIndex=new Ce}loadData(ue,be){const Re=ue&&ue.request,tt=Re&&Re.collectResourceTiming;this._geoJSONIndex=null,this.loadGeoJSON(ue,(Xe,lt)=>{if(Xe||!lt)return be(Xe);if(typeof lt!="object")return be(new Error(`Input data given to '${ue.source}' is not a valid GeoJSON object.`));{try{if(ue.filter){const dt=a.U(ue.filter,{type:"boolean","property-type":"data-driven",overridable:!1,transition:!1});if(dt.result==="error")throw new Error(dt.value.map(St=>`${St.key}: ${St.message}`).join(", "));lt.features=lt.features.filter(St=>dt.value.evaluate({zoom:0},St))}ue.dynamic?(lt.type==="Feature"&&(lt={type:"FeatureCollection",features:[lt]}),ue.append||(this._dynamicIndex.clear(),this.loaded={}),this._dynamicIndex.load(lt.features,this.loaded),ue.cluster&&(lt.features=this._dynamicIndex.getFeatures())):this.loaded={},this._geoJSONIndex=ue.cluster?new Ar(function({superclusterOptions:dt,clusterProperties:St}){if(!St||!dt)return dt;const sr={},Ut={},Ir={accumulated:null,zoom:0},en={properties:null},Ge=Object.keys(St);for(const ur of Ge){const[jr,Vr]=St[ur],cn=a.U(Vr),Ns=a.U(typeof jr=="string"?[jr,["accumulated"],["get",ur]]:jr);sr[ur]=cn.value,Ut[ur]=Ns.value}return dt.map=ur=>{en.properties=ur;const jr={};for(const Vr of Ge)jr[Vr]=sr[Vr].evaluate(Ir,en);return jr},dt.reduce=(ur,jr)=>{en.properties=jr;for(const Vr of Ge)Ir.accumulated=ur[Vr],ur[Vr]=Ut[Vr].evaluate(Ir,en)},dt}(ue)).load(lt.features):ue.dynamic?this._dynamicIndex:function(dt,St){return new zc(dt,St)}(lt,ue.geojsonVtOptions)}catch(dt){return be(dt)}const Ct={};if(tt){const dt=m(Re);dt&&(Ct.resourceTiming={},Ct.resourceTiming[ue.source]=JSON.parse(JSON.stringify(dt)))}be(null,Ct)}})}reloadTile(ue,be){const Re=this.loaded;return Re&&Re[ue.uid]?ue.partial?be(null,void 0):super.reloadTile(ue,be):this.loadTile(ue,be)}loadGeoJSON(ue,be){if(ue.request)a.m(ue.request,be);else{if(typeof ue.data!="string")return be(new Error(`Input data given to '${ue.source}' is not a valid GeoJSON object.`));setTimeout(()=>{try{return be(null,JSON.parse(ue.data))}catch{return be(new Error(`Input data given to '${ue.source}' is not a valid GeoJSON object.`))}},0)}}getClusterExpansionZoom(ue,be){try{be(null,this._geoJSONIndex.getClusterExpansionZoom(ue.clusterId))}catch(Re){be(Re)}}getClusterChildren(ue,be){try{be(null,this._geoJSONIndex.getChildren(ue.clusterId))}catch(Re){be(Re)}}getClusterLeaves(ue,be){try{be(null,this._geoJSONIndex.getLeaves(ue.clusterId,ue.limit,ue.offset))}catch(Re){be(Re)}}}class Px{constructor(ue,be,Re){this.tileID=new a.aQ(ue.tileID.overscaledZ,ue.tileID.wrap,ue.tileID.canonical.z,ue.tileID.canonical.x,ue.tileID.canonical.y),this.tileZoom=ue.tileZoom,this.uid=ue.uid,this.zoom=ue.zoom,this.canonical=ue.tileID.canonical,this.pixelRatio=ue.pixelRatio,this.tileSize=ue.tileSize,this.source=ue.source,this.overscaling=this.tileID.overscaleFactor(),this.projection=ue.projection,this.brightness=be,this.worldview=Re}parse(ue,be,Re,tt){this.status="parsing";const Xe=new a.aQ(Re.tileID.overscaledZ,Re.tileID.wrap,Re.tileID.canonical.z,Re.tileID.canonical.x,Re.tileID.canonical.y),lt=[],Ct=be.familiesBySource[Re.source],dt=new a.fn(Xe,Re.promoteId);dt.bucketLayerIDs=[],dt.is3DTile=!0,a.fC(ue).then(St=>{if(!St)return tt(new Error("Could not parse tile"));const sr=St.json.extensionsUsed&&St.json.extensionsUsed.includes("MAPBOX_mesh_features")||St.json.asset.extras&&St.json.asset.extras.MAPBOX_mesh_features,Ut=St.json.extensionsUsed&&St.json.extensionsUsed.includes("EXT_meshopt_compression"),Ir=new a.ac(this.zoom,{brightness:this.brightness,worldview:this.worldview});for(const en in Ct)for(const Ge of Ct[en]){const ur=Ge[0];dt.bucketLayerIDs.push(Ge.map(cn=>a.B(cn.id,cn.scope))),ur.recalculate(Ir,[]);const jr=a.fD(St,1/a.d7(Re.tileID.canonical)),Vr=new a.fE(Ge,jr,Xe,sr,Ut,this.brightness,dt,this.worldview);sr||(Vr.needsUpload=!0),lt.push(Vr),Vr.evaluate(ur)}this.status="done",tt(null,{buckets:lt,featureIndex:dt,collisionBoxArray:null,glyphAtlasImage:null,lineAtlas:null,imageAtlas:null,brightness:null})}).catch(St=>tt(new Error(St.message)))}}class jh{constructor(ue,be,Re,tt,Xe,lt,Ct,dt){this.actor=ue,this.layerIndex=be,this.availableImages=Re,this.availableModels=tt,this.brightness=Ct,this.loading={},this.loaded={},this.worldview=dt}loadTile(ue,be){const Re=ue.uid,tt=this.loading[Re]=new Px(ue,this.brightness,this.worldview);a.bu(ue.request,(Xe,lt)=>{const Ct=!this.loading[Re];return delete this.loading[Re],Ct||Xe?(tt.status="done",Ct||(this.loaded[Re]=tt),be(Xe)):lt&<.byteLength!==0?void tt.parse(lt,this.layerIndex,ue,(dt,St)=>{tt.status="done",this.loaded=this.loaded||{},this.loaded[Re]=tt,dt||!St?be(dt):be(null,St)}):(tt.status="done",this.loaded[Re]=tt,be())})}reloadTile(ue,be){const Re=this.loaded,tt=ue.uid;if(Re&&Re[tt]){const Xe=Re[tt];Xe.projection=ue.projection,Xe.brightness=ue.brightness;const lt=(Ct,dt)=>{Xe.reloadCallback&&(delete Xe.reloadCallback,this.loadTile(ue,be)),be(Ct,dt)};Xe.status==="parsing"?Xe.reloadCallback=lt:Xe.status==="done"&&this.loadTile(ue,be)}}abortTile(ue,be){const Re=ue.uid;this.loading[Re]&&delete this.loading[Re],be()}removeTile(ue,be){const Re=this.loaded,tt=ue.uid;Re&&Re[tt]&&delete Re[tt],be()}}class Fp{constructor(ue){this.self=ue,this.actor=new a.fG(ue,this),this.layerIndexes={},this.availableImages={},this.availableModels={},this.isSpriteLoaded={},this.imageRasterizer=new a.x,this.rtlPluginParsingListeners=[],this.projections={},this.defaultProjection=a.cm({name:"mercator"}),this.workerSourceTypes={vector:Q,geojson:Bo,"raster-dem":te,"raster-array":ie,"batched-model":jh},this.workerSources={},this.self.registerWorkerSource=(be,Re)=>{if(this.workerSourceTypes[be])throw new Error(`Worker source with name "${be}" already registered.`);this.workerSourceTypes[be]=Re},this.self.registerRTLTextPlugin=be=>{if(a.fH.isParsed())throw new Error("RTL text plugin already registered.");a.fH.setState({pluginStatus:a.fI.parsed,pluginURL:a.fH.getPluginURL()}),a.fH.applyArabicShaping=be.applyArabicShaping,a.fH.processBidirectionalText=be.processBidirectionalText,a.fH.processStyledBidirectionalText=be.processStyledBidirectionalText;for(const Re of this.rtlPluginParsingListeners)Re(null,!0);this.rtlPluginParsingListeners=[]}}clearCaches(ue,be,Re){delete this.layerIndexes[ue],delete this.availableImages[ue],delete this.availableModels[ue],delete this.workerSources[ue],Re()}checkIfReady(ue,be,Re){Re()}setReferrer(ue,be){this.referrer=be}spriteLoaded(ue,be){this.isSpriteLoaded[ue]||(this.isSpriteLoaded[ue]={});const{scope:Re,isLoaded:tt}=be;if(this.isSpriteLoaded[ue][Re]=tt,this.workerSources[ue]&&this.workerSources[ue][Re])for(const Xe in this.workerSources[ue][Re]){const lt=this.workerSources[ue][Re][Xe];for(const Ct in lt){const dt=lt[Ct];dt instanceof Q&&(dt.isSpriteLoaded=tt,dt.fire(new a.z("isSpriteLoaded")))}}}setImages(ue,be,Re){this.availableImages[ue]||(this.availableImages[ue]={});const{scope:tt,images:Xe}=be;if(this.availableImages[ue][tt]=Xe,this.workerSources[ue]&&this.workerSources[ue][tt]){for(const lt in this.workerSources[ue][tt]){const Ct=this.workerSources[ue][tt][lt];for(const dt in Ct)Ct[dt].availableImages=Xe}Re()}else Re()}setModels(ue,{scope:be,models:Re},tt){if(this.availableModels[ue]||(this.availableModels[ue]={}),this.availableModels[ue][be]=Re,this.workerSources[ue]&&this.workerSources[ue][be]){for(const Xe in this.workerSources[ue][be]){const lt=this.workerSources[ue][be][Xe];for(const Ct in lt)lt[Ct].availableModels=Re}tt()}else tt()}setProjection(ue,be){this.projections[ue]=a.cm(be)}setBrightness(ue,be,Re){this.brightness=be,Re()}setWorldview(ue,be,Re){this.worldview=be,Re()}setLayers(ue,be,Re){this.getLayerIndex(ue,be.scope).replace(be.layers,be.options),Re()}updateLayers(ue,be,Re){this.getLayerIndex(ue,be.scope).update(be.layers,be.removedIds,be.options),Re()}loadTile(ue,be,Re){be.projection=this.projections[ue]||this.defaultProjection,this.getWorkerSource(ue,be.type,be.source,be.scope).loadTile(be,Re)}decodeRasterArray(ue,be,Re){this.getWorkerSource(ue,be.type,be.source,be.scope).decodeRasterArray(be,Re)}reloadTile(ue,be,Re){be.projection=this.projections[ue]||this.defaultProjection,this.getWorkerSource(ue,be.type,be.source,be.scope).reloadTile(be,Re)}abortTile(ue,be,Re){this.getWorkerSource(ue,be.type,be.source,be.scope).abortTile(be,Re)}removeTile(ue,be,Re){this.getWorkerSource(ue,be.type,be.source,be.scope).removeTile(be,Re)}removeSource(ue,be,Re){if(!(this.workerSources[ue]&&this.workerSources[ue][be.scope]&&this.workerSources[ue][be.scope][be.type]&&this.workerSources[ue][be.scope][be.type][be.source]))return;const tt=this.workerSources[ue][be.scope][be.type][be.source];delete this.workerSources[ue][be.scope][be.type][be.source],tt.removeSource!==void 0?tt.removeSource(be,Re):Re()}loadWorkerSource(ue,be,Re){try{this.self.importScripts(be.url),Re()}catch(tt){Re(tt)}}syncRTLPluginState(ue,be,Re){if(a.fH.isParsed())Re(null,!0);else if(a.fH.isParsing())this.rtlPluginParsingListeners.push(Re);else try{a.fH.setState(be);const tt=a.fH.getPluginURL();!a.fH.isLoaded()||a.fH.isParsed()||a.fH.isParsing()||tt==null||(a.fH.setState({pluginStatus:a.fI.parsing,pluginURL:a.fH.getPluginURL()}),this.self.importScripts(tt),a.fH.isParsed()?Re(null,!0):this.rtlPluginParsingListeners.push(Re))}catch(tt){Re(tt)}}setDracoUrl(ue,be){this.dracoUrl=be}getAvailableImages(ue,be){this.availableImages[ue]||(this.availableImages[ue]={});let Re=this.availableImages[ue][be];return Re||(Re=[]),Re}getAvailableModels(ue,be){this.availableModels[ue]||(this.availableModels[ue]={});let Re=this.availableModels[ue][be];return Re||(Re={}),Re}getLayerIndex(ue,be){this.layerIndexes[ue]||(this.layerIndexes[ue]={});let Re=this.layerIndexes[ue][be];return Re||(Re=this.layerIndexes[ue][be]=new j,Re.scope=be),Re}getWorkerSource(ue,be,Re,tt){const Xe=this.workerSources;return Xe[ue]||(Xe[ue]={}),Xe[ue][tt]||(Xe[ue][tt]={}),Xe[ue][tt][be]||(Xe[ue][tt][be]={}),this.isSpriteLoaded[ue]||(this.isSpriteLoaded[ue]={}),Xe[ue][tt][be][Re]||(Xe[ue][tt][be][Re]=new this.workerSourceTypes[be]({send:(lt,Ct,dt,St,sr,Ut)=>this.actor.send(lt,Ct,dt,ue,sr,Ut),scheduler:this.actor.scheduler},this.getLayerIndex(ue,tt),this.getAvailableImages(ue,tt),this.getAvailableModels(ue,tt),this.isSpriteLoaded[ue][tt],void 0,this.brightness,this.worldview)),Xe[ue][tt][be][Re]}rasterizeImagesWorker(ue,be,Re){const tt=new Map;for(const[Xe,{image:lt,imageVariant:Ct}]of be.tasks.entries()){const dt=this.imageRasterizer.rasterize(Ct,lt,be.scope,ue);tt.set(Xe,dt)}Re(void 0,tt)}removeRasterizedImages(ue,be,Re){this.imageRasterizer.removeImagesFromCacheByIds(be.imageIds,be.scope,ue),Re()}enforceCacheSizeLimit(ue,be){a.fJ(be)}getWorkerPerformanceMetrics(ue,be,Re){Re(void 0,void 0)}}return a.fF(self)&&(self.worker=new Fp(self)),Fp}),o(["./shared"],function(a){var m="3.17.0";const g={create:"create",load:"load",fullLoad:"fullLoad"},_={mark(x){performance.mark(x)},measure(x,u,f){performance.measure(x,u,f)}};function j(x){const u=x.name.split("?")[0];return a.a(u)&&u.includes("mapbox-gl.js")?"javascript":a.a(u)&&u.includes("mapbox-gl.css")?"css":a.b(u)?"fontRange":a.c(u)?"sprite":a.i(u)?"style":a.d(u)?"tilejson":"other"}var N,C={},P=function(){if(N)return C;function x(v){return!u(v)}function u(v){return typeof window>"u"||typeof document>"u"?"not a browser":function(){if(!("Worker"in window&&"Blob"in window&&"URL"in window))return!1;var T,E,L=new Blob([""],{type:"text/javascript"}),B=URL.createObjectURL(L);try{E=new Worker(B),T=!0}catch{T=!1}return E&&E.terminate(),URL.revokeObjectURL(B),T}()?function(){var T=document.createElement("canvas");T.width=T.height=1;var E=T.getContext("2d");if(!E)return!1;var L=E.getImageData(0,0,1,1);return L&&L.width===T.width}()?(f[S=v&&v.failIfMajorPerformanceCaveat]===void 0&&(f[S]=function(T){var E,L=function(B){var q=document.createElement("canvas"),G=Object.create(x.webGLContextAttributes);return G.failIfMajorPerformanceCaveat=B,q.getContext("webgl2",G)}(T);if(!L)return!1;try{E=L.createShader(L.VERTEX_SHADER)}catch{return!1}return!(!E||L.isContextLost())&&(L.shaderSource(E,"void main() {}"),L.compileShader(E),L.getShaderParameter(E,L.COMPILE_STATUS)===!0)}(S)),f[S]?document.documentMode?"insufficient ECMAScript 6 support":void 0:"insufficient WebGL2 support"):"insufficient Canvas/getImageData support":"insufficient worker support";var S}N=1,C.supported=x,C.notSupportedReason=u;var f={};return x.webGLContextAttributes={antialias:!1,alpha:!0,stencil:!0,depth:!0},C}();function A(x,u,f){const v=document.createElement(x);return u!=null&&(v.className=u),f&&f.appendChild(v),v}function I(x,u,f){const v=document.createElementNS("http://www.w3.org/2000/svg",x);for(const S of Object.keys(u))v.setAttributeNS(null,S,String(u[S]));return f&&f.appendChild(v),v}const O=typeof document<"u"?document.documentElement&&document.documentElement.style:null,R=O&&O.userSelect!==void 0?"userSelect":"WebkitUserSelect";let z;function W(){O&&R&&(z=O[R],O[R]="none")}function V(){O&&R&&(O[R]=z)}function K(x){x.preventDefault(),x.stopPropagation(),window.removeEventListener("click",K,!0)}function Q(){window.addEventListener("click",K,!0),window.setTimeout(()=>{window.removeEventListener("click",K,!0)},0)}function te(x,u){const f=x.getBoundingClientRect();return he(x,f,u)}function X(x,u){const f=x.getBoundingClientRect(),v=[];for(let S=0;Sthis._skuTokenExpiresAt}transformRequest(u,f){return this._transformRequestFn&&this._transformRequestFn(u,f)||{url:u}}normalizeStyleURL(u,f){if(!a.h(u))return u;const v=ke(u);return v.params.push(`sdk=js-${m}`),v.path=`/styles/v1${v.path}`,this._makeAPIURL(v,this._customAccessToken||f)}normalizeGlyphsURL(u,f){if(!a.h(u))return u;const v=ke(u);return v.path=`/fonts/v1${v.path}`,this._makeAPIURL(v,this._customAccessToken||f)}normalizeModelURL(u,f){if(!a.h(u))return u;const v=ke(u);return v.path=`/models/v1${v.path}`,this._makeAPIURL(v,this._customAccessToken||f)}normalizeSourceURL(u,f,v,S){if(!a.h(u))return u;const T=ke(u);return T.path=`/v4/${T.authority}.json`,T.params.push("secure"),v&&T.params.push(`language=${v}`),S&&T.params.push(`worldview=${S}`),this._makeAPIURL(T,this._customAccessToken||f)}normalizeIconsetURL(u,f){const v=ke(u);return a.h(u)?(v.path=`/styles/v1${v.path}/iconset.pbf`,this._makeAPIURL(v,this._customAccessToken||f)):Ce(v)}normalizeSpriteURL(u,f,v,S){const T=ke(u);return a.h(u)?(T.path=`/styles/v1${T.path}/sprite${f}${v}`,this._makeAPIURL(T,this._customAccessToken||S)):(T.path+=`${f}${v}`,Ce(T))}normalizeTileURL(u,f,v){if(this._isSkuTokenExpired()&&this._createSkuToken(),u&&!a.h(u))return u;const S=ke(u);S.path=S.path.replace(/(\.(png|jpg)\d*)(?=$)/,`${f||v&&S.authority!=="raster"&&v===512?"@2x":""}${a.k.supported?".webp":"$1"}`),S.authority==="raster"?S.path=`/${a.e.RASTER_URL_PREFIX}${S.path}`:S.authority==="rasterarrays"?S.path=`/${a.e.RASTERARRAYS_URL_PREFIX}${S.path}`:S.authority==="3dtiles"?S.path=`/${a.e.TILES3D_URL_PREFIX}${S.path}`:(S.path=S.path.replace(/^.+\/v4\//,"/"),S.path=`/${a.e.TILE_URL_VERSION}${S.path}`);const T=this._customAccessToken||function(E){for(const L of E){const B=L.match(/^access_token=(.*)$/);if(B)return B[1]}return null}(S.params)||a.e.ACCESS_TOKEN;return a.e.REQUIRE_ACCESS_TOKEN&&T&&this._skuToken&&S.params.push(`sku=${this._skuToken}`),this._makeAPIURL(S,T)}canonicalizeTileURL(u,f){const v=ke(u);if(!v.path.match(/^(\/v4\/|\/(raster|rasterarrays)\/v1\/)/)||!v.path.match(/\.[\w]+$/))return u;let S="mapbox://";v.path.match(/^\/raster\/v1\//)?S+=`raster/${v.path.replace(`/${a.e.RASTER_URL_PREFIX}/`,"")}`:v.path.match(/^\/rasterarrays\/v1\//)?S+=`rasterarrays/${v.path.replace(`/${a.e.RASTERARRAYS_URL_PREFIX}/`,"")}`:S+=`tiles/${v.path.replace(`/${a.e.TILE_URL_VERSION}/`,"")}`;let T=v.params;return f&&(T=T.filter(E=>!E.match(/^access_token=/))),T.length&&(S+=`?${T.join("&")}`),S}canonicalizeTileset(u,f){const v=!!f&&a.h(f),S=[];for(const T of u.tiles||[])a.j(T)?S.push(this.canonicalizeTileURL(T,v)):S.push(T);return S}_makeAPIURL(u,f){const v="See https://docs.mapbox.com/api/overview/#access-tokens-and-token-scopes",S=ke(a.e.API_URL);if(u.protocol=S.protocol,u.authority=S.authority,u.protocol==="http"){const T=u.params.indexOf("secure");T>=0&&u.params.splice(T,1)}if(S.path!=="/"&&(u.path=`${S.path}${u.path}`),!a.e.REQUIRE_ACCESS_TOKEN)return Ce(u);if(f=f||a.e.ACCESS_TOKEN,!this._silenceAuthErrors){if(!f)throw new Error(`An API access token is required to use Mapbox GL. ${v}`);if(f[0]==="s")throw new Error(`Use a public access token (pk.*) with Mapbox GL, not a secret access token (sk.*). ${v}`)}return u.params=u.params.filter(T=>T.indexOf("access_token")===-1),u.params.push(`access_token=${f||""}`),Ce(u)}}const ge=/^(\w+):\/\/([^/?]*)(\/[^?]+)?\??(.+)?/;function ke(x){const u=x.match(ge);if(!u)throw new Error("Unable to parse URL object");return{protocol:u[1],authority:u[2],path:u[3]||"/",params:u[4]?u[4].split("&"):[]}}function Ce(x){const u=x.params.length?`?${x.params.join("&")}`:"";return`${x.protocol}://${x.authority}${x.path}${u}`}const Se="mapbox.eventData";function je(x){if(!x)return null;const u=x.split(".");if(!u||u.length!==3)return null;try{return JSON.parse(a.l(u[1]))}catch{return null}}class et{constructor(u){this.type=u,this.anonId=null,this.anonIdTimestamp=null,this.eventData={},this.queue=[],this.pendingRequest=null}getStorageKey(u){const f=je(a.e.ACCESS_TOKEN);let v="";return v=f&&f.u?a.f(f.u):a.e.ACCESS_TOKEN||"",u?`${Se}.${u}:${v}`:`${Se}:${v}`}fetchEventData(){const u=a.s("localStorage"),f=this.getStorageKey(),v=this.getStorageKey("uuid"),S=this.getStorageKey("uuidTimestamp");if(u)try{const T=localStorage.getItem(f);T&&(this.eventData=JSON.parse(T));const E=localStorage.getItem(v);E&&(this.anonId=E);const L=localStorage.getItem(S);L&&(this.anonIdTimestamp=Number(L));const B=Date.now()-864e5;(!this.anonIdTimestamp||this.anonIdTimestamp=1&&localStorage.setItem(f,JSON.stringify(this.eventData)),E&&localStorage.setItem(S,E.toString())}catch{a.w("Unable to write to LocalStorage")}}processRequests(u){}postEvent(u,f,v,S){if(!a.e.EVENTS_URL)return;const T=ke(a.e.EVENTS_URL);T.params.push(`access_token=${S||a.e.ACCESS_TOKEN||""}`);const E={event:this.type,created:new Date(u).toISOString()},L=f?Object.assign(E,f):E,B={url:Ce(T),headers:{"Content-Type":"text/plain"},body:JSON.stringify([L])};this.pendingRequest=a.p(B,q=>{this.pendingRequest=null,v(q),this.saveEventData(),this.processRequests(S)})}queueRequest(u,f){this.queue.push(u),this.processRequests(f)}}class bt extends et{constructor(u){super("metrics"),u&&(this.data=u)}postMetricsEvent(u){if(!a.e.EVENTS_URL||!u&&!a.e.ACCESS_TOKEN)return;this.anonId||this.fetchEventData(),a.v(this.anonId)||this.refreshUUID();const f=Object.assign({},this.data,{sessionId:this.anonId});this.queueRequest({timestamp:Date.now(),payload:f},u)}processRequests(u){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:f,payload:v}=this.queue.shift();this.postEvent(f,v,()=>{},u)}}const _e=new class extends et{constructor(x){super("appUserTurnstile"),this._customAccessToken=x}postTurnstileEvent(x,u){a.e.EVENTS_URL&&a.e.ACCESS_TOKEN&&Array.isArray(x)&&x.some(f=>a.h(f)||a.j(f))&&this.queueRequest(Date.now(),u)}processRequests(x){if(this.pendingRequest||this.queue.length===0)return;this.anonId&&this.anonIdTimestamp&&this.eventData.lastSuccess&&this.eventData.tokenU||this.fetchEventData();const u=je(a.e.ACCESS_TOKEN),f=u?u.u:a.e.ACCESS_TOKEN;let v=f!==this.eventData.tokenU;a.v(this.anonId)||(this.refreshUUID(),v=!0);const S=this.queue.shift();if(this.eventData.lastSuccess){const T=new Date(this.eventData.lastSuccess),E=new Date(S),L=(S-this.eventData.lastSuccess)/864e5;v=v||L>=1||L<-1||T.getDate()!==E.getDate()}else v=!0;v?this.postEvent(S,{sdkIdentifier:"mapbox-gl-js",sdkVersion:m,skuId:xe,"enabled.telemetry":!1,userId:this.anonId},T=>{T||(this.eventData.lastSuccess=S,this.eventData.tokenU=f)},x):this.processRequests()}},Ye=_e.postTurnstileEvent.bind(_e),pt=new class extends et{constructor(){super("map.load"),this.success={},this.skuToken=""}postMapLoadEvent(x,u,f,v){this.skuToken=u,this.errorCb=v,a.e.EVENTS_URL&&(f||a.e.ACCESS_TOKEN?this.queueRequest({id:x,timestamp:Date.now()},f):this.errorCb(new Error(pe)))}processRequests(x){if(this.pendingRequest||this.queue.length===0)return;const{id:u,timestamp:f}=this.queue.shift();u&&this.success[u]||(this.anonId&&this.anonIdTimestamp||this.fetchEventData(),a.v(this.anonId)||this.refreshUUID(),this.postEvent(f,{sdkIdentifier:"mapbox-gl-js",sdkVersion:m,skuId:xe,skuToken:this.skuToken,userId:this.anonId},v=>{v?this.errorCb(v):u&&(this.success[u]=!0)},x))}remove(){this.errorCb=null}},nt=pt.postMapLoadEvent.bind(pt),Qt=new class extends et{constructor(){super("style.load"),this.eventIdPerMapInstanceMap=new Map,this.mapInstanceIdMap=new WeakMap}getMapInstanceId(x){let u=this.mapInstanceIdMap.get(x);return u||(u=a.u(),this.mapInstanceIdMap.set(x,u)),u}getEventId(x){const u=this.eventIdPerMapInstanceMap.get(x)||0;return this.eventIdPerMapInstanceMap.set(x,u+1),u}postStyleLoadEvent(x,u){const{map:f,style:v,importedStyles:S}=u;if(!a.e.EVENTS_URL||!x&&!a.e.ACCESS_TOKEN)return;const T=this.getMapInstanceId(f),E={mapInstanceId:T,eventId:this.getEventId(T),style:v};S.length&&(E.importedStyles=S),this.queueRequest({timestamp:Date.now(),payload:E},x)}processRequests(x){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:u,payload:f}=this.queue.shift();this.postEvent(u,f,()=>{},x)}},gt=Qt.postStyleLoadEvent.bind(Qt),Me=new bt({attributes:[{name:"maps/js/layer-animations/style-with-appearances"}]}),Oe=Me.postMetricsEvent.bind(Me),Ie=new bt({attributes:[{name:"maps/js/layer-animations/runtime-appearances"}]}),Be=Ie.postMetricsEvent.bind(Ie),Pe=new class extends et{constructor(){super("gljs.performance")}postPerformanceEvent(x,u){a.e.EVENTS_URL&&(x||a.e.ACCESS_TOKEN)&&this.queueRequest({timestamp:Date.now(),performanceData:u},x)}processRequests(x){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:u,performanceData:f}=this.queue.shift(),v=function(S){const T=performance.getEntriesByType("resource"),E=performance.getEntriesByType("mark"),L=function(re){const oe={};if(re){for(const se in re)if(se!=="other")for(const me of re[se]){const fe=`${se}ResolveRangeMin`,Ne=`${se}ResolveRangeMax`,Ae=`${se}RequestCount`,Te=`${se}RequestCachedCount`;oe[fe]=Math.min(oe[fe]||1/0,me.startTime),oe[Ne]=Math.max(oe[Ne]||-1/0,me.responseEnd);const Ze=$e=>{oe[$e]===void 0&&(oe[$e]=0),++oe[$e]};me.transferSize!==void 0&&me.transferSize===0&&Ze(Te),Ze(Ae)}}return oe}(function(re,oe){const se={};if(re)for(const me of re){const fe=oe(me);se[fe]===void 0&&(se[fe]=[]),se[fe].push(me)}return se}(T,j)),B=window.devicePixelRatio,q=navigator.connection||navigator.mozConnection||navigator.webkitConnection,G=q?q.effectiveType:void 0,ee={counters:[],metadata:[],attributes:[]},J=(re,oe,se)=>{se!=null&&re.push({name:oe,value:se.toString()})};for(const re in L)J(ee.counters,re,L[re]);if(S.interactionRange[0]!==1/0&&S.interactionRange[1]!==-1/0&&(J(ee.counters,"interactionRangeMin",S.interactionRange[0]),J(ee.counters,"interactionRangeMax",S.interactionRange[1])),E)for(const re of Object.values(g)){const oe=E.find(se=>se.name===re);oe&&J(ee.counters,re,oe.startTime)}return J(ee.counters,"visibilityHidden",S.visibilityHidden),J(ee.attributes,"style",function(re){if(re)for(const oe of re){const se=oe.name.split("?")[0];if(a.i(se)){const me=se.split("/").slice(-2);if(me.length===2)return`mapbox://styles/${me[0]}/${me[1]}`}}}(T)),J(ee.attributes,"terrainEnabled",S.terrainEnabled?"true":"false"),J(ee.attributes,"fogEnabled",S.fogEnabled?"true":"false"),J(ee.attributes,"projection",S.projection),J(ee.attributes,"zoom",S.zoom),J(ee.metadata,"devicePixelRatio",B),J(ee.metadata,"connectionEffectiveType",G),J(ee.metadata,"navigatorUserAgent",navigator.userAgent),J(ee.metadata,"screenWidth",window.screen.width),J(ee.metadata,"screenHeight",window.screen.height),J(ee.metadata,"windowWidth",window.innerWidth),J(ee.metadata,"windowHeight",window.innerHeight),J(ee.metadata,"mapWidth",S.width/B),J(ee.metadata,"mapHeight",S.height/B),J(ee.metadata,"webglRenderer",S.renderer),J(ee.metadata,"webglVendor",S.vendor),J(ee.metadata,"sdkVersion",m),J(ee.metadata,"sdkIdentifier","mapbox-gl-js"),ee}(f);for(const S of v.metadata);for(const S of v.counters);for(const S of v.attributes);this.postEvent(u,v,()=>{},x)}},ut=Pe.postPerformanceEvent.bind(Pe),jt=new class extends et{constructor(){super("map.auth"),this.success={},this.skuToken=""}getSession(x,u,f,v){if(!a.e.API_URL||!a.e.SESSION_PATH)return;const S=ke(a.e.API_URL+a.e.SESSION_PATH);S.params.push(`sku=${u||""}`),S.params.push(`access_token=${v||a.e.ACCESS_TOKEN||""}`);const T={url:Ce(S),headers:{"Content-Type":"text/plain"}};this.pendingRequest=a.g(T,E=>{this.pendingRequest=null,f(E),this.saveEventData(),this.processRequests(v)})}getSessionAPI(x,u,f,v){this.skuToken=u,this.errorCb=v,a.e.SESSION_PATH&&a.e.API_URL&&(f||a.e.ACCESS_TOKEN?this.queueRequest({id:x,timestamp:Date.now()},f):this.errorCb(new Error(pe)))}processRequests(x){if(this.pendingRequest||this.queue.length===0)return;const{id:u,timestamp:f}=this.queue.shift();u&&this.success[u]||this.getSession(f,this.skuToken,v=>{v?this.errorCb(v):u&&(this.success[u]=!0)},x)}remove(){this.errorCb=null}},$t=jt.getSessionAPI.bind(jt),Ht=new Set;function Lt(x,u){u?Ht.add(x):Ht.delete(x)}class Kt{constructor(){this._changed=!1,this._updatedLayers={},this._removedLayers={},this._updatedSourceCaches={},this._updatedPaintProps=new Set,this._updatedImages={}}isDirty(){return this._changed}setDirty(){this._changed=!0}getUpdatedSourceCaches(){return this._updatedSourceCaches}updateSourceCache(u,f){this._updatedSourceCaches[u]=f,this.setDirty()}discardSourceCacheUpdate(u){delete this._updatedSourceCaches[u]}updateLayer(u){const f=u.scope;this._updatedLayers[f]=this._updatedLayers[f]||new Set,this._updatedLayers[f].add(u.id),this.setDirty()}removeLayer(u){const f=u.scope;this._removedLayers[f]=this._removedLayers[f]||{},this._updatedLayers[f]=this._updatedLayers[f]||new Set,this._removedLayers[f][u.id]=u,this._updatedLayers[f].delete(u.id),this._updatedPaintProps.delete(u.fqid),this.setDirty()}getRemovedLayer(u){return this._removedLayers[u.scope]?this._removedLayers[u.scope][u.id]:null}discardLayerRemoval(u){this._removedLayers[u.scope]&&delete this._removedLayers[u.scope][u.id]}getLayerUpdatesByScope(){const u={};for(const f in this._updatedLayers)u[f]=u[f]||{},u[f].updatedIds=Array.from(this._updatedLayers[f].values());for(const f in this._removedLayers)u[f]=u[f]||{},u[f].removedIds=Object.keys(this._removedLayers[f]);return u}getUpdatedPaintProperties(){return this._updatedPaintProps}updatePaintProperties(u){this._updatedPaintProps.add(u.fqid),this.setDirty()}getUpdatedImages(u){return this._updatedImages[u]?Array.from(this._updatedImages[u].values()):[]}updateImage(u,f){this._updatedImages[f]=this._updatedImages[f]||new Set,this._updatedImages[f].add(a.I.toString(u)),this.setDirty()}resetUpdatedImages(u){this._updatedImages[u]&&this._updatedImages[u].clear()}reset(){this._changed=!1,this._updatedLayers={},this._removedLayers={},this._updatedSourceCaches={},this._updatedPaintProps.clear(),this._updatedImages={}}}function Ar(x){const{userImage:u}=x;return!!(u&&u.render&&u.render())&&(x.data.replace(new Uint8Array(u.data.buffer)),!0)}class rt extends a.E{constructor(u){super(),this.imageProviders=new Map,this.images=new Map,this.updatedImages=new Map,this.callbackDispatchedThisFrame=new Map,this.loaded=new Map,this.requestors=[],this.patterns=new Map,this.patternsInFlight=new Set,this.atlasImage=new Map,this.atlasTexture=new Map,this.dirty=!0,this.spriteFormat=u,u!=="raster"&&a.r()&&(this.imageRasterizerDispatcher=new a.D(a.t(),this,"Image Rasterizer Worker",1))}addScope(u){this.loaded.set(u,!1),this.imageProviders.set(u,new Map),this.images.set(u,new Map),this.updatedImages.set(u,new Set),this.callbackDispatchedThisFrame.set(u,new Set),this.patterns.set(u,new Map),this.atlasImage.set(u,new a.q({width:1,height:1}))}removeScope(u){this.loaded.delete(u),this.imageProviders.delete(u),this.images.delete(u),this.updatedImages.delete(u),this.callbackDispatchedThisFrame.delete(u),this.patterns.delete(u),this.atlasImage.delete(u);const f=this.atlasTexture.get(u);f&&(f.destroy(),this.atlasTexture.delete(u))}addImageProvider(u,f){this.imageProviders.has(f)||this.imageProviders.set(f,new Map),this.imageProviders.get(f).set(u.id,u)}removeImageProvider(u,f){this.imageProviders.has(f)&&this.imageProviders.get(f).delete(u)}getPendingImageProviders(){const u=[];for(const f of this.imageProviders.values())for(const v of f.values())v.hasPendingRequests()&&u.push(v);return u}get imageRasterizer(){return this._imageRasterizer||(this._imageRasterizer=new a.x),this._imageRasterizer}isLoaded(){for(const u of this.loaded.keys())if(!this.loaded.get(u))return!1;return!0}setLoaded(u,f){if(this.loaded.get(f)!==u&&(this.loaded.set(f,u),u)){for(const{ids:v,callback:S}of this.requestors)this._notify(v,f,S);this.requestors=[]}}hasImage(u,f){return!!this.getImage(u,f)}getImage(u,f){return this.images.get(f).get(u.toString())}addImage(u,f,v){this._validate(u,v)&&this.images.get(f).set(u.toString(),v)}_validate(u,f){let v=!0;return this._validateStretch(f.stretchX,f.data&&f.data.width)||(this.fire(new a.y(new Error(`Image "${u.name}" has invalid "stretchX" value`))),v=!1),this._validateStretch(f.stretchY,f.data&&f.data.height)||(this.fire(new a.y(new Error(`Image "${u.name}" has invalid "stretchY" value`))),v=!1),this._validateContent(f.content,f)||(this.fire(new a.y(new Error(`Image "${u.name}" has invalid "content" value`))),v=!1),v}_validateStretch(u,f){if(!u)return!0;let v=0;for(const S of u){if(S[0]a.I.from(f))}getImages(u,f,v){const S=[],T=[],E=this.imageProviders.get(f);for(const G of u){if(!G.iconsetId){S.push(G);continue}const ee=E.get(G.iconsetId);ee&&(this.getImage(G,f)?T.push(G):ee.addPendingRequest(G))}if(S.length===0)return void this._notify(T,f,v);let L=!0;const B=!!this.loaded.get(f),q=this.images.get(f);if(!B)for(const G of S)q.has(G.toString())||(L=!1);B||L?this._notify(S,f,v):this.requestors.push({ids:S,scope:f,callback:v})}rasterizeImages(u,f){const v=new Map,{tasks:S,scope:T}=u;for(const[E,L]of S.entries()){const B=this.getImage(L.id,T);B&&v.set(E,{image:B,imageVariant:L})}this._rasterizeImages(T,v,f)}_rasterizeImages(u,f,v){if(a.r())this.imageRasterizerDispatcher.getActor().send("rasterizeImagesWorker",{tasks:f,scope:u},v);else{const S=new Map;for(const[T,{image:E,imageVariant:L}]of f.entries())S.set(T,this.imageRasterizer.rasterize(L,E,u,0));v(void 0,S)}}getUpdatedImages(u){return this.updatedImages.get(u)||new Set}_notify(u,f,v){const S=this.images.get(f),T=new Map;for(const E of u){if(!S.get(E.toString())){if(E.iconsetId)continue;this.fire(new a.z("styleimagemissing",{id:E.name}))}const L=S.get(E.toString());if(!L){a.w(`Image "${E.name}" could not be loaded. Please make sure you have added the image with map.addImage() or a "sprite" property in your style. You can provide missing images by listening for the "styleimagemissing" map event.`);continue}const B={data:L.usvg?null:L.data.clone(),pixelRatio:L.pixelRatio,sdf:L.sdf,usvg:L.usvg,version:L.version,stretchX:L.stretchX,stretchY:L.stretchY,content:L.content,hasRenderCallback:!!(L.userImage&&L.userImage.render)};L.usvg&&Object.assign(B,{width:L.icon.usvg_tree.width,height:L.icon.usvg_tree.height}),T.set(a.I.toString(E),B)}v(null,T)}getPixelSize(u){const{width:f,height:v}=this.atlasImage.get(u);return{width:f,height:v}}getPattern(u,f,v){const S=u.toString(),T=this.patterns.get(f),E=T.get(S),L=this.getImage(u,f);if(!L)return null;if(E){if(E.position.version===L.version)return E.position;E.position.version=L.version}else{if(L.usvg&&!L.data){const B=this.getPatternInFlightId(S,f);if(this.patternsInFlight.has(B))return null;this.patternsInFlight.add(B);const q=new a.A(u).scaleSelf(a.o.devicePixelRatio),G=new Map([[q.toString(),{image:L,imageVariant:q}]]);return this._rasterizeImages(f,G,(ee,J)=>this.storePatternImage(q,f,L,v,J)),null}this.storePattern(u,f,L)}return this._updatePatternAtlas(f,v),T.get(S).position}getPatternInFlightId(u,f){return a.B(u,f)}hasPatternsInFlight(){return this.patternsInFlight.size!==0}storePatternImage(u,f,v,S,T){const E=u.toString(),L=T?T.get(E):void 0;L&&(v.data=L,this.storePattern(u.id,f,v),this._updatePatternAtlas(f,S),this.patternsInFlight.delete(this.getPatternInFlightId(u.id.toString(),f)))}storePattern(u,f,v){const S={w:v.data.width+2*a.C,h:v.data.height+2*a.C,x:0,y:0},T=new a.F(S,v,a.C);this.patterns.get(f).set(u.toString(),{bin:S,position:T})}destroyAtlasTextures(){for(const u of this.atlasTexture.values())u&&u.destroy();this.atlasTexture.clear()}bind(u,f){const v=u.gl;let S=this.atlasTexture.get(f);S?this.dirty&&(S.update(this.atlasImage.get(f)),this.dirty=!1):(S=new a.T(u,this.atlasImage.get(f),v.RGBA8),this.atlasTexture.set(f,S)),S.bind(v.LINEAR,v.CLAMP_TO_EDGE)}_updatePatternAtlas(u,f){const v=this.patterns.get(u),S=Array.from(v.values()).map(({bin:q})=>q),{w:T,h:E}=a.G(S),L=this.atlasImage.get(u);L.resize({width:T||1,height:E||1});const B=this.images.get(u);for(const[q,{bin:G,position:ee}]of v.entries()){let J=ee.padding;const re=G.x+J,oe=G.y+J,se=B.get(q).data,me=se.width,fe=se.height;J=J>1?J-1:J,a.q.copy(se,L,{x:0,y:0},{x:re,y:oe},{width:me,height:fe},f),a.q.copy(se,L,{x:0,y:fe-J},{x:re,y:oe-J},{width:me,height:J},f),a.q.copy(se,L,{x:0,y:0},{x:re,y:oe+fe},{width:me,height:J},f),a.q.copy(se,L,{x:me-J,y:0},{x:re-J,y:oe},{width:J,height:fe},f),a.q.copy(se,L,{x:0,y:0},{x:re+me,y:oe},{width:J,height:fe},f),a.q.copy(se,L,{x:me-J,y:fe-J},{x:re-J,y:oe-J},{width:J,height:J},f),a.q.copy(se,L,{x:0,y:fe-J},{x:re+me,y:oe-J},{width:J,height:J},f),a.q.copy(se,L,{x:0,y:0},{x:re+me,y:oe+fe},{width:J,height:J},f),a.q.copy(se,L,{x:me-J,y:0},{x:re-J,y:oe+fe},{width:J,height:J},f)}this.dirty=!0}beginFrame(){for(const u of this.images.keys())this.callbackDispatchedThisFrame.set(u,new Set)}dispatchRenderCallbacks(u,f){const v=this.images.get(f);for(const S of u){if(this.callbackDispatchedThisFrame.get(f).has(S.toString()))continue;this.callbackDispatchedThisFrame.get(f).add(S.toString());const T=v.get(S.toString());Ar(T)&&this.updateImage(S,f,T)}}destroy(){this.imageRasterizerDispatcher&&this.imageRasterizerDispatcher.remove()}}function We(x){const u=x.value,f=x.valueSpec,v=x.style,S=x.styleSpec,T=x.key,E=x.arrayElementValidator||Qs;if(!Array.isArray(u))return[new a.V(T,u,`array expected, ${a.K(u)} found`)];if(f.length&&u.length!==f.length)return[new a.V(T,u,`array length ${f.length} expected, length ${u.length} found`)];if(f["min-length"]&&u.lengthS)return[new a.V(u,f,`${f} is greater than the maximum value ${S}`)]}return[]}function Gt(x){const u=x.key,f=x.value;if(!a.H(f))return[new a.V(u,f,`object expected, ${a.K(f)} found`)];const v=x.valueSpec,S=a.J(f.type);let T,E,L,B={};const q=S!=="categorical"&&f.property===void 0,G=!q,ee=function(se){const me=se.stops;return Array.isArray(me)&&Array.isArray(me[0])&&a.H(me[0][0])}(f),J=La({key:x.key,value:x.value,valueSpec:x.styleSpec.function,style:x.style,styleSpec:x.styleSpec,objectElementValidators:{stops:function(se){if(S==="identity")return[new a.V(se.key,se.value,'identity function may not have a "stops" property')];let me=[];const fe=se.value;return me=me.concat(We({key:se.key,value:fe,valueSpec:se.valueSpec,style:se.style,styleSpec:se.styleSpec,arrayElementValidator:re})),Array.isArray(fe)&&fe.length===0&&me.push(new a.V(se.key,fe,"array must have at least one stop")),me},default:function(se){return Qs({key:se.key,value:se.value,valueSpec:v,style:se.style,styleSpec:se.styleSpec})}}});return S==="identity"&&q&&J.push(new a.V(x.key,x.value,'missing required property "property"')),S==="identity"||f.stops||J.push(new a.V(x.key,x.value,'missing required property "stops"')),S==="exponential"&&v.expression&&!a.M(v)&&J.push(new a.V(x.key,x.value,"exponential functions not supported")),x.styleSpec.$version>=8&&(G&&!a.N(v)?J.push(new a.V(x.key,x.value,"property functions not supported")):q&&!a.O(v)&&J.push(new a.V(x.key,x.value,"zoom functions not supported"))),S!=="categorical"&&!ee||f.property!==void 0||J.push(new a.V(x.key,x.value,'"property" property is required')),J;function re(se){let me=[];const fe=se.value,Ne=se.key;if(!Array.isArray(fe))return[new a.V(Ne,fe,`array expected, ${a.K(fe)} found`)];if(fe.length!==2)return[new a.V(Ne,fe,`array length 2 expected, length ${fe.length} found`)];if(ee){if(!a.H(fe[0]))return[new a.V(Ne,fe,`object expected, ${a.K(fe[0])} found`)];const Ae=fe[0];if(Ae.zoom===void 0)return[new a.V(Ne,fe,"object stop key must have zoom")];if(Ae.value===void 0)return[new a.V(Ne,fe,"object stop key must have value")];const Te=a.J(Ae.zoom);if(typeof Te!="number")return[new a.V(Ne,Ae.zoom,"stop zoom values must be numbers")];if(L&&L>Te)return[new a.V(Ne,Ae.zoom,"stop zoom values must appear in ascending order")];Te!==L&&(L=Te,E=void 0,B={}),me=me.concat(La({key:`${Ne}[0]`,value:fe[0],valueSpec:{zoom:{}},style:se.style,styleSpec:se.styleSpec,objectElementValidators:{zoom:_t,value:oe}}))}else me=me.concat(oe({key:`${Ne}[0]`,value:fe[0],style:se.style,styleSpec:se.styleSpec},fe));return a.Q(a.S(fe[1]))?me.concat([new a.V(`${Ne}[1]`,fe[1],"expressions are not allowed in function stops.")]):me.concat(Qs({key:`${Ne}[1]`,value:fe[1],valueSpec:v,style:se.style,styleSpec:se.styleSpec}))}function oe(se,me){const fe=a.K(se.value),Ne=a.J(se.value),Ae=se.value!==null?se.value:me;if(T){if(fe!==T)return[new a.V(se.key,Ae,`${fe} stop domain type must match previous stop domain type ${T}`)]}else T=fe;if(fe!=="number"&&fe!=="string"&&fe!=="boolean"&&typeof Ne!="number"&&typeof Ne!="string"&&typeof Ne!="boolean")return[new a.V(se.key,Ae,"stop domain value must be a number, string, or boolean")];if(fe!=="number"&&S!=="categorical"){let Te=`number expected, ${fe} found`;return a.N(v)&&S===void 0&&(Te+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new a.V(se.key,Ae,Te)]}return S!=="categorical"||fe!=="number"||typeof Ne=="number"&&isFinite(Ne)&&Math.floor(Ne)===Ne?S!=="categorical"&&fe==="number"&&typeof Ne=="number"&&typeof E=="number"&&E!==void 0&&Nenew a.V(`${x.key}${v.key}`,x.value,v.message));const f=u.value.expression||u.value._styleExpression.expression;if(x.expressionContext==="property"&&x.propertyKey==="text-font"&&!f.outputDefined())return[new a.V(x.key,x.value,`Invalid data expression for "${x.propertyKey}". Output values must be contained as literals within the expression.`)];if(x.expressionContext==="property"&&x.propertyType==="layout"&&!a.Z(f))return[new a.V(x.key,x.value,'"feature-state" data expressions are not supported with layout properties.')];if(x.expressionContext==="filter")return pr(f,x);if(x.expressionContext==="appearance")return kr(f,x);if(x.expressionContext&&x.expressionContext.indexOf("cluster")===0){if(!a.X(f,["zoom","feature-state"]))return[new a.V(x.key,x.value,'"zoom" and "feature-state" expressions are not supported with cluster properties.')];if(x.expressionContext==="cluster-initial"&&!a.Y(f))return[new a.V(x.key,x.value,"Feature data expressions are not supported with initial expression part of cluster properties.")]}return[]}function pr(x,u){const f=new Set(["zoom","feature-state","pitch","distance-from-center"]);if(u.valueSpec&&u.valueSpec.expression)for(const S of u.valueSpec.expression.parameters)f.delete(S);if(f.size===0)return[];const v=[];return x instanceof a._&&f.has(x.name)?[new a.V(u.key,u.value,`["${x.name}"] expression is not supported in a filter for a ${u.object.type} layer with id: ${u.object.id}`)]:(x.eachChild(S=>{v.push(...pr(S,u))}),v)}function kr(x,u){const f=new Set;if(u.valueSpec&&u.valueSpec.expression)for(const S of u.valueSpec.expression.parameters)f.add(S);if(f.size===0)return[];const v=[];return x instanceof a._&&!f.has(x.name)?[new a.V(u.key,u.value,`["${x.name}"] is not an allowed parameter`)]:(x.eachChild(S=>{v.push(...kr(S,u))}),v)}function Hr(x){const u=x.key,f=x.value,v=x.valueSpec,S=[];return Array.isArray(v.values)?v.values.indexOf(a.J(f))===-1&&S.push(new a.V(u,f,`expected one of [${v.values.join(", ")}], ${JSON.stringify(f)} found`)):Object.keys(v.values).indexOf(a.J(f))===-1&&S.push(new a.V(u,f,`expected one of [${Object.keys(v.values).join(", ")}], ${JSON.stringify(f)} found`)),S}function Fn(x){return a.a2(a.S(x.value))?rr(Object.assign({},x,{expressionContext:"filter",valueSpec:x.styleSpec[`filter_${x.layerType||"fill"}`]})):Os(x)}function Os(x){const u=x.value,f=x.key;if(!Array.isArray(u))return[new a.V(f,u,`array expected, ${a.K(u)} found`)];if(u.length<1)return[new a.V(f,u,"filter array must have at least 1 element")];const v=x.styleSpec;let S=Hr({key:`${f}[0]`,value:u[0],valueSpec:v.filter_operator});const T=()=>{u.length>=2&&(a.a0(u[1])||S.push(new a.V(`${f}[1]`,u[1],`string expected, ${a.K(u[1])} found`)));for(let E=2;E":case">=":u.length>=2&&a.J(u[1])==="$type"&&S.push(new a.V(f,u,`"$type" cannot be use with operator "${u[0]}"`)),u.length!==3&&S.push(new a.V(f,u,`filter array for operator "${u[0]}" must have 3 elements`)),T();break;case"==":case"!=":u.length!==3&&S.push(new a.V(f,u,`filter array for operator "${u[0]}" must have 3 elements`)),T();break;case"in":case"!in":T();break;case"any":case"all":case"none":for(let E=1;E{q in f&&u.push(new a.V(v,f[q],`"${q}" is prohibited for ref layers`))}),S.layers.forEach(q=>{a.J(q.id)===L&&(B=q)}),B?B.ref?u.push(new a.V(v,f.ref,"ref cannot reference another ref layer")):E=a.J(B.type):typeof L=="string"&&u.push(new a.V(v,f.ref,`ref layer "${L}" not found`))}else if(E!=="background"&&E!=="sky"&&E!=="slot")if(f.source)if(a.a0(f.source)){const B=S.sources&&S.sources[f.source],q=B&&a.J(B.type);B?q==="vector"&&E==="raster"?u.push(new a.V(v,f.source,`layer "${f.id}" requires a raster source`)):q==="raster"&&E!=="raster"?u.push(new a.V(v,f.source,`layer "${f.id}" requires a vector source`)):q!=="vector"||f["source-layer"]?q==="raster-dem"&&E!=="hillshade"?u.push(new a.V(v,f.source,"raster-dem source can only be used with layer type 'hillshade'.")):q!=="raster-array"||["raster","raster-particle"].includes(E)?E==="line"&&f.paint&&(f.paint["line-gradient"]||f.paint["line-trim-offset"])&&q==="geojson"&&!B.lineMetrics?u.push(new a.V(v,f,`layer "${f.id}" specifies a line-gradient, which requires the GeoJSON source to have \`lineMetrics\` enabled.`)):E==="raster-particle"&&q!=="raster-array"&&u.push(new a.V(v,f.source,`layer "${f.id}" requires a 'raster-array' source.`)):u.push(new a.V(v,f.source,"raster-array source can only be used with layer type 'raster'.")):u.push(new a.V(v,f,`layer "${f.id}" must specify a "source-layer"`)):u.push(new a.V(v,f.source,`source "${f.source}" not found`))}else u.push(new a.V(`${v}.source`,f.source,'"source" must be a string'));else u.push(new a.V(v,f,'missing required property "source"'));return u=u.concat(La({key:v,value:f,valueSpec:T.layer,style:x.style,styleSpec:x.styleSpec,objectElementValidators:{"*":()=>[],type:()=>Qs({key:`${v}.type`,value:f.type,valueSpec:T.layer.type,style:x.style,styleSpec:x.styleSpec,object:f,objectKey:"type"}),filter:B=>Fn(Object.assign({layerType:E},B)),layout:B=>La({layer:f,key:B.key,value:B.value,valueSpec:{},style:B.style,styleSpec:B.styleSpec,objectElementValidators:{"*":q=>zo(Object.assign({layerType:E},q))}}),paint:B=>La({layer:f,key:B.key,value:B.value,valueSpec:{},style:B.style,styleSpec:B.styleSpec,objectElementValidators:{"*":q=>pa(Object.assign({layerType:E,layer:f},q))}}),appearances(B){const q=We({key:B.key,value:B.value,valueSpec:B.valueSpec,style:B.style,styleSpec:B.styleSpec,arrayElementValidator:J=>function(re){const{key:oe,layer:se,layerType:me}=re,fe=a.J(re.value),Ne=a.J(fe.name),Ae=a.J(fe.condition),Te=La({key:oe,value:fe,valueSpec:re.styleSpec.appearance,style:re.style,styleSpec:re.styleSpec,objectElementValidators:{condition:Ze=>function($e){const He=[];return He.push(...rr({key:$e.key,value:$e.object.condition,valueSpec:a.a6.appearance.condition,expressionContext:"appearance"})),He}(Object.assign({layer:se,layerType:me},Ze)),properties:Ze=>function($e){const He=[],{styleSpec:ze,layer:De,layerType:Qe}=$e,ht=ze[`paint_${Qe}`],ot=ze[`layout_${Qe}`],Tt=$e.object[$e.objectKey];for(const At in Tt){const Bt=At in ht?"paint":At in ot?"layout":void 0;if(!Bt){He.push(new a.V($e.key,At,`unknown property "${At}" for layer type "${Qe}"`));continue}const or=Object.assign({},$e,{key:`${$e.key}.${At}`,object:Tt,objectKey:At,layer:De,layerType:Qe,value:Tt[At],valueSpec:Bt==="paint"?ht[At]:ot[At]});He.push(...ia(or,Bt))}return He}(Object.assign({layer:se,layerType:me},Ze))}});return Ne!=="hidden"&&Ae===void 0&&Te.push(new a.V(re.key,"name",'Appearance with name different than "hidden" must have a condition')),Te}(Object.assign({layerType:E,layer:f},J))}),G=Array.isArray(B.value)?B.value:[],ee=new Set;return G.forEach((J,re)=>{const oe=a.J(J.name);if(oe)if(ee.has(oe)){const se=a.J(f.id);q.push(new a.V(B.key,oe,`Duplicated appearance name "${oe}" for layer "${se}"`))}else ee.add(oe)}),q}}})),u}function Xs({key:x,value:u}){return a.a0(u)?[]:[new a.V(x,u,`string expected, ${a.K(u)} found`)]}const Ma={promoteId:function x({key:u,value:f}){if(a.a0(f))return Xs({key:u,value:f});if(Array.isArray(f)){const S=[],T=a.S(f),E=a.U(T);return E.result==="error"&&E.value.forEach(L=>{S.push(new a.V(`${u}${L.key}`,null,`${L.message}`))}),a.X(E.value.expression,["zoom","heatmap-density","line-progress","raster-value","sky-radial-progress","accumulated","is-supported-script","pitch","distance-from-center","measure-light","raster-particle-speed"])||S.push(new a.V(`${u}`,null,"promoteId expression should be only feature dependent")),S}if(!a.H(f))return[new a.V(u,f,`string, expression or object expected, "${a.K(f)}" found`)];const v=[];for(const S in f)v.push(...x({key:`${u}.${S}`,value:f[S]}));return v}};function Qo(x){const u=x.value,f=x.key,v=x.styleSpec,S=x.style;if(!a.H(u))return[new a.V(f,u,`object expected, ${a.K(u)} found`)];if(!("type"in u))return[new a.V(f,u,'"type" is required')];const T=a.J(u.type);let E=[];switch(["vector","raster","raster-dem","raster-array"].includes(T)&&("url"in u||"tiles"in u||E.push(new a.a3(f,u,'Either "url" or "tiles" is required.'))),T){case"vector":case"raster":case"raster-dem":case"raster-array":return E=E.concat(La({key:f,value:u,valueSpec:v[`source_${T.replace("-","_")}`],style:x.style,styleSpec:v,objectElementValidators:Ma})),E;case"geojson":if(E=La({key:f,value:u,valueSpec:v.source_geojson,style:S,styleSpec:v,objectElementValidators:Ma}),"cluster"in u&&"clusterProperties"in u){if(!a.H(u.clusterProperties))return[new a.V(`${f}.clusterProperties`,u,`object expected, ${a.K(u)} found`)];for(const L in u.clusterProperties){const B=u.clusterProperties[L];if(!Array.isArray(B))return[new a.V(`${f}.clusterProperties.${L}`,B,"array expected")];const[q,G]=B,ee=typeof q=="string"?[q,["accumulated"],["get",L]]:q;E.push(...rr({key:`${f}.${L}.map`,value:G,expressionContext:"cluster-map"})),E.push(...rr({key:`${f}.${L}.reduce`,value:ee,expressionContext:"cluster-reduce"}))}}return E;case"video":return La({key:f,value:u,valueSpec:v.source_video,style:S,styleSpec:v});case"image":return La({key:f,value:u,valueSpec:v.source_image,style:S,styleSpec:v});case"canvas":return[new a.V(f,null,"Please use runtime APIs to add canvas sources, rather than including them in stylesheets.","source.canvas")];default:return Hr({key:`${f}.type`,value:u.type,valueSpec:{values:ec(v)}})}}function ec(x){return x.source.reduce((u,f)=>{const v=x[f];return v.type.type==="enum"&&(u=u.concat(Object.keys(v.type.values||{}))),u},[])}function yl(x){const u=x.value,f=x.styleSpec,v=f.light,S=x.style;if(u===void 0)return[];if(!a.H(u))return[new a.V("light",u,`object expected, ${a.K(u)} found`)];let T=[];for(const E in u){const L=E.match(/^(.*)-transition$/),B=E.match(/^(.*)-use-theme$/);T=T.concat(B&&v[B[1]]?Qs({key:E,value:u[E],valueSpec:{type:"string"},style:S,styleSpec:f}):L&&v[L[1]]&&v[L[1]].transition?Qs({key:E,value:u[E],valueSpec:f.transition,style:S,styleSpec:f}):v[E]?Qs({key:E,value:u[E],valueSpec:v[E],style:S,styleSpec:f}):[new a.V(E,u[E],`unknown property "${E}"`)])}return T}function tc(x){const u=x.value;if(!u)return[];const f=x.key;if(!a.H(u))return[new a.V(f,u,`object expected, ${a.K(u)} found`)];let v=[];const S=x.styleSpec,T=S["light-3d"],E=x.style,L=x.style.lights;for(const G of["type","id"])if(!(G in u))return v=v.concat([new a.V(f,u,`missing property "${G}"`)]),v;if(!a.a0(u.type))return v=v.concat([new a.V(`${f}.type`,u.type,"string expected")]),v;if(L)for(let G=0;G[],array:We,boolean:function(x){const u=x.value,f=x.key;return a.$(u)?[]:[new a.V(f,u,`boolean expected, ${a.K(u)} found`)]},number:_t,color:function({key:x,value:u}){return a.a0(u)?a.a1.parseCSSColor(u)===null?[new a.V(x,u,`color expected, "${u}" found`)]:[]:[new a.V(x,u,`color expected, ${a.K(u)} found`)]},enum:Hr,filter:Fn,function:Gt,layer:Xo,object:La,source:Qo,model:a.a7,light:yl,"light-3d":tc,terrain:Jo,fog:wh,string:Xs,formatted:function(x){return Xs(x).length===0?[]:rr(x)},resolvedImage:function(x){return Xs(x).length===0?[]:rr(x)},projection:function(x){const u=x.value,f=x.styleSpec,v=f.projection,S=x.style;if(a.H(u)){let T=[];for(const E in u)T=T.concat(Qs({key:E,value:u[E],valueSpec:v[E],style:S,styleSpec:f}));return T}return a.a0(u)?[]:[new a.V("projection",u,`object or string expected, ${a.K(u)} found`)]},import:function(x){const u=x.key,{value:f,styleSpec:v}=x;if(!a.H(f))return[new a.V(u,f,"import must be an object")];const{data:S,...T}=f;Object.defineProperty(T,"__line__",{value:f.__line__,enumerable:!1});let E=La(Object.assign({},x,{value:T,valueSpec:v.import}));return a.J(T.id)===""&&E.push(new a.V(`${x.key}.id`,T,"import id can't be an empty string")),S&&(E=E.concat(bi(S,v,{key:`${x.key}.data`}))),E},iconset:function(x){const u=x.value,f=x.key,v=x.styleSpec,S=x.style;if(!a.H(u))return[new a.V(f,u,"object expected")];if(!u.type)return[new a.V(f,u,'"type" is required')];const T=a.J(u.type);let E=[];if(E=E.concat(La({key:f,value:u,valueSpec:v[`iconset_${T}`],style:S,styleSpec:v})),function(L,B){return!(L!=="source"||!B.source)}(T,u)){const L=S.sources&&S.sources[u.source],B=L&&a.J(L.type);L?B!=="raster-array"&&E.push(new a.V(f,u.source,`iconset cannot be used with a source of type ${String(B)}, it only be used with a "raster-array" source type`)):E.push(new a.V(f,u.source,`source "${u.source}" not found`))}return E}};function Qs(x,u=!1){const f=x.value,v=x.valueSpec,S=x.styleSpec;if(v.expression){if(a.a4(a.J(f)))return Gt(x);if(a.Q(a.S(f)))return rr(x)}if(v.type&&xa[v.type]){const T=xa[v.type](x);return u===!0&&T.length>0&&Array.isArray(x.value)?rr(x):T}return La(Object.assign({},x,{valueSpec:v.type?S[v.type]:v}))}function La(x){const u=x.key,f=x.value,v=x.valueSpec||{},S=x.objectElementValidators||{},T=x.style,E=x.styleSpec;if(!a.H(f))return[new a.V(u,f,`object expected, ${a.K(f)} found`)];let L=[];for(const B in f){const q=B.split(".")[0];let G;S[q]?G=S[q]:v[q]?G=Qs:S["*"]?G=S["*"]:v["*"]&&(G=Qs),G?L=L.concat(G({key:(u&&`${u}.`)+B,value:f[B],valueSpec:v[q]||v["*"],style:T,styleSpec:E,object:f,objectKey:B},f)):L.push(new a.a3(u,f[B],`unknown property "${B}"`))}for(const B in v){if(S[B])continue;const q=v[B];q.required&&q.default===void 0&&f[B]===void 0&&L.push(new a.V(u,f,`missing required property "${B}"`))}return L}function Ss({key:x,value:u}){const f=Xs({key:x,value:u});if(f.length)return f;const v=u;return v.indexOf("{fontstack}")===-1&&f.push(new a.V(x,u,'"glyphs" url must include a "{fontstack}" token')),v.indexOf("{range}")===-1&&f.push(new a.V(x,u,'"glyphs" url must include a "{range}" token')),f}function bi(x,u=a.a6,f={}){return La({key:f.key||"",value:x,valueSpec:Object.assign(u.$root,{"*":{type:"*"}}),styleSpec:u,style:x,objectElementValidators:{glyphs:Ss}})}function ki(x,u=a.a6){return be(bi(x,u))}const yo=x=>be(Qo(x)),Wt=x=>be(yl(x)),xo=x=>be(tc(x)),zc=x=>be(Jo(x)),oo=x=>be(wh(x)),Xn=x=>be(function(u){const f=u.value,v=u.style,S=u.styleSpec,T=S.snow;if(f===void 0)return[];if(!a.H(f))return[new a.V("snow",f,`object expected, ${a.K(f)} found`)];let E=[];for(const L in f){const B=L.match(/^(.*)-transition$/);E=E.concat(B&&T[B[1]]&&T[B[1]].transition?Qs({key:L,value:f[L],valueSpec:S.transition,style:v,styleSpec:S}):T[L]?Qs({key:L,value:f[L],valueSpec:T[L],style:v,styleSpec:S}):[new a.a3(L,f[L],`unknown property "${L}"`)])}return E}(x)),Bo=x=>be(function(u){const f=u.value,v=u.style,S=u.styleSpec,T=S.rain;if(f===void 0)return[];if(!a.H(f))return[new a.V("rain",f,`object expected, ${a.K(f)} found`)];let E=[];for(const L in f){const B=L.match(/^(.*)-transition$/);E=E.concat(B&&T[B[1]]&&T[B[1]].transition?Qs({key:L,value:f[L],valueSpec:S.transition,style:v,styleSpec:S}):T[L]?Qs({key:L,value:f[L],valueSpec:T[L],style:v,styleSpec:S}):[new a.a3(L,f[L],`unknown property "${L}"`)])}return E}(x)),Px=x=>be(Xo(x)),jh=x=>be(Fn(x)),Fp=x=>be(pa(x)),vt=x=>be(zo(x)),ue=x=>be(a.a7(x));function be(x){return x.slice().sort((u,f)=>u.line&&f.line?u.line-f.line:0)}function Re(x,u){let f=!1;if(u&&u.length)for(const v of u)v instanceof a.a3?a.w(v.message):(x.fire(new a.y(new Error(v.message))),f=!0);return f}const tt=a.a6.light;let Xe;class lt extends a.E{constructor(u,f="flat"){super(),this._transitionable=new a.a8(Xe||(Xe=new a.a9({anchor:new a.aa(tt.anchor),position:new a.ab(tt.position),color:new a.aa(tt.color),intensity:new a.aa(tt.intensity)}))),this.setLight(u,f),this._transitioning=this._transitionable.untransitioned()}getLight(){return this._transitionable.serialize()}setLight(u,f,v={}){this._validate(Wt,u,v)||(this._transitionable.setTransitionOrValue(u),this.id=f)}updateTransitions(u){this._transitioning=this._transitionable.transitioned(u,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(u){this.properties=this._transitioning.possiblyEvaluate(u)}_validate(u,f,v){return(!v||v.validate!==!1)&&Re(this,u.call(ki,Object.assign({value:f,style:{glyphs:!0,sprite:!0},styleSpec:a.a6})))}}const Ct=a.a6.terrain;let dt=class extends a.E{constructor(x,u,f,v,S){super(),this.scope=f,this._transitionable=new a.a8(new a.a9({source:new a.aa(Ct.source),exaggeration:new a.aa(Ct.exaggeration)}),f,v),this._transitionable.setTransitionOrValue(x,v),this._transitioning=this._transitionable.untransitioned(),this.drapeRenderMode=u,this.worldview=S}get(){return this._transitionable.serialize()}set(x,u){this._transitionable.setTransitionOrValue(x,u)}updateTransitions(x){this._transitioning=this._transitionable.transitioned(x,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(x){this.properties=this._transitioning.possiblyEvaluate(x)}getExaggeration(x){return this._transitioning.possiblyEvaluate(new a.ac(x,{worldview:this.worldview})).get("exaggeration")}getAttenuationRange(){if(!this.isZoomDependent())return null;const x=this._transitionable._values.exaggeration;if(!x)return null;const u=x.value.expression;if(!u)return null;let f=-1,v=-1,S=1;for(const T of u.zoomStops)S=u.evaluate(new a.ac(T,{worldview:this.worldview})),S>.01?(f=T,v=-1):v=T;return S<.01&&f>0&&v>f?[f,v]:null}isZoomDependent(){const x=this._transitionable._values.exaggeration;return x!=null&&x.value!=null&&x.value.expression!=null&&x.value.expression instanceof a.ad}};const St=45,sr=65,Ut=.05;function Ir(x,u,f,v){const S=a.ah(St,sr,f),[T,E]=en(x,v);let L=1-Math.min(1,Math.exp((u-T)/(E-T)*-6));return L*=L*L,L=Math.min(1,1.00747*L),L*S*x.alpha}function en(x,u){const f=.5/Math.tan(.5*u);return[x.range[0]+f,x.range[1]+f]}function Ge(x,u,f,v,S){const T=a.af([],[u,f,v],S.mercatorFogMatrix);return Ir(x,a.ag(T),S.pitch,S._fov)}function ur(x,u,f,v,S,T,E){const L=[[f,v,0],[S,v,0],[S,T,0],[f,T,0]];let B=Number.MAX_VALUE,q=-Number.MAX_VALUE;for(const G of L){const ee=a.af([],G,u),J=a.ag(ee);B=Math.min(B,J),q=Math.max(q,J)}return[Ir(x,B,E.pitch,E._fov),Ir(x,q,E.pitch,E._fov)]}const jr=a.a6.fog;class Vr extends a.E{constructor(u,f,v,S){super();const T=new a.a9({range:new a.aa(jr.range),color:new a.aa(jr.color),"color-use-theme":new a.aa({type:"string","property-type":"data-constant",default:"default"}),"high-color":new a.aa(jr["high-color"]),"high-color-use-theme":new a.aa({type:"string","property-type":"data-constant",default:"default"}),"space-color":new a.aa(jr["space-color"]),"space-color-use-theme":new a.aa({type:"string","property-type":"data-constant",default:"default"}),"horizon-blend":new a.aa(jr["horizon-blend"]),"star-intensity":new a.aa(jr["star-intensity"]),"vertical-range":new a.aa(jr["vertical-range"])});this._transitionable=new a.a8(T,v,new Map(S)),this.set(u,S),this._transitioning=this._transitionable.untransitioned(),this._transform=f,this.properties=new a.ai(T),this.scope=v}get state(){const u=this._transform,f=u.projection.name==="globe",v=a.aj(u.zoom),S=this.properties.get("range"),T=[.5,3];return{range:f?[a.ak(T[0],S[0],v),a.ak(T[1],S[1],v)]:S,horizonBlend:this.properties.get("horizon-blend"),alpha:this.properties.get("color").a}}get(){return this._transitionable.serialize()}set(u,f,v={}){if(this._validate(oo,u,v))return;const S=Object.assign({},u);for(const T of Object.keys(jr))S[T]===void 0&&(S[T]=jr[T].default);this._options=S,this._transitionable.setTransitionOrValue(this._options,f)}getOpacity(u){if(!this._transform.projection.supportsFog)return 0;const f=this.properties&&this.properties.get("color")||1;return(this._transform.projection.name==="globe"?1:a.ah(St,sr,u))*f.a}getOpacityAtLatLng(u,f){return this._transform.projection.supportsFog?function(v,S,T){const E=a.ae.fromLngLat(S),L=T.elevation?T.elevation.getAtPointOrZero(E):0;return Ge(v,E.x,E.y,L,T)}(this.state,u,f):0}getOpacityForTile(u){if(!this._transform.projection.supportsFog)return[1,1];const f=this._transform.calculateFogTileMatrix(u.toUnwrapped());return ur(this.state,f,0,0,a.al,a.al,this._transform)}getOpacityForBounds(u,f,v,S,T){return this._transform.projection.supportsFog?ur(this.state,u,f,v,S,T,this._transform):[1,1]}getFovAdjustedRange(u){return this._transform.projection.supportsFog?en(this.state,u):[0,1]}isVisibleOnFrustum(u){if(!this._transform.projection.supportsFog)return!1;const f=[4,5,6,7];for(const v of f){const S=u.points[v];let T;if(S[2]>=0)T=S;else{const E=u.points[v-4];T=a.am(E,S,E[2]/(E[2]-S[2]))}if(Ge(this.state,T[0],T[1],0,this._transform)>=Ut)return!0}return!1}updateConfig(u){this._transitionable.setTransitionOrValue(this._options,new Map(u))}updateTransitions(u){this._transitioning=this._transitionable.transitioned(u,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(u){this.properties=this._transitioning.possiblyEvaluate(u)}_validate(u,f,v){return(!v||v.validate!==!1)&&Re(this,u.call(ki,Object.assign({value:f,style:{glyphs:!0,sprite:!0},styleSpec:a.a6})))}}let cn,Ns,Mi,Zi,Oa=class extends a.E{constructor(x,u,f,v){super();const S=cn||(cn=new a.a9({density:new a.aa(a.a6.snow.density),intensity:new a.aa(a.a6.snow.intensity),color:new a.aa(a.a6.snow.color),opacity:new a.aa(a.a6.snow.opacity),vignette:new a.aa(a.a6.snow.vignette),"vignette-color":new a.aa(a.a6.snow["vignette-color"]),"center-thinning":new a.aa(a.a6.snow["center-thinning"]),direction:new a.aa(a.a6.snow.direction),"flake-size":new a.aa(a.a6.snow["flake-size"])}));this._transitionable=new a.a8(S,f,new Map(v)),this.set(x,v),this._transitioning=this._transitionable.untransitioned(),this.properties=new a.ai(S),this.scope=f}get state(){const x=this.properties.get("opacity"),u=this.properties.get("color"),f=this.properties.get("direction"),v=a.an(f[0]),S=-Math.max(a.an(f[1]),.01),T=[Math.cos(v)*Math.cos(S),Math.sin(v)*Math.cos(S),Math.sin(S)],E=this.properties.get("vignette"),L=this.properties.get("vignette-color");return L.a=E,{density:this.properties.get("density"),intensity:this.properties.get("intensity"),color:new a.ao(u.r,u.g,u.b,u.a*x),direction:T,centerThinning:this.properties.get("center-thinning"),flakeSize:this.properties.get("flake-size"),vignetteColor:L}}get(){return this._transitionable.serialize()}set(x,u,f={}){if(this._validate(Xn,x,f))return;const v=Object.assign({},x),S=a.a6.snow;for(const T of Object.keys(S))v[T]===void 0&&(v[T]=S[T].default);this._options=v,this._transitionable.setTransitionOrValue(this._options,u)}updateConfig(x){this._transitionable.setTransitionOrValue(this._options,new Map(x))}updateTransitions(x){this._transitioning=this._transitionable.transitioned(x,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(x){this.properties=this._transitioning.possiblyEvaluate(x)}_validate(x,u,f){return(!f||f.validate!==!1)&&Re(this,x.call(ki,Object.assign({value:u,style:{glyphs:!0,sprite:!0},styleSpec:a.a6})))}},Yi=class extends a.E{constructor(x,u,f,v){super();const S=Ns||(Ns=new a.a9({density:new a.aa(a.a6.rain.density),intensity:new a.aa(a.a6.rain.intensity),color:new a.aa(a.a6.rain.color),opacity:new a.aa(a.a6.rain.opacity),vignette:new a.aa(a.a6.rain.vignette),"vignette-color":new a.aa(a.a6.rain["vignette-color"]),"center-thinning":new a.aa(a.a6.rain["center-thinning"]),direction:new a.aa(a.a6.rain.direction),"droplet-size":new a.aa(a.a6.rain["droplet-size"]),"distortion-strength":new a.aa(a.a6.rain["distortion-strength"])}));this._transitionable=new a.a8(S,f,new Map(v)),this.set(x,v),this._transitioning=this._transitionable.untransitioned(),this.properties=new a.ai(S),this.scope=f}get state(){const x=this.properties.get("opacity"),u=this.properties.get("color"),f=this.properties.get("direction"),v=a.an(f[0]),S=-Math.max(a.an(f[1]),.01),T=[Math.cos(v)*Math.cos(S),Math.sin(v)*Math.cos(S),Math.sin(S)],E=this.properties.get("vignette-color");return E.a=this.properties.get("vignette"),{density:this.properties.get("density"),intensity:this.properties.get("intensity"),color:new a.ao(u.r,u.g,u.b,u.a*x),direction:T,centerThinning:this.properties.get("center-thinning"),dropletSize:this.properties.get("droplet-size"),distortionStrength:this.properties.get("distortion-strength"),vignetteColor:E}}get(){return this._transitionable.serialize()}set(x,u,f={}){if(this._validate(Bo,x,f))return;const v=Object.assign({},x),S=a.a6.rain;for(const T of Object.keys(S))v[T]===void 0&&(v[T]=S[T].default);this._options=v,this._transitionable.setTransitionOrValue(this._options,u)}updateConfig(x){this._transitionable.setTransitionOrValue(this._options,new Map(x))}updateTransitions(x){this._transitioning=this._transitionable.transitioned(x,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(x){this.properties=this._transitioning.possiblyEvaluate(x)}_validate(x,u,f){return(!f||f.validate!==!1)&&Re(this,x.call(ki,Object.assign({value:u,style:{glyphs:!0,sprite:!0},styleSpec:a.a6})))}};class _s extends a.E{constructor(u,f,v,S){super(),this.scope=v,this._options=u,this.properties=new a.ai(f),this._transitionable=new a.a8(f,v,new Map(S)),this._transitionable.setTransitionOrValue(u.properties),this._transitioning=this._transitionable.untransitioned()}updateConfig(u){this._transitionable.setTransitionOrValue(this._options.properties,new Map(u))}updateTransitions(u){this._transitioning=this._transitionable.transitioned(u,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(u){this.properties=this._transitioning.possiblyEvaluate(u)}get(){return this._options.properties=this._transitionable.serialize(),this._options}set(u,f){this._options=u,this._transitionable.setTransitionOrValue(u.properties,f)}shadowsEnabled(){return!!this.properties&&this.properties.get("cast-shadows")===!0}}class Xi{constructor(u,f,v){this.screenBounds=u,this.cameraPoint=v.getCameraPoint(),this._screenRaycastCache={},this._cameraRaycastCache={},this.isAboveHorizon=f,this.screenGeometry=this.bufferedScreenGeometry(0),this.screenGeometryMercator=this._bufferedScreenMercator(0,v)}static createFromScreenPoints(u,f){let v,S;if(u instanceof a.P||typeof u[0]=="number"){const T=a.P.convert(u);v=[T],S=f.isPointAboveHorizon(T)}else{const T=a.P.convert(u[0]),E=a.P.convert(u[1]),L=T.add(E)._div(2);v=[T,E],S=a.aq(T,E).every(B=>f.isPointAboveHorizon(B))&&f.isPointAboveHorizon(L)}return new Xi(v,S,f)}isPointQuery(){return this.screenBounds.length===1}bufferedScreenGeometry(u){return a.aq(this.screenBounds[0],this.screenBounds.length===1?this.screenBounds[0]:this.screenBounds[1],u)}bufferedCameraGeometry(u){const f=this.screenBounds[0],v=this.screenBounds.length===1?this.screenBounds[0].add(new a.P(1,1)):this.screenBounds[1],S=a.aq(f,v,0,!1);return this.cameraPoint.y>v.y&&(this.cameraPoint.x>f.x&&this.cameraPoint.x=v.x?S[2]=this.cameraPoint:this.cameraPoint.x<=f.x&&(S[3]=this.cameraPoint)),a.ar(S,u)}bufferedCameraGeometryGlobe(u){const f=this.screenBounds[0],v=this.screenBounds.length===1?this.screenBounds[0].add(new a.P(1,1)):this.screenBounds[1],S=a.aq(f,v,u),T=this.cameraPoint.clone();switch(3*((T.y>f.y)+(T.y>v.y))+((T.x>f.x)+(T.x>v.x))){case 0:S[0]=T,S[4]=T.clone();break;case 1:S.splice(1,0,T);break;case 2:S[1]=T;break;case 3:S.splice(4,0,T);break;case 5:S.splice(2,0,T);break;case 6:S[3]=T;break;case 7:S.splice(3,0,T);break;case 8:S[2]=T}return S}containsTile(u,f,v,S=0){const T=Math.max(u.queryPadding,u.evaluateQueryRenderedFeaturePadding())/f._pixelsPerMercatorPixel+1,E=v?this._bufferedCameraMercator(T,f):this._bufferedScreenMercator(T,f);let L=u.tileID.wrap+(E.unwrapped?S:0);const B=E.polygon.map(me=>a.as(u.tileTransform,me,L));if(!a.at(B,0,0,a.al,a.al))return;L=u.tileID.wrap+(this.screenGeometryMercator.unwrapped?S:0);const q=this.screenGeometryMercator.polygon.map(me=>a.au(u.tileTransform,me,L)),G=q.map(me=>new a.P(me[0],me[1])),ee=f.getFreeCameraOptions().position||new a.ae(0,0,0),J=a.au(u.tileTransform,ee,L),re=q.map(me=>{const fe=a.av(me,me,J);return a.aw(fe,fe),new a.ax(J,fe)}),oe=a.ay(u,1,f.zoom)*f._pixelsPerMercatorPixel;return{queryGeometry:this,tilespaceGeometry:G,tilespaceRays:re,bufferedTilespaceGeometry:B,bufferedTilespaceBounds:(se=a.az(B),se.min.x=a.aA(se.min.x,0,a.al),se.min.y=a.aA(se.min.y,0,a.al),se.max.x=a.aA(se.max.x,0,a.al),se.max.y=a.aA(se.max.y,0,a.al),se),tile:u,tileID:u.tileID,pixelToTileUnitsFactor:oe};var se}_bufferedScreenMercator(u,f){const v=ca(u);if(this._screenRaycastCache[v])return this._screenRaycastCache[v];{let S;return S=f.projection.name==="globe"?this._projectAndResample(this.bufferedScreenGeometry(u),f):{polygon:this.bufferedScreenGeometry(u).map(T=>f.pointCoordinate3D(T)),unwrapped:!0},this._screenRaycastCache[v]=S,S}}_bufferedCameraMercator(u,f){const v=ca(u);if(this._cameraRaycastCache[v])return this._cameraRaycastCache[v];{let S;return S=f.projection.name==="globe"?this._projectAndResample(this.bufferedCameraGeometryGlobe(u),f):{polygon:this.bufferedCameraGeometry(u).map(T=>f.pointCoordinate3D(T)),unwrapped:!0},this._cameraRaycastCache[v]=S,S}}_projectAndResample(u,f){const v=function(T,E){const L=a.aB([],E.pixelMatrix,E.globeMatrix),B=[0,-a.aD,0,1],q=[0,a.aD,0,1],G=[0,0,0,1];a.aC(B,B,L),a.aC(q,q,L),a.aC(G,G,L);const ee=new a.P(B[0]/B[3],B[1]/B[3]),J=new a.P(q[0]/q[3],q[1]/q[3]),re=a.aE(T,ee)&&B[3]1?gi(T.slice(0,me),E):[],Ae=menew a.P(is(He.x),He.y)),Ae=Ae.map(He=>new a.P(is(He.x),He.y));const Te=[...Ne];Te.length===0&&Te.push(Ae[Ae.length-1]);const Ze=a.ak(Te[Te.length-1].y,(Ae.length===0?Ne[0]:Ae[0]).y,fe);let $e;return $e=re?[new a.P(0,Ze),new a.P(0,0),new a.P(1,0),new a.P(1,Ze)]:[new a.P(1,Ze),new a.P(1,1),new a.P(0,1),new a.P(0,Ze)],Te.push(...$e),Ae.length===0?Te.push(Ne[0]):Te.push(...Ae),{polygon:Te.map(He=>new a.ae(He.x,He.y)),unwrapped:!1}}(u,f);if(v)return v;const S=function(T,E){let L=!1,B=-1/0,q=0;for(let ee=0;eeB&&(B=T[ee].x,q=ee);for(let ee=0;ee.5&&(re.x{ee.x-=1}),{polygon:T,unwrapped:L}}(gi(u,f).map(T=>new a.P(is(T.x),T.y)),f);return{polygon:S.polygon.map(T=>new a.ae(T.x,T.y)),unwrapped:S.unwrapped}}}function gi(x,u){return a.aG(x,f=>{const v=u.pointCoordinate3D(f);f.x=v.x,f.y=v.y},1/256)}function is(x){return x<0?1+x%1:x%1}function ca(x){return 100*x|0}function $o(x,u,f,v,S){const T=function(L,B){if(L)return S(L);if(B){if(x.url&&B.tiles&&x.tiles&&delete x.tiles,B.variants){if(!Array.isArray(B.variants))return S(new Error("variants must be an array"));for(const G of B.variants){if(G==null||typeof G!="object"||G.constructor!==Object)return S(new Error("variant must be an object"));if(!Array.isArray(G.capabilities))return S(new Error("capabilities must be an array"));if(G.capabilities.length===1&&G.capabilities[0]==="meshopt"){B=Object.assign(B,G);break}}}const q=a.aH(Object.assign({},B,x),["tilejson","tiles","minzoom","maxzoom","attribution","mapbox_logo","bounds","extra_bounds","scheme","tileSize","encoding","vector_layers","raster_layers","worldview_options","worldview_default","worldview"]);q.tiles=u.canonicalizeTileset(q,x.url),S(null,q)}},E=function(L,B,q){if(!L)return null;if(!B&&!q)return L;q=q||L.worldview_default;const G=Object.values(L.language||{});if(G.length===0)return null;const ee=Object.values(L.worldview||{});if(ee.length===0)return null;const J=G.every(oe=>oe===B),re=ee.every(oe=>oe===q);return J&&re?L:B in(L.language_options||{})||q in(L.worldview_options||{})?null:L.language_options&&L.worldview_options?L:null}(x.data,f,v);return E?a.o.frame(()=>T(null,E)):x.url?a.m(u.transformRequest(u.normalizeSourceURL(x.url,null,f,v),a.R.Source),T):a.o.frame(()=>{const{data:L,...B}=x;T(null,B)})}function el(x,u){const f=Math.pow(2,u.z),v=Math.floor(a.aF(x.getWest())*f),S=Math.floor(a.aJ(x.getNorth())*f),T=Math.ceil(a.aF(x.getEast())*f),E=Math.ceil(a.aJ(x.getSouth())*f);return u.x>=v&&u.x=S&&u.ythis.maxzoom||u.z{if(this._tileJSONRequest=null,this._loaded=!0,S)f&&console.warn(`Ensure that your requested language string is a valid BCP-47 code or list of codes. Found: ${f}`),v&&console.warn(`Requested worldview strings must be a valid ISO alpha-2 code. Found: ${v}`),this.fire(new a.y(S));else if(T){if(Object.assign(this,T),this.hasWorldviews=!!T.worldview_options,T.worldview_default&&(this.worldviewDefault=T.worldview_default),T.vector_layers){this.vectorLayers=T.vector_layers,this.vectorLayerIds=[],this.localizableLayerIds=new Set;for(const E of T.vector_layers)this.vectorLayerIds.push(E.id),T.worldview&&T.worldview[E.source]&&this.localizableLayerIds.add(E.id)}this.tileBounds=rc.fromTileJSON(T),Ye(T.tiles,this.map._requestManager._customAccessToken),this.fire(new a.z("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new a.z("data",{dataType:"source",sourceDataType:"content"}))}u&&u(S)})}loaded(){return this._loaded}hasTile(u){return!this.tileBounds||this.tileBounds.contains(u.canonical)}onAdd(u){this.map=u,this.load()}reload(){this.cancelTileJSONRequest();const u=a.B(this.id,this.scope);this.load(()=>this.map.style.clearSource(u))}setTiles(u){return this._options.tiles=u,this.reload(),this}setUrl(u){return this.url=u,this._options.url=u,this.reload(),this}onRemove(u){this.cancelTileJSONRequest()}serialize(){return Object.assign({},this._options)}loadTile(u,f){const v=u.tileID.canonical.url(this.tiles,this.scheme),S=this.map._requestManager.normalizeTileURL(v),T=this.map._requestManager.transformRequest(S,a.R.Tile),E=this.map.style?this.map.style.getLut(this.scope):null,L=E?{image:E.image.clone()}:null,B={request:T,data:void 0,uid:u.uid,tileID:u.tileID,tileZoom:u.tileZoom,zoom:u.tileID.overscaledZ,maxZoom:this.maxzoom,lut:L,tileSize:this.tileSize*u.tileID.overscaleFactor(),type:this.type,source:this.id,scope:this.scope,pixelRatio:a.o.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,isSymbolTile:u.isSymbolTile,brightness:this.map.style&&this.map.style.getBrightness()||0,extraShadowCaster:u.isExtraShadowCaster,tessellationStep:this.map._tessellationStep,scaleFactor:this.map.getScaleFactor(),worldview:this.map.getWorldview()||this.worldviewDefault,indoor:this.map.indoor?this.map.indoor.getIndoorTileOptions(this.id,this.scope):null};if(this.hasWorldviews&&a.h(v)&&(B.localizableLayerIds=this.localizableLayerIds),B.request.collectResourceTiming=this._collectResourceTiming,u.actor&&u.state!=="expired")u.state==="loading"?u.reloadCallback=f:u.request=u.actor.send("reloadTile",B,q.bind(this));else if(u.actor=this._tileWorkers[S]=this._tileWorkers[S]||this.dispatcher.getActor(),this.dispatcher.ready)u.request=u.actor.send("loadTile",B,q.bind(this),void 0,!0);else{const G=a.aL.call({deduped:this._deduped},B,(ee,J)=>{if(ee||!J)q.call(this,ee);else{const re=a.aM(J.responseHeaders);B.data={rawData:J.rawData.slice(0),expires:re.expires,cacheControl:re.cacheControl},u.actor&&u.actor.send("loadTile",B,q.bind(this),void 0,!0)}},!0);u.request={cancel:G}}function q(G,ee){return delete u.request,u.aborted?f(null):G&&G instanceof a.aN&&G.status!==404?f(G):(ee&&ee.resourceTiming&&(u.resourceTiming=ee.resourceTiming),this.map._refreshExpiredTiles&&ee&&u.setExpiryData(ee),u.loadVectorData(ee,this.map.painter),a.aO(this.dispatcher),f(null,ee),void(u.reloadCallback&&(this.loadTile(u,u.reloadCallback),u.reloadCallback=null)))}}abortTile(u){u.request&&(u.request.cancel(),delete u.request),u.actor&&u.actor.send("abortTile",{uid:u.uid,type:this.type,source:this.id,scope:this.scope})}unloadTile(u,f){u.actor&&u.actor.send("removeTile",{uid:u.uid,type:this.type,source:this.id,scope:this.scope}),u.destroy()}hasTransition(){return!1}afterUpdate(){this._tileWorkers={}}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}}class vo extends a.E{constructor(u,f,v,S){super(),this.id=u,this.dispatcher=v,this.setEventedParent(S),this.type="raster",this.minzoom=0,this.maxzoom=22,this.roundZoom=!0,this.scheme="xyz",this.tileSize=512,this._loaded=!1,this._options=Object.assign({type:"raster"},f),Object.assign(this,a.aH(f,["url","scheme","tileSize"]))}load(u){this._loaded=!1,this.fire(new a.z("dataloading",{dataType:"source"}));const f=this.map.getWorldview();this._tileJSONRequest=$o(this._options,this.map._requestManager,null,f,(v,S)=>{this._tileJSONRequest=null,this._loaded=!0,v?this.fire(new a.y(v)):S&&(Object.assign(this,S),S.raster_layers&&(this.rasterLayers=S.raster_layers,this.rasterLayerIds=this.rasterLayers.map(T=>T.id)),this.tileBounds=rc.fromTileJSON(S),Ye(S.tiles),this.fire(new a.z("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new a.z("data",{dataType:"source",sourceDataType:"content"}))),u&&u(v)})}loaded(){return this._loaded}onAdd(u){this.map=u,this.load()}reload(){this.cancelTileJSONRequest();const u=a.B(this.id,this.scope);this.load(()=>this.map.style.clearSource(u))}setTiles(u){return this._options.tiles=u,this.reload(),this}setUrl(u){return this.url=u,this._options.url=u,this.reload(),this}onRemove(u){this.cancelTileJSONRequest()}serialize(){return Object.assign({},this._options)}hasTile(u){return!this.tileBounds||this.tileBounds.contains(u.canonical)}loadTile(u,f){const v=a.o.devicePixelRatio>=2,S=this.map._requestManager.normalizeTileURL(u.tileID.canonical.url(this.tiles,this.scheme),v,this.tileSize);u.request=a.n(this.map._requestManager.transformRequest(S,a.R.Tile),(T,E,L)=>{if(delete u.request,u.aborted)return u.state="unloaded",f(null);if(T)return u.state="errored",f(T);if(!E)return f(null);const B=a.aM(L);this.map._refreshExpiredTiles&&u.setExpiryData(B),u.setTexture(E,this.map.painter),u.state="loaded",a.aO(this.dispatcher),f(null)})}abortTile(u,f){u.request&&(u.request.cancel(),delete u.request),f&&f()}unloadTile(u,f){u.texture&&u.texture instanceof a.T?(u.destroy(!1),u.texture&&u.texture instanceof a.T&&this.map.painter.saveTileTexture(u.texture)):u.destroy(),f&&f()}hasTransition(){return!1}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}}function Bc([x,u],f,v,{scaled:S=!0}={}){const{tileSize:T,buffer:E}=v,{x:L,y:B,z:q}=f;if(!isFinite(L)||!isFinite(B)||!isFinite(q))throw new Error("Invalid MRT header");const G=2**q,ee=G*a.aF(x),J=G*a.aJ(u);return function([re,oe],se,{scaled:me=!0}={}){if(!se)throw new Error("bandView is undefined");const{data:fe,tileSize:Ne,buffer:Ae,offset:Te,scale:Ze,dimension:$e}=se;if(re<-Ae||re>Ne+Ae||oe<-Ae||oe>Ne+Ae)throw new Error(`Point (${re}, ${oe}) out of bounds for tileSize=${Ne}, buffer=${Ae}`);const He=(oe+Ae)*(Ne+2*Ae)+(re+Ae);if(new Uint32Array(fe.buffer)[He]===4294967295)return null;let ze=[];ze=me?[]:new se.data.constructor($e);for(let De=0;De<$e;De++)ze[De]=Math.round(1e12*(fe[$e*He+De]*Ze+Te))/1e12;return ze}([Math.min(Math.max(-E,Math.floor((ee-L)*T)),T-1+E),Math.min(Math.max(-E,Math.floor((J-B)*T)),T-1+E)],v,{scaled:S})}class xl extends vo{constructor(u,f,v,S){super(u,f,v,S),this.type="raster-array",this.maxzoom=22,this.partial=!0,this._loadTilePending={},this._loadTileLoaded={},this._options=Object.assign({type:"raster-array"},f)}triggerRepaint(u){const f=this.map.painter._terrain,v=this.map.style.getSourceCache(this.id);f&&f.enabled&&v&&f._clearRenderCacheForTile(v.id,u.tileID),this.map.triggerRepaint()}loadTile(u,f){const v=this.map._requestManager.normalizeTileURL(u.tileID.canonical.url(this.tiles,this.scheme),!1,this.tileSize),S=this.map._requestManager.transformRequest(v,a.R.Tile),T={request:S,uid:u.uid,tileID:u.tileID,type:this.type,source:this.id,scope:this.scope,partial:this.partial};u.source=this.id,u.scope=this.scope,u.requestParams=S,u.actor||(u.actor=this.dispatcher.getActor());const E=(L,B,q)=>{if(delete u.request,u.aborted)return u.state="unloaded",f(null);if(L)return L.name==="AbortError"?void 0:(u.state="errored",f(L));if(this.map._refreshExpiredTiles&&B){const G=a.aM(q);u.setExpiryData(G)}if(this.partial&&u.state!=="expired")u.state="empty";else if(!this.partial){if(!B)return f(null);u.state="loaded",u._isHeaderLoaded=!0,u._mrt=B}f(null)};u.request=this.partial?u.fetchHeader(void 0,E.bind(this)):u.actor.send("loadTile",T,E.bind(this),void 0,!0)}abortTile(u){u.request&&(u.request.cancel(),delete u.request),u.actor&&u.actor.send("abortTile",{uid:u.uid,type:this.type,source:this.id,scope:this.scope})}unloadTile(u,f){const v=u.texturePerLayer;if(u.flushAllQueues(),v.size){u.destroy(!1);for(const S of v.values())this.map.painter.saveTileTexture(S)}else u.destroy()}prepareTile(u,f,v,S){u._isHeaderLoaded&&(u.state!=="empty"&&(u.state="reloading"),u.fetchBandForRender(f,v,S,(T,E)=>{if(T)return u.state="errored",this.fire(new a.y(T)),void this.triggerRepaint(u);E&&(u._isHeaderLoaded=!0,u.setTexturePerLayer(v,E,this.map.painter),u.state="loaded",this.triggerRepaint(u))}))}getInitialBand(u){if(!this.rasterLayers)return 0;const f=this.rasterLayers.find(({id:T})=>T===u),v=f&&f.fields,S=v&&v.bands&&v.bands;return S?S[0]:0}getTextureDescriptor(u,f,v){if(!u)return;const S=f.sourceLayer||this.rasterLayerIds&&this.rasterLayerIds[0];if(!S)return;let T=null;f instanceof a.aR?T=f.paint.get("raster-array-band"):f instanceof a.aS&&(T=f.paint.get("raster-particle-array-band"));const E=T||this.getInitialBand(S);if(E==null)return;if(!u.textureDescriptorPerLayer.get(f.id))return void this.prepareTile(u,S,f.id,E);if(u.updateNeeded(f.id,E)&&!v)return;const L=u.textureDescriptorPerLayer.get(f.id);return Object.assign({},L,{texture:u.texturePerLayer.get(f.id)})}getImages(u,f){const v=new Map;for(const S of u)for(const T of f){const[E,L]=T.split("/"),B=S.getLayer(E);if(!B||!B.hasBand(L)||!B.hasDataForBand(L))continue;const{bytes:q,tileSize:G,buffer:ee}=B.getBandView(L),J=G+2*ee,re={data:new a.q({width:J,height:J},q),pixelRatio:2,sdf:!1,usvg:!1,version:0};v.set(T,re)}return v}queryRasterArrayValueByBandId(u,f,v){const S=f._mrt;return new Promise(T=>{const E={},L=new Set;for(const[B,q]of Object.entries(S.layers)){if(v.layerName&&B!==v.layerName)continue;const G={};E[B]=G;for(const{bands:ee}of q.dataIndex)for(const J of ee)v.bands&&!v.bands.includes(J)||(L.add(a.B(B,J)),f.fetchBand(B,null,J,re=>{a.o.frame(()=>{G[J]=re?null:Bc([u.lng,u.lat],S,q.getBandView(J)),L.delete(a.B(B,J)),L.size===0&&T(E)})},!1))}L.size===0&&T(E)})}_loadTileForQuery(u,f){if(this._loadTileLoaded[u.uid])return void f(null,u._mrt);if(this._loadTilePending[u.uid])return void this._loadTilePending[u.uid].push(f);this._loadTilePending[u.uid]=[f];const v=this.map._requestManager.normalizeTileURL(u.tileID.canonical.url(this.tiles,this.scheme),!1,this.tileSize),S=this.map._requestManager.transformRequest(v,a.R.Tile);u.actor.send("loadTile",{request:S,uid:u.uid,tileID:u.tileID,type:this.type,source:this.id,scope:this.scope,partial:!1},(T,E,L)=>{if(T)return this._loadTilePending[u.uid].forEach(B=>B(T,null)),void delete this._loadTilePending[u.uid];if(!E)return this._loadTilePending[u.uid].forEach(B=>B(null,null)),void delete this._loadTilePending[u.uid];if(this.map._refreshExpiredTiles&&E){const B=a.aM(L);u.setExpiryData(B)}u._mrt=E,u._isHeaderLoaded=!0,u.state="loaded",this._loadTilePending[u.uid].forEach(B=>B(null,E)),this._loadTileLoaded[u.uid]=!0,delete this._loadTilePending[u.uid]},void 0,!0)}queryRasterArrayValueByAllBands(u,f,v){return new Promise((S,T)=>{this._loadTileForQuery(f,(E,L)=>{E?T(E):S(L?this.queryRasterArrayValueByBandId(u,f,v):null)})})}queryRasterArrayValue(u,f){const v=a.aT.convert(u),S=this.findLoadedParent(v);return S&&S._mrt?f.bands||!this.partial?this.queryRasterArrayValueByBandId(v,S,f):this.queryRasterArrayValueByAllBands(v,S,f):Promise.resolve(null)}findLoadedParent(u){const f=a.ae.fromLngLat(u,this.map.transform.tileSize),v=this.maxzoom+1,S=1<0&&(L[new a.aQ(x.overscaledZ,S,u.z,v,u.y-1).key]={backfilled:!1},L[new a.aQ(x.overscaledZ,x.wrap,u.z,u.x,u.y-1).key]={backfilled:!1},L[new a.aQ(x.overscaledZ,E,u.z,T,u.y-1).key]={backfilled:!1}),u.y+1{if(this._loaded=!0,this._pendingLoad=null,v)this.fire(new a.y(v));else{const T={dataType:"source",sourceDataType:this._metadataFired?"content":"metadata"};this._collectResourceTiming&&S&&S.resourceTiming&&S.resourceTiming[this.id]&&(T.resourceTiming=S.resourceTiming[this.id]),x&&(this._partialReload=!0),this.fire(new a.z("data",T)),this._partialReload=!1,this._metadataFired=!0}this._coalesce&&(this._updateWorkerData(x),this._coalesce=!1)})}loaded(){return this._loaded}reload(){const x=a.B(this.id,this.scope);this.map.style.clearSource(x),this._updateWorkerData()}loadTile(x,u){const f=x.actor?"reloadTile":"loadTile";x.actor=this.actor;const v=this.map.style?this.map.style.getLut(this.scope):null,S=v?{image:v.image.clone()}:null,T=this._partialReload,E={type:this.type,uid:x.uid,tileID:x.tileID,tileZoom:x.tileZoom,zoom:x.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,lut:S,scope:this.scope,pixelRatio:a.o.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,brightness:this.map.style&&this.map.style.getBrightness()||0,extraShadowCaster:x.isExtraShadowCaster,scaleFactor:this.map.getScaleFactor(),partial:T,worldview:this.map.getWorldview(),indoor:this.map.indoor?this.map.indoor.getIndoorTileOptions(this.id,this.scope):null};x.request=this.actor.send(f,E,(L,B)=>T&&!B?(x.state="loaded",u(null)):(delete x.request,x.destroy(!1),x.aborted?u(null):L?u(L):(x.loadVectorData(B,this.map.painter,f==="reloadTile"),u(null))),void 0,f==="loadTile")}abortTile(x){x.request&&(x.request.cancel(),delete x.request),x.aborted=!0}unloadTile(x,u){this.actor.send("removeTile",{uid:x.uid,type:this.type,source:this.id,scope:this.scope}),x.destroy()}onRemove(x){this._pendingLoad&&this._pendingLoad.cancel()}serialize(){return Object.assign({},this._options,{type:this.type,data:this._data})}hasTransition(){return!1}},video:class extends a.aU{constructor(x,u,f,v){super(x,u,f,v),this.roundZoom=!0,this.type="video",this.options=u}load(){this._loaded=!1;const x=this.options;this.urls=[];for(const u of x.urls)this.urls.push(this.map._requestManager.transformRequest(u,a.R.Source).url);a.aV(this.urls,(u,f)=>{this._loaded=!0,u?this.fire(new a.y(u)):f&&(this.video=f,this.video.loop=!0,this.video.setAttribute("playsinline",""),this.video.addEventListener("playing",()=>{this.map.triggerRepaint()}),this.map&&this.video.play(),this._finishLoading())})}pause(){this.video&&this.video.pause()}play(){this.video&&this.video.play()}seek(x){if(this.video){const u=this.video.seekable;xu.end(0)?this.fire(new a.y(new a.V(`sources.${this.id}`,null,`Playback for this video can be set only between the ${u.start(0)} and ${u.end(0)}-second mark.`))):this.video.currentTime=x}}getVideo(){return this.video}onAdd(x){this.map||(this.map=x,this.load(),this.video&&(this.video.play(),this.setCoordinates(this.coordinates)))}prepare(){if(Object.keys(this.tiles).length===0||this.video.readyState<2)return;const x=this.map.painter.context,u=x.gl;this.texture?this.video.paused||(this.texture.bind(u.LINEAR,u.CLAMP_TO_EDGE),u.texSubImage2D(u.TEXTURE_2D,0,0,0,u.RGBA,u.UNSIGNED_BYTE,this.video)):(this.texture=new a.T(x,this.video,u.RGBA8),this.texture.bind(u.LINEAR,u.CLAMP_TO_EDGE),this.width=this.video.videoWidth,this.height=this.video.videoHeight),this._prepareData(x)}serialize(){return{type:"video",urls:this.urls,coordinates:this.coordinates}}hasTransition(){return this.video&&!this.video.paused}},image:a.aU,model:a.aX,"batched-model":class extends a.E{constructor(x,u,f,v){super(),this.type="batched-model",this.id=x,this.tileSize=512,this._options=u,this.tiles=this._options.tiles,this.maxzoom=u.maxzoom||19,this.minzoom=u.minzoom||0,this.roundZoom=!0,this.usedInConflation=!0,this.dispatcher=f,this.reparseOverscaled=!1,this.scheme="xyz",this._loaded=!1,this.setEventedParent(v)}onAdd(x){this.map=x,this.load()}reload(){this.cancelTileJSONRequest();const x=a.B(this.id,this.scope);this.load(()=>this.map.style.clearSource(x))}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}load(x){this._loaded=!1,this.fire(new a.z("dataloading",{dataType:"source"}));const u=Array.isArray(this.map._language)?this.map._language.join():this.map._language,f=this.map.getWorldview();this._tileJSONRequest=$o(this._options,this.map._requestManager,u,f,(v,S)=>{this._tileJSONRequest=null,this._loaded=!0,v?(u&&console.warn(`Ensure that your requested language string is a valid BCP-47 code or list of codes. Found: ${u}`),f&&f.length!==2&&console.warn(`Requested worldview strings must be a valid ISO alpha-2 code. Found: ${f}`),this.fire(new a.y(v))):S&&(Object.assign(this,S),S.bounds&&(this.tileBounds=new rc(S.bounds,this.minzoom,this.maxzoom)),Ye(S.tiles,this.map._requestManager._customAccessToken),this.fire(new a.z("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new a.z("data",{dataType:"source",sourceDataType:"content"}))),x&&x(v)})}hasTransition(){return!1}hasTile(x){return!this.tileBounds||this.tileBounds.contains(x.canonical)}loaded(){return this._loaded}loadTile(x,u){const f=this.map._requestManager.normalizeTileURL(x.tileID.canonical.url(this.tiles,this.scheme)),v={request:this.map._requestManager.transformRequest(f,a.R.Tile),data:void 0,uid:x.uid,tileID:x.tileID,tileZoom:x.tileZoom,zoom:x.tileID.overscaledZ,tileSize:this.tileSize*x.tileID.overscaleFactor(),type:this.type,source:this.id,scope:this.scope,showCollisionBoxes:this.map.showCollisionBoxes,isSymbolTile:x.isSymbolTile,brightness:this.map.style&&this.map.style.getBrightness()||0,pixelRatio:a.o.devicePixelRatio,promoteId:this.promoteId};if(x.actor&&x.state!=="expired")if(x.state==="loading")x.reloadCallback=u;else{if(x.buckets){const T=Object.values(x.buckets);for(const E of T)E.dirty=!0;return void(x.state="loaded")}x.request=x.actor.send("reloadTile",v,S.bind(this))}else x.actor=this.dispatcher.getActor(),x.request=x.actor.send("loadTile",v,S.bind(this),void 0,!0);function S(T,E){return x.aborted?u(null):T&&T.status!==404?u(T):(this.map._refreshExpiredTiles&&E&&x.setExpiryData(E),x.loadModelData(E,this.map.painter),x.state="loaded",void u(null))}}serialize(){return Object.assign({},this._options)}},canvas:class extends a.aU{constructor(x,u,f,v){super(x,u,f,v),u.coordinates?Array.isArray(u.coordinates)&&u.coordinates.length===4&&!u.coordinates.some(S=>!Array.isArray(S)||S.length!==2||S.some(T=>typeof T!="number"))||this.fire(new a.y(new a.V(`sources.${x}`,null,'"coordinates" property must be an array of 4 longitude/latitude array pairs'))):this.fire(new a.y(new a.V(`sources.${x}`,null,'missing required property "coordinates"'))),u.animate&&typeof u.animate!="boolean"&&this.fire(new a.y(new a.V(`sources.${x}`,null,'optional "animate" property must be a boolean value'))),u.canvas?typeof u.canvas=="string"||u.canvas instanceof HTMLCanvasElement||this.fire(new a.y(new a.V(`sources.${x}`,null,'"canvas" must be either a string representing the ID of the canvas element from which to read, or an HTMLCanvasElement instance'))):this.fire(new a.y(new a.V(`sources.${x}`,null,'missing required property "canvas"'))),this.options=u,this.animate=u.animate===void 0||u.animate}load(){this._loaded=!0,this.canvas||(this.canvas=this.options.canvas instanceof HTMLCanvasElement?this.options.canvas:document.getElementById(this.options.canvas)),this.width=this.canvas.width,this.height=this.canvas.height,this._hasInvalidDimensions()?this.fire(new a.y(new Error("Canvas dimensions cannot be less than or equal to zero."))):(this.play=function(){this._playing=!0,this.map.triggerRepaint()},this.pause=function(){this._playing&&(this.prepare(),this._playing=!1)},this._finishLoading())}getCanvas(){return this.canvas}onAdd(x){this.map=x,this.load(),this.canvas&&this.animate&&this.play()}onRemove(x){this.pause()}prepare(){let x=!1;if(this.canvas.width!==this.width&&(this.width=this.canvas.width,x=!0),this.canvas.height!==this.height&&(this.height=this.canvas.height,x=!0),this._hasInvalidDimensions()||Object.keys(this.tiles).length===0)return;const u=this.map.painter.context;this.texture?!x&&!this._playing||this.texture instanceof a.aW||this.texture.update(this.canvas,{premultiply:!0}):this.texture=new a.T(u,this.canvas,u.gl.RGBA8,{premultiply:!0}),this._prepareData(u)}serialize(){return{type:"canvas",coordinates:this.coordinates}}hasTransition(){return this._playing}_hasInvalidDimensions(){for(const x of[this.canvas.width,this.canvas.height])if(isNaN(x)||x<=0)return!0;return!1}},custom:class extends a.E{constructor(x,u,f,v){super(),this.id=x,this.type="custom",this._dataType="raster",this._dispatcher=f,this._implementation=u,this.setEventedParent(v),this.scheme="xyz",this.minzoom=0,this.maxzoom=22,this.tileSize=512,this._loaded=!1,this.roundZoom=!0,this._implementation||this.fire(new a.y(new Error(`Missing implementation for ${this.id} custom source`))),this._implementation.loadTile||this.fire(new a.y(new Error(`Missing loadTile implementation for ${this.id} custom source`))),this._implementation.bounds&&(this.tileBounds=new rc(this._implementation.bounds,this.minzoom,this.maxzoom)),u.update=this._update.bind(this),u.clearTiles=this._clearTiles.bind(this),u.coveringTiles=this._coveringTiles.bind(this),Object.assign(this,a.aH(u,["dataType","scheme","minzoom","maxzoom","tileSize","attribution","minTileCacheSize","maxTileCacheSize"]))}serialize(){return a.aH(this,["type","scheme","minzoom","maxzoom","tileSize","attribution"])}load(){this._loaded=!0,this.fire(new a.z("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new a.z("data",{dataType:"source",sourceDataType:"content"}))}loaded(){return this._loaded}onAdd(x){this.map=x,this._loaded=!1,this.fire(new a.z("dataloading",{dataType:"source"})),this._implementation.onAdd&&this._implementation.onAdd(x),this.load()}onRemove(x){this._implementation.onRemove&&this._implementation.onRemove(x)}hasTile(x){if(this._implementation.hasTile){const{x:u,y:f,z:v}=x.canonical;return this._implementation.hasTile({x:u,y:f,z:v})}return!this.tileBounds||this.tileBounds.contains(x.canonical)}loadTile(x,u){const{x:f,y:v,z:S}=x.tileID.canonical,T=new AbortController;x.request=Promise.resolve(this._implementation.loadTile({x:f,y:v,z:S},{signal:T.signal})).then((function(E){return delete x.request,x.aborted?(x.state="unloaded",u(null)):E===void 0?(x.state="errored",u(null)):E===null?(this.loadTileData(x,{width:this.tileSize,height:this.tileSize,data:null}),x.state="loaded",u(null)):function(L){return L instanceof ImageData||L instanceof HTMLCanvasElement||L instanceof ImageBitmap||L instanceof HTMLImageElement}(E)?(this.loadTileData(x,E),x.state="loaded",void u(null)):(x.state="errored",u(new Error(`Can't infer data type for ${this.id}, only raster data supported at the moment`)))}).bind(this)).catch(E=>{E.name!=="AbortError"&&(x.state="errored",u(E))}),x.request.cancel=()=>T.abort()}loadTileData(x,u){x.setTexture(u,this.map.painter)}unloadTile(x,u){if(x.texture&&x.texture instanceof a.T?(x.destroy(!1),x.texture&&x.texture instanceof a.T&&this.map.painter.saveTileTexture(x.texture)):x.destroy(),this._implementation.unloadTile){const{x:f,y:v,z:S}=x.tileID.canonical;this._implementation.unloadTile({x:f,y:v,z:S})}u&&u()}abortTile(x,u){x.request&&x.request.cancel&&(x.request.cancel(),delete x.request),u&&u()}hasTransition(){return!1}_coveringTiles(){return this.map.transform.coveringTiles({tileSize:this.tileSize,minzoom:this.minzoom,maxzoom:this.maxzoom,roundZoom:this.roundZoom}).map(x=>({x:x.canonical.x,y:x.canonical.y,z:x.canonical.z}))}_clearTiles(){const x=a.B(this.id,this.scope);this.map.style.clearSource(x)}_update(){this.fire(new a.z("data",{dataType:"source",sourceDataType:"content"}))}}},lo=function(x,u,f,v){const S=new Td[u.type](x,u,f,v);if(S.id!==x)throw new Error(`Expected Source id to be ${x} instead of ${S.id}`);return a.aY(["load","abort","unload","serialize","prepare"],S),S};function Bp(x,u,f=""){return`${f}:${u.id||""}:${u.layer.id}:${function(v){if("layerId"in v)return`layer:${v.layerId}`;{const{featuresetId:S,importId:T}=v;return`featureset:${S}${T?`:import:${T}`:""}`}}(x.target)}`}function hg(x,u,f,v=""){if(x.uniqueFeatureID){const S=Bp(x,u,v);if(f.has(S))return!0;f.add(S)}return!1}function p0(x,u,f,v,S=!1){const T=u.sourceCache.transform,E=u.sourceCache.tilesIn(x,u.has3DLayers,S);E.sort(Ix);const L=[];for(const B of E){const q=B.tile.queryRenderedFeatures(u,B,f,v,T,S);Object.keys(q).length&&L.push({wrappedTileID:B.tile.tileID.wrapped().key,queryResults:q})}for(const B in u.layers){const q=u.layers[B];if(q.styleLayer){const G=q.styleLayer.queryRenderedFeatures(x,u.sourceCache,v);Object.keys(G).length&&L.push({wrappedTileID:0,queryResults:G})}}return L.length===0?{}:function(B){const q={},G={};for(const ee of B){const J=ee.queryResults,re=ee.wrappedTileID,oe=G[re]=G[re]||{};for(const se in J){const me=J[se],fe=oe[se]=oe[se]||{},Ne=q[se]=q[se]||[];for(const Ae of me)fe[Ae.featureIndex]||(fe[Ae.featureIndex]=!0,Ne.push(Ae))}}return q}(L)}function m0(x,u,f,v,S,T){const E={},L=v.queryRenderedSymbols(x),B=[];for(const q of Object.keys(L).map(Number))B.push(S[q]);B.sort(Ix);for(const q of B){const G=q.featureIndex.lookupSymbolFeatures(L[q.bucketInstanceId],q.bucketIndex,q.sourceLayerIndex,u,f,T);for(const ee in G){const J=E[ee]=E[ee]||[],re=G[ee];re.sort((oe,se)=>{const me=q.featureSortOrder;if(me){const fe=me.indexOf(oe.featureIndex);return me.indexOf(se.featureIndex)-fe}return se.featureIndex-oe.featureIndex});for(const oe of re)J.push(oe)}}return E}function g0(x,u){const f=x.getRenderableIds().map(T=>x.getTileByID(T)),v=[],S={};for(let T=0;Tu.getLayer(T)).filter(Boolean);if(S.length!==0){v.layers=S,v.stateDependentLayerIds&&(v.stateDependentLayers=v.stateDependentLayerIds.map(T=>S.filter(E=>E.id===T)[0]));for(const T of S)f[T.fqid]=v}}return f}const nc=32,Gu=33,Ku=new Uint16Array(8184);for(let x=0;x<2046;x++){let u=x+2,f=0,v=0,S=0,T=0,E=0,L=0;for(1&u?S=T=E=nc:f=v=L=nc;(u>>=1)>1;){const q=f+S>>1,G=v+T>>1;1&u?(S=f,T=v,f=E,v=L):(f=S,v=T,S=E,T=L),E=q,L=G}const B=4*x;Ku[B+0]=f,Ku[B+1]=v,Ku[B+2]=S,Ku[B+3]=T}const yu=new Uint16Array(2178),Ad=new Uint8Array(1089),If=new Uint16Array(1089);function $p(x){return x===0?-.03125:x===32?.03125:0}const y0={type:2,extent:a.al,loadGeometry:()=>[[new a.P(0,0),new a.P(a.al+1,0),new a.P(a.al+1,a.al+1),new a.P(0,a.al+1),new a.P(0,0)]]};class Up{constructor(u,f,v,S,T,E){this.tileID=u,this.uid=a.b2(),this.uses=0,this.tileSize=f,this.tileZoom=v,this.buckets={},this.expirationTime=null,this.queryPadding=0,this.hasSymbolBuckets=!1,this.hasRTLText=!1,this.dependencies={},this.isRaster=T,S&&S.style&&(this._lastUpdatedBrightness=S.style.getBrightness()),this.expiredRequestCount=0,this.state="loading",S&&S.transform&&(this.projection=S.transform.projection),this.worldview=E,this._hasAppearances=null}registerFadeDuration(u){const f=u+this.timeAdded;fv)S=!1;else if(f)if(this.expirationTimev.appearances&&v.appearances.length>0))return!0;return!1}updateBuckets(u,f){if(!this.latestFeatureIndex||!u.style)return;const v=u.style.listImages(),S=u.style.getBrightness();for(const T in this.buckets){if(!u.style.hasLayer(T))continue;const E=this.buckets[T],L=E.layers[0],B=L.sourceLayer||"_geojsonTileLayer",q=u.style.getLayerSourceCache(L);let G={};q&&(G=q._state.getState(B,void 0));const ee=this.imageAtlas?Object.fromEntries(this.imageAtlas.patternPositions):{},J=Object.keys(G).length>0&&!f;E.hasAppearances=E.layers.some(se=>se.appearances&&se.appearances.length>0);const re=J?E.stateDependentLayers:E.layers;if(J&&E.stateDependentLayers.length!==0||f){const se=this.latestFeatureIndex.loadVTLayers();E.update(G,se[B],v,ee,re,f,S)}if(J&&E.stateDependentLayers.length!==0||f||E.hasAppearances){const se={zoom:u.transform.zoom,pitch:u.transform.pitch,brightness:u.style.getBrightness()||0,worldview:u.worldview};E.updateAppearances(this.tileID.canonical,G,v,se)}(E instanceof a.ba||E instanceof a.bb)&&u._terrain&&u._terrain.enabled&&q&&E.uploadPending()&&u._terrain._clearRenderCacheForTile(q.id,this.tileID);const oe=u&&u.style&&u.style.getOwnLayer(T);oe&&(this.queryPadding=Math.max(this.queryPadding,oe.queryRadius(E)))}}holdingForFade(){return this.symbolFadeHoldUntil!==void 0}symbolFadeFinished(){return!this.symbolFadeHoldUntil||this.symbolFadeHoldUntil=0;me--){const fe=4*me,Ne=Ku[fe+0],Ae=Ku[fe+1],Te=Ku[fe+2],Ze=Ku[fe+3],$e=Ne+Te>>1,He=Ae+Ze>>1,ze=$e+He-Ae,De=He+Ne-$e,Qe=Ae*Gu+Ne,ht=Ze*Gu+Te,ot=He*Gu+$e,Tt=Math.hypot((yu[2*Qe+0]+yu[2*ht+0])/2-yu[2*ot+0],(yu[2*Qe+1]+yu[2*ht+1])/2-yu[2*ot+1])>=16;Ad[ot]=Ad[ot]||(Tt?1:0),me<1022&&(Ad[ot]=Ad[ot]||Ad[(Ae+De>>1)*Gu+(Ne+ze>>1)]||Ad[(Ze+De>>1)*Gu+(Te+ze>>1)])}const ee=new a.b1,J=new a.b0;let re=0;function oe(me,fe){const Ne=fe*Gu+me;return If[Ne]===0&&(ee.emplaceBack(yu[2*Ne+0],yu[2*Ne+1],me*a.al/nc,fe*a.al/nc),If[Ne]=++re),If[Ne]-1}function se(me,fe,Ne,Ae,Te,Ze){const $e=me+Ne>>1,He=fe+Ae>>1;if(Math.abs(me-Te)+Math.abs(fe-Ze)>1&&Ad[He*Gu+$e])se(Te,Ze,me,fe,$e,He),se(Ne,Ae,Te,Ze,$e,He);else{const ze=oe(me,fe),De=oe(Ne,Ae),Qe=oe(Te,Ze);J.emplaceBack(ze,De,Qe)}}return se(0,0,nc,nc,nc,0),se(nc,nc,0,0,0,nc),{vertices:ee,indices:J}}(this.tileID.canonical,f);S=E.vertices,T=E.indices}else{S=new a.b1,T=new a.b0;for(const{x:L,y:B}of v)S.emplaceBack(L,B,0,0);const E=a.bh(S.int16.subarray(0,4*S.length),void 0,4);for(let L=0;L0&&(B=a.bl(new Float64Array(16),f.globeMatrix)),this._makeGlobeTileDebugBorderBuffer(u,S,f,E,B,L),this._makeGlobeTileDebugTextBuffer(u,S,f,E,B,L)}_globePoint(u,f,v,S,T,E,L){let B=a.bm(u,f,v);if(E){const q=1<.5?re=-1:J<-.5&&(re=1);let oe=(u/a.al+v.x)/q+re,se=(f/a.al+v.y)/q;oe=(oe-G)*S._pixelsPerMercatorPixel+G,se=(se-ee)*S._pixelsPerMercatorPixel+ee;const me=[oe*S.worldSize,se*S.worldSize,0];a.af(me,me,E),B=a.bn(B,me,L)}return a.af(B,B,T)}_makeGlobeTileDebugBorderBuffer(u,f,v,S,T,E){const L=new a.bd,B=new a.be,q=new a.bo,G=(J,re,oe,se,me)=>{const fe=(oe-J)/(me-1),Ne=(se-re)/(me-1),Ae=L.length;for(let Te=0;Teee*re+oe;for(let re=0;re{if(T)f(T);else try{const B=v.getHeaderLength(E);if(B>u)return void(this.request=this.fetchHeader(B,f));v.parseHeader(E),this._isHeaderLoaded=!0;let q=0;for(const G of Object.values(v.layers))q=Math.max(q,G.dataIndex[G.dataIndex.length-1].lastByte);E.byteLength>=q&&(this.entireBuffer=E),f(null,this.entireBuffer||E,L)}catch(B){f(B)}}),this.request}fetchBandForRender(u,f,v,S){this.fetchBand(u,f,v,T=>{if(T)return void S(T);this.updateTextureDescriptor(u,f,v);const E=this.textureDescriptorPerLayer.get(f);S(null,E?E.img:null)})}fetchBand(u,f,v,S,T=!0){const E=this._mrt;if(!this._isHeaderLoaded||!E)return void S(new Error("Tile header is not ready"));const L=this.actor;if(!L)return void S(new Error("Can't fetch tile band without an actor"));let B;const q=a.B(String(v),a.B(this.tileID.key,u));let G=this._taskQueue.get(q);G?G.add(S):(G=new Set,G.add(S),this._taskQueue.set(q,G));const ee=(se,me)=>{B.complete(se,me),se?S(se):(G.forEach(fe=>fe(null,me)),this._taskQueue.delete(q))},J=(se,me)=>{if(se)return S(se);const fe=L.send("decodeRasterArray",{type:"raster-array",source:this.source,scope:this.scope,tileID:this.tileID,uid:this.uid,buffer:me,task:B},ee,void 0,!0);if(f!==null){const Ne=this._workQueuePerLayer.get(f)||[];Ne.push(()=>{fe&&fe.cancel(),B.cancel()}),this._workQueuePerLayer.has(f)||this._workQueuePerLayer.set(f,Ne)}};let re;try{re=E.getLayer(u)}catch(se){if(this.state==="reloading")return;throw se}if(!re)return void S(new Error(`Unknown sourceLayer "${u}"`));if(re.hasDataForBand(v))return G.forEach(se=>se(null,null)),void this._taskQueue.delete(q);const oe=re.getDataRange([v]);if(B=E.createDecodingTask(oe),!B||B.tasks.length)if(f!==null&&this.flushQueues(f),this.entireBuffer)J(null,this.entireBuffer.slice(oe.firstByte,oe.lastByte+1));else{const se=Object.assign({},this.requestParams,{headers:{Range:`bytes=${oe.firstByte}-${oe.lastByte}`}}),me=a.bu(se,J);if(f!==null){const fe=this._fetchQueuePerLayer.get(f)||[];fe.push(()=>{me.cancel(),B.cancel()}),this._fetchQueuePerLayer.has(f)||this._fetchQueuePerLayer.set(f,fe)}}}updateNeeded(u,f){return(!this.textureDescriptorPerLayer.get(u)||this.textureDescriptorPerLayer.get(u).band!==f||this.refreshedUponExpiration)&&this.state!=="errored"}updateTextureDescriptor(u,f,v){if(!this._mrt)return;const S=this._mrt.getLayer(u);if(!S||!S.hasBand(v)||!S.hasDataForBand(v))return;const{bytes:T,tileSize:E,buffer:L,offset:B,scale:q}=S.getBandView(v),G=E+2*L,ee=new a.q({width:G,height:G},T),J=this.texturePerLayer.get(f);J&&J instanceof a.T&&J.update(ee,{premultiply:!1}),this.textureDescriptorPerLayer.set(f,{layer:u,band:v,img:ee,buffer:L,offset:B,tileSize:E,format:S.pixelFormat,mix:[q,256*q,65536*q,16777216*q]})}destroy(u=!1){if(super.destroy(u),delete this._mrt,!u)for(const f of this.texturePerLayer.values())f&&f instanceof a.T&&f.destroy();this.texturePerLayer.clear(),this.textureDescriptorPerLayer.clear(),this.fbo&&(this.fbo.destroy(),delete this.fbo),delete this.request,delete this.requestParams,this._isHeaderLoaded=!1}}class XT{constructor(u,f){this.max=u,this.onRemove=f,this.reset()}reset(){for(const u in this.data)for(const f of this.data[u])f.timeout&&clearTimeout(f.timeout),this.onRemove(f.value);return this.data={},this.order=[],this}add(u,f,v){const S=u.wrapped().key;this.data[S]===void 0&&(this.data[S]=[]);const T={value:f,timeout:void 0};if(v!==void 0&&(T.timeout=setTimeout(()=>{this.remove(u,T)},v)),this.data[S].push(T),this.order.push(S),this.order.length>this.max){const E=this._getAndRemoveByKey(this.order[0]);E&&this.onRemove(E)}return this}has(u){return u.wrapped().key in this.data}getAndRemove(u){return this.has(u)?this._getAndRemoveByKey(u.wrapped().key):null}_getAndRemoveByKey(u){const f=this.data[u].shift();return f.timeout&&clearTimeout(f.timeout),this.data[u].length===0&&delete this.data[u],this.order.splice(this.order.indexOf(u),1),f.value}getByKey(u){const f=this.data[u];return f?f[0].value:null}get(u){return this.has(u)?this.data[u.wrapped().key][0].value:null}remove(u,f){if(!this.has(u))return this;const v=u.wrapped().key,S=f===void 0?0:this.data[v].indexOf(f),T=this.data[v][S];return this.data[v].splice(S,1),T.timeout&&clearTimeout(T.timeout),this.data[v].length===0&&delete this.data[v],this.onRemove(T.value),this.order.splice(this.order.indexOf(v),1),this}setMaxSize(u){for(this.max=u;this.order.length>this.max;){const f=this._getAndRemoveByKey(this.order[0]);f&&this.onRemove(f)}return this}filter(u){const f=[];for(const v in this.data)for(const S of this.data[v])u(S.value)||f.push(S);for(const v of f)this.remove(v.value.tileID,v)}}class Mx{constructor(){this.state={},this.stateChanges={},this.deletedStates={}}updateState(u,f,v){const S=String(f);if(this.stateChanges[u]=this.stateChanges[u]||{},this.stateChanges[u][S]=this.stateChanges[u][S]||{},Object.assign(this.stateChanges[u][S],v),this.deletedStates[u]===null){this.deletedStates[u]={};for(const T in this.state[u])T!==S&&(this.deletedStates[u][T]=null)}else if(this.deletedStates[u]&&this.deletedStates[u][S]===null){this.deletedStates[u][S]={};for(const T in this.state[u][S])v[T]||(this.deletedStates[u][S][T]=null)}else for(const T in v)this.deletedStates[u]&&this.deletedStates[u][S]&&this.deletedStates[u][S][T]===null&&delete this.deletedStates[u][S][T]}removeFeatureState(u,f,v){if(this.deletedStates[u]===null)return;const S=String(f);if(this.deletedStates[u]=this.deletedStates[u]||{},v&&f!==void 0)this.deletedStates[u][S]!==null&&(this.deletedStates[u][S]=this.deletedStates[u][S]||{},this.deletedStates[u][S][v]=null);else if(f!==void 0)if(this.stateChanges[u]&&this.stateChanges[u][S])for(v in this.deletedStates[u][S]={},this.stateChanges[u][S])this.deletedStates[u][S][v]=null;else this.deletedStates[u][S]=null;else this.deletedStates[u]=null}getState(u,f){const v=this.state[u]||{},S=this.stateChanges[u]||{},T=this.deletedStates[u];if(T===null)return{};if(f!==void 0){const L=String(f),B=Object.assign({},v[L],S[L]);if(T){const q=T[f];if(q===null)return{};for(const G in q)delete B[G]}return B}const E=Object.assign({},v,S);if(T)for(const L in T)delete E[L];return E}initializeTileState(u,f){u.refreshFeatureState(f)}coalesceChanges(u,f){const v={};for(const S in this.stateChanges){this.state[S]=this.state[S]||{};const T={};for(const E in this.stateChanges[S])this.state[S][E]||(this.state[S][E]={}),Object.assign(this.state[S][E],this.stateChanges[S][E]),T[E]=this.state[S][E];v[S]=T}for(const S in this.deletedStates){this.state[S]=this.state[S]||{};const T={};if(this.deletedStates[S]===null)for(const E in this.state[S])T[E]={},this.state[S][E]={};else for(const E in this.deletedStates[S]){if(this.deletedStates[S][E]===null)this.state[S][E]={};else if(this.state[S][E])for(const L of Object.keys(this.deletedStates[S][E]))delete this.state[S][E][L];T[E]=this.state[S][E]}v[S]=v[S]||{},Object.assign(v[S],T)}if(this.stateChanges={},this.deletedStates={},Object.keys(v).length!==0)for(const S in u)u[S].refreshFeatureState(f)}}class jc extends a.E{constructor(u,f,v){super(),this.id=u,this._onlySymbols=v,f.on("data",S=>{S.dataType==="source"&&S.sourceDataType==="metadata"&&(this._sourceLoaded=!0),this._sourceLoaded&&!this._paused&&S.dataType==="source"&&S.sourceDataType==="content"&&(this.reload(),this.transform&&this.update(this.transform))}),f.on("error",()=>{this._sourceErrored=!0}),this._source=f,this._tiles={},this._cache=new XT(0,this._unloadTile.bind(this)),this._timers={},this._cacheTimers={},this._minTileCacheSize=f.minTileCacheSize,this._maxTileCacheSize=f.maxTileCacheSize,this._loadedParentTiles={},this.castsShadows=!1,this.tileCoverLift=0,this._coveredTiles={},this._shadowCasterTiles={},this._state=new Mx,this._isRaster=this._source.type==="raster"||this._source.type==="raster-dem"||this._source.type==="raster-array"||this._source.type==="custom"&&this._source._dataType==="raster"}onAdd(u){this.map=u,this._minTileCacheSize=this._minTileCacheSize===void 0&&u?u._minTileCacheSize:this._minTileCacheSize,this._maxTileCacheSize=this._maxTileCacheSize===void 0&&u?u._maxTileCacheSize:this._maxTileCacheSize}loaded(){if(this._sourceErrored)return!0;if(!this._sourceLoaded||!this._source.loaded())return!1;for(const u in this._tiles)if(!this._tiles[u].loaded())return!1;return!0}getSource(){return this._source}pause(){this._paused=!0}resume(){if(!this._paused)return;const u=this._shouldReloadOnResume;this._paused=!1,this._shouldReloadOnResume=!1,u&&this.reload(),this.transform&&this.update(this.transform)}_loadTile(u,f){return u.isSymbolTile=this._onlySymbols,u.isExtraShadowCaster=this._shadowCasterTiles[u.tileID.key],this._source.loadTile(u,f)}_unloadTile(u){if(this._source.unloadTile)return this._source.unloadTile(u)}_abortTile(u){if(this._source.abortTile)return this._source.abortTile(u)}serialize(){return this._source.serialize()}prepare(u){this._source.prepare&&this._source.prepare(),this._state.coalesceChanges(this._tiles,this.map?this.map.painter:null);for(const f in this._tiles){const v=this._tiles[f];v.upload(u,this.map?this.map.painter:void 0),v.prepare(this.map.style.imageManager,this.map?this.map.painter:null,this._source.scope)}}getIds(){return Object.values(this._tiles).map(u=>u.tileID).sort(v0).map(u=>u.key)}getRenderableIds(u,f){const v=[];for(const S in this._tiles)this._isIdRenderable(+S,u,f)&&v.push(this._tiles[S]);return u?v.sort((S,T)=>{const E=S.tileID,L=T.tileID,B=new a.P(E.canonical.x,E.canonical.y)._rotate(this.transform.angle),q=new a.P(L.canonical.x,L.canonical.y)._rotate(this.transform.angle);return E.overscaledZ-L.overscaledZ||q.y-B.y||q.x-B.x}).map(S=>S.tileID.key):v.map(S=>S.tileID).sort(v0).map(S=>S.key)}hasRenderableParent(u){const f=this.findLoadedParent(u,0);return!!f&&this._isIdRenderable(f.tileID.key)}_isIdRenderable(u,f,v){return this._tiles[u]&&this._tiles[u].hasData()&&!this._coveredTiles[u]&&(f||!this._tiles[u].holdingForFade())&&(v||!this._shadowCasterTiles[u])}reload(){if(this._paused)this._shouldReloadOnResume=!0;else{this._cache.reset();for(const u in this._tiles)this._tiles[u].state!=="errored"&&this._reloadTile(+u,"reloading")}}_reloadTile(u,f){const v=this._tiles[u];v&&(v.state!=="loading"&&(v.state=f),this._loadTile(v,this._tileLoaded.bind(this,v,u,f)))}_tileLoaded(u,f,v,S,T){if(S){if(u.state="errored",S.status!==404)this._source.fire(new a.y(S,{tile:u}));else{if(this._source.fire(new a.z("data",{dataType:"source",sourceDataType:"error",sourceId:this._source.id,tile:u})),!(u.tileID.key in this._loadedParentTiles))return;if(this._source.type==="raster-dem"&&this.usedForTerrain&&this.map.painter.terrain){const L=this.map.painter.terrain;this.update(this.transform,L.getScaledDemTileSize(),!0),L.resetTileLookupCache(this.id)}else this.update(this.transform)}return}u.timeAdded=a.o.now(),v==="expired"&&(u.refreshedUponExpiration=!0),this._setTileReloadTimer(f,u),this._source.type==="raster-dem"&&u.dem&&this._backfillDEM(u),this._state.initializeTileState(u,this.map?this.map.painter:null);let E=new Map;T&&T.responseHeaders&&(E=T.responseHeaders),this._source.fire(new a.z("data",{dataType:"source",tile:u,coord:u.tileID,sourceCacheId:this.id,responseHeaders:E}))}_backfillDEM(u){const f=this.getRenderableIds();for(let S=0;S1||(Math.abs(E)>1&&(Math.abs(E+B)===1?E+=B:Math.abs(E-B)===1&&(E-=B)),T.dem&&S.dem&&(S.dem.backfillBorder(T.dem,E,L),S.neighboringTiles&&S.neighboringTiles[q]&&(S.neighboringTiles[q].backfilled=!0)))}}getTile(u){return this.getTileByID(u.key)}getTileByID(u){return this._tiles[u]}_retainLoadedChildren(u,f,v,S){for(const T in this._tiles){let E=this._tiles[T];if(S[T]||!E.hasData()||E.tileID.overscaledZ<=f||E.tileID.overscaledZ>v)continue;let L=E.tileID;for(;E&&E.tileID.overscaledZ>f+1;){const q=E.tileID.scaledTo(E.tileID.overscaledZ-1);E=this._tiles[q.key],E&&E.hasData()&&(L=q)}let B=L;for(;B.overscaledZ>f;)if(B=B.scaledTo(B.overscaledZ-1),u[B.key]){S[L.key]=L;break}}}findLoadedParent(u,f){if(u.key in this._loadedParentTiles){const v=this._loadedParentTiles[u.key];return v&&v.tileID.overscaledZ>=f?v:null}for(let v=u.overscaledZ-1;v>=f;v--){const S=u.scaledTo(v),T=this._getLoadedTile(S);if(T)return T}}_getLoadedTile(u){const f=this._tiles[u.key];return f&&f.hasData()?f:this._cache.getByKey(this._source.reparseOverscaled?u.wrapped().key:u.canonical.key)}updateCacheSize(u,f){f=f||this._source.tileSize;const v=Math.ceil(u.width/f)+1,S=Math.ceil(u.height/f)+1,T=Math.floor(v*S*5),E=typeof this._minTileCacheSize=="number"?Math.max(this._minTileCacheSize,T):T,L=typeof this._maxTileCacheSize=="number"?Math.min(this._maxTileCacheSize,E):E;this._cache.setMaxSize(L)}handleWrapJump(u){const f=Math.round((u-(this._prevLng===void 0?u:this._prevLng))/360);if(this._prevLng=u,f){const v={};for(const S in this._tiles){const T=this._tiles[S];T.tileID=T.tileID.unwrapTo(T.tileID.wrap+f),v[T.tileID.key]=T}this._tiles=v;for(const S in this._timers)clearTimeout(this._timers[S]),delete this._timers[S];for(const S in this._tiles)this._setTileReloadTimer(+S,this._tiles[S])}}update(u,f,v,S,T){if(this.transform=u,!this._sourceLoaded||this._paused||this.transform.freezeTileCoverage||this.usedForTerrain&&!v)return;this.updateCacheSize(u,f),this.transform.projection.name!=="globe"&&this.handleWrapJump(this.transform.center.lng),this._shadowCasterTiles={},this._coveredTiles={};const E=this._source.type==="batched-model";let L,B=this._source.maxzoom;const q=this.map&&this.map.painter?this.map.painter._terrain:null;if(q&&q.sourceCache===this&&q.attenuationRange()){const J=q.attenuationRange()[0],re=Math.floor(J)-Math.log2(q.getDemUpscale());B>re&&(B=re)}if(this.used||this.usedForTerrain){if(this._source.tileID)L=u.getVisibleUnwrappedCoordinates(this._source.tileID).map(J=>new a.aQ(J.canonical.z,J.wrap,J.canonical.z,J.canonical.x,J.canonical.y));else if(this.tileCoverLift!==0){const J=u.clone();J.tileCoverLift=this.tileCoverLift,L=J.coveringTiles({tileSize:f||this._source.tileSize,minzoom:this._source.minzoom,maxzoom:B,roundZoom:this._source.roundZoom&&!v,reparseOverscaled:this._source.reparseOverscaled,isTerrainDEM:this.usedForTerrain,calculateQuadrantVisibility:E}),this._source.minzoom<=1&&u.projection.name==="globe"&&(L.push(new a.aQ(1,0,1,0,0)),L.push(new a.aQ(1,0,1,1,0)),L.push(new a.aQ(1,0,1,0,1)),L.push(new a.aQ(1,0,1,1,1)))}else if(L=u.coveringTiles({tileSize:f||this._source.tileSize,minzoom:this._source.minzoom,maxzoom:B,roundZoom:this._source.roundZoom&&!v,reparseOverscaled:this._source.reparseOverscaled,isTerrainDEM:this.usedForTerrain,calculateQuadrantVisibility:E}),this._source.hasTile){const J=this._source.hasTile.bind(this._source);L=L.filter(re=>J(re))}}else L=[];if(L.length>0&&this.transform.projection.name!=="globe"&&!this.usedForTerrain&&!Vp(this._source.type)){const J=u.coveringZoomLevel({tileSize:f||this._source.tileSize,roundZoom:this._source.roundZoom&&!v}),re=Math.min(J,this._source.maxzoom);if(E){const oe=u.extendTileCover(L,re);for(const se of oe)L.push(se)}else if(T){const oe=u.extendTileCoverToNearPlane(L,this.transform.getFrustum(re),re);for(const se of oe)L.push(se)}else if(this.castsShadows&&S){const oe=u.extendTileCover(L,re,S,16);for(const se of oe)this._shadowCasterTiles[se.key]=!0,L.push(se)}}const G=this._updateRetainedTiles(L);if(Vp(this._source.type)&&L.length!==0){const J={},re={},oe=Object.keys(G);for(const me of oe){const fe=G[me],Ne=this._tiles[me];if(!Ne||Ne.fadeEndTime&&Ne.fadeEndTime<=a.o.now())continue;const Ae=this.findLoadedParent(fe,Math.max(fe.overscaledZ-jc.maxOverzooming,this._source.minzoom));Ae&&(this._addTile(Ae.tileID),J[Ae.tileID.key]=Ae.tileID),re[me]=fe}const se=L[L.length-1].overscaledZ;for(const me in this._tiles){const fe=this._tiles[me];if(G[me]||!fe.hasData())continue;let Ne=fe.tileID;for(;Ne.overscaledZ>se;){Ne=Ne.scaledTo(Ne.overscaledZ-1);const Ae=this._tiles[Ne.key];if(Ae&&Ae.hasData()&&re[Ne.key]){G[me]=fe.tileID;break}}}for(const me in J)G[me]||(this._coveredTiles[me]=!0,G[me]=J[me])}for(const J in G)this._tiles[J].clearFadeHold();const ee=a.bv(this._tiles,G);for(const J of ee){const re=this._tiles[J];re.hasSymbolBuckets&&!re.holdingForFade()?re.setHoldDuration(this.map._fadeDuration):re.hasSymbolBuckets&&!re.symbolFadeFinished()||this._removeTile(+J)}this._updateLoadedParentTileCache(),this._onlySymbols&&this._source.afterUpdate&&this._source.afterUpdate()}releaseSymbolFadeTiles(){for(const u in this._tiles)this._tiles[u].holdingForFade()&&this._removeTile(+u)}_updateRetainedTiles(u){const f={};if(u.length===0)return f;const v={},S=u.reduce((q,G)=>Math.min(q,G.overscaledZ),1/0),T=u[0].overscaledZ,E=Math.max(T-jc.maxOverzooming,this._source.minzoom),L=Math.max(T+jc.maxUnderzooming,this._source.minzoom),B={};for(const q of u){const G=this._addTile(q);f[q.key]=q,G.hasData()||S=this._source.maxzoom){const J=q.children(this._source.maxzoom)[0],re=this.getTile(J);if(re&&re.hasData()){f[J.key]=J;continue}}else{const J=q.children(this._source.maxzoom);if(f[J[0].key]&&f[J[1].key]&&f[J[2].key]&&f[J[3].key])continue}let ee=G.wasRequested();for(let J=q.overscaledZ-1;J>=E;--J){const re=q.scaledTo(J);if(v[re.key]||(v[re.key]=!0,G=this.getTile(re),!G&&ee&&(G=this._addTile(re)),G&&(f[re.key]=re,ee=G.wasRequested(),G.hasData())))break}}return f}_updateLoadedParentTileCache(){this._loadedParentTiles={};for(const u in this._tiles){const f=[];let v,S=this._tiles[u].tileID;for(;S.overscaledZ>0;){if(S.key in this._loadedParentTiles){v=this._loadedParentTiles[S.key];break}f.push(S.key);const T=S.scaledTo(S.overscaledZ-1);if(v=this._getLoadedTile(T),v)break;S=T}for(const T of f)this._loadedParentTiles[T]=v}}_addTile(u){let f=this._tiles[u.key];if(f)return f.isExtraShadowCaster!==!0||this._shadowCasterTiles[u.key]||this._reloadTile(u.key,"reloading"),f;f=this._cache.getAndRemove(u),f&&(this._setTileReloadTimer(u.key,f),f.tileID=u,this._state.initializeTileState(f,this.map?this.map.painter:null),this._cacheTimers[u.key]&&(clearTimeout(this._cacheTimers[u.key]),delete this._cacheTimers[u.key],this._setTileReloadTimer(u.key,f)));const v=!!f;if(!v){const S=this.map?this.map.painter:null,T=this._source.tileSize*u.overscaleFactor();f=this._source.type==="raster-array"?new x0(u,T,this.transform.tileZoom,S,this._isRaster):new Up(u,T,this.transform.tileZoom,S,this._isRaster,this._source.worldview),this._loadTile(f,this._tileLoaded.bind(this,f,u.key,f.state))}return f.uses++,this._tiles[u.key]=f,v||this._source.fire(new a.z("dataloading",{tile:f,coord:f.tileID,dataType:"source"})),f}_setTileReloadTimer(u,f){u in this._timers&&(clearTimeout(this._timers[u]),delete this._timers[u]);const v=f.getExpiryTimeout();v&&(this._timers[u]=setTimeout(()=>{this._reloadTile(u,"expired"),delete this._timers[u]},v))}_removeTile(u){const f=this._tiles[u];f&&(f.uses--,delete this._tiles[u],this._timers[u]&&(clearTimeout(this._timers[u]),delete this._timers[u]),f.uses>0||(f.hasData()&&f.state!=="reloading"||f.state==="empty"?this._cache.add(f.tileID,f,f.getExpiryTimeout()):(f.aborted=!0,this._abortTile(f),this._unloadTile(f))))}clearTiles(){this._shouldReloadOnResume=!1,this._paused=!1;for(const u in this._tiles)this._removeTile(+u);this._source._clear&&this._source._clear(),this._cache.reset(),this.map&&this.usedForTerrain&&this.map.painter.terrain&&this.map.painter.terrain.resetTileLookupCache(this.id)}tilesIn(u,f,v){const S=[],T=this.transform;if(!T)return S;const E=T.projection.name==="globe",L=a.aF(T.center.lng);for(const B in this._tiles){const q=this._tiles[B];if(v&&q.clearQueryDebugViz(),q.holdingForFade())continue;let G;if(E){const ee=q.tileID.canonical;if(ee.z===0){const J=[Math.abs(a.aA(L,...Sh(ee,-1))-L),Math.abs(a.aA(L,...Sh(ee,1))-L)];G=[0,2*J.indexOf(Math.min(...J))-1]}else{const J=[Math.abs(a.aA(L,...Sh(ee,-1))-L),Math.abs(a.aA(L,...Sh(ee,0))-L),Math.abs(a.aA(L,...Sh(ee,1))-L)];G=[J.indexOf(Math.min(...J))-1]}}else G=[0];for(const ee of G){const J=u.containsTile(q,T,f,ee);J&&S.push(J)}}return S}getShadowCasterCoordinates(){return this._getRenderableCoordinates(!1,!0)}getVisibleCoordinates(u){return this._getRenderableCoordinates(u)}_getRenderableCoordinates(u,f){const v=this.getRenderableIds(u,f).map(T=>this._tiles[T].tileID),S=this.transform.projection.name==="globe";for(const T of v)T.projMatrix=this.transform.calculateProjMatrix(T.toUnwrapped()),T.expandedProjMatrix=S?this.transform.calculateProjMatrix(T.toUnwrapped(),!1,!0):T.projMatrix;return v}sortCoordinatesByDistance(u){const f=u.slice(),v=this.transform._camera.position,S=this.transform._camera.forward(),T={};for(const E of f){const L=1/(1<T[E.key]-T[L.key]),f}hasTransition(){if(this._source.hasTransition())return!0;if(Vp(this._source.type))for(const u in this._tiles){const f=this._tiles[u];if(f.fadeEndTime!==void 0&&f.fadeEndTime>=a.o.now())return!0}return!1}setFeatureState(u,f,v){this._state.updateState(u=u||"_geojsonTileLayer",f,v)}removeFeatureState(u,f,v){this._state.removeFeatureState(u=u||"_geojsonTileLayer",f,v)}getFeatureState(u,f){return this._state.getState(u=u||"_geojsonTileLayer",f)}setDependencies(u,f,v){const S=this._tiles[u];S&&S.setDependencies(f,v)}reloadTilesForDependencies(u,f){for(const v in this._tiles)this._tiles[v].hasDependency(u,f)&&this._reloadTile(+v,"reloading");this._cache.filter(v=>!v.hasDependency(u,f))}_preloadTiles(u,f){if(!this._sourceLoaded){const B=()=>{this._sourceLoaded&&(this._source.off("data",B),this._preloadTiles(u,f))};return void this._source.on("data",B)}const v=new Map,S=Array.isArray(u)?u:[u],T=this.map.painter.terrain,E=this.usedForTerrain&&T?T.getScaledDemTileSize():this._source.tileSize;for(const B of S){const q=B.coveringTiles({tileSize:E,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this._source.roundZoom&&!this.usedForTerrain,reparseOverscaled:this._source.reparseOverscaled,isTerrainDEM:this.usedForTerrain});for(const G of q)v.set(G.key,G);this.usedForTerrain&&B.updateElevation(!1)}const L=Array.from(v.values());a.bw(L,(B,q)=>{const G=new Up(B,this._source.tileSize*B.overscaleFactor(),this.transform.tileZoom,this.map.painter,this._isRaster,this._source.worldview);this._loadTile(G,ee=>{this._source.type==="raster-dem"&&G.dem&&this._backfillDEM(G),q(ee,G)})},f)}}function v0(x,u){const f=Math.abs(2*x.wrap)-+(x.wrap<0),v=Math.abs(2*u.wrap)-+(u.wrap<0);return x.overscaledZ-u.overscaledZ||v-f||u.canonical.y-x.canonical.y||u.canonical.x-x.canonical.x}function Vp(x){return x==="raster"||x==="image"||x==="video"||x==="custom"}function Sh(x,u){const f=1<0:v.type==="building"?S=!v.isHidden(u)&&v.paint.get("building-opacity")>0:v.type==="model"&&(S=!v.isHidden(u)&&v.paint.get("model-opacity").constantOr(1)>0),this.layersGotHidden=this.layersGotHidden||!S&&f.visible,f.visible=S}}updateZOffset(u,f){this.currentBuildingBuckets=[];for(const S of this.layers){const T=S.layer,E=this.style.getLayerSourceCache(T);let L=1;T.type==="fill-extrusion"?L=S.visible?T.paint.get("fill-extrusion-vertical-scale"):0:T.type==="building"&&(L=S.visible?T.paint.get("building-vertical-scale"):0);let B=E?E.getTile(f):null;if(!B&&E)for(const q in E._tiles){const G=E._tiles[q];if(f.canonical.isChildOf(G.tileID.canonical)){B=G;break}}this.currentBuildingBuckets.push({bucket:B?B.getBucket(T):null,tileID:B?B.tileID:f,verticalScale:L})}u.hasAnyZOffset=!1;let v=!1;for(let S=0;S{v in u&&(f[v]=u[v])}),f}function Ox(x){x=x.slice();const u=Object.create(null);for(let f=0;f0?(S-E)/L:0;return this.points[T].mult(1-B).add(this.points[f].mult(B))}}class cS{constructor(u,f,v){const S=this.boxCells=[],T=this.circleCells=[];this.xCellCount=Math.ceil(u/v),this.yCellCount=Math.ceil(f/v);for(let E=0;Ethis.width||S<0||f>this.height)return!T&&[];const L=[];if(u<=0&&f<=0&&this.width<=v&&this.height<=S){if(T)return!0;for(let B=0;B0:L}_queryCircle(u,f,v,S,T){const E=u-v,L=u+v,B=f-v,q=f+v;if(L<0||E>this.width||q<0||B>this.height)return!S&&[];const G=[];return this._forEachCell(E,B,L,q,this._queryCellCircle,G,{hitTest:S,circle:{x:u,y:f,radius:v},seenUids:{box:{},circle:{}}},T),S?G.length>0:G}query(u,f,v,S,T){return this._query(u,f,v,S,!1,T)}hitTest(u,f,v,S,T){return this._query(u,f,v,S,!0,T)}hitTestCircle(u,f,v,S){return this._queryCircle(u,f,v,!0,S)}_queryCell(u,f,v,S,T,E,L,B){const q=L.seenUids,G=this.boxCells[T];if(G!==null){const J=this.bboxes;for(const re of G)if(!q.box[re]){q.box[re]=!0;const oe=4*re;if(u<=J[oe+2]&&f<=J[oe+3]&&v>=J[oe+0]&&S>=J[oe+1]&&(!B||B(this.boxKeys[re]))){if(L.hitTest)return E.push(!0),!0;E.push({key:this.boxKeys[re],x1:J[oe],y1:J[oe+1],x2:J[oe+2],y2:J[oe+3]})}}}const ee=this.circleCells[T];if(ee!==null){const J=this.circles;for(const re of ee)if(!q.circle[re]){q.circle[re]=!0;const oe=3*re;if(this._circleAndRectCollide(J[oe],J[oe+1],J[oe+2],u,f,v,S)&&(!B||B(this.circleKeys[re]))){if(L.hitTest)return E.push(!0),!0;{const se=J[oe],me=J[oe+1],fe=J[oe+2];E.push({key:this.circleKeys[re],x1:se-fe,y1:me-fe,x2:se+fe,y2:me+fe})}}}}}_queryCellCircle(u,f,v,S,T,E,L,B){const q=L.circle,G=L.seenUids,ee=this.boxCells[T];if(ee!==null){const re=this.bboxes;for(const oe of ee)if(!G.box[oe]){G.box[oe]=!0;const se=4*oe;if(this._circleAndRectCollide(q.x,q.y,q.radius,re[se+0],re[se+1],re[se+2],re[se+3])&&(!B||B(this.boxKeys[oe])))return E.push(!0),!0}}const J=this.circleCells[T];if(J!==null){const re=this.circles;for(const oe of J)if(!G.circle[oe]){G.circle[oe]=!0;const se=3*oe;if(this._circlesCollide(re[se],re[se+1],re[se+2],q.x,q.y,q.radius)&&(!B||B(this.circleKeys[oe])))return E.push(!0),!0}}}_forEachCell(u,f,v,S,T,E,L,B){const q=this._convertToXCellCoord(u),G=this._convertToYCellCoord(f),ee=this._convertToXCellCoord(v),J=this._convertToYCellCoord(S);for(let re=q;re<=ee;re++)for(let oe=G;oe<=J;oe++)if(T.call(this,u,f,v,S,this.xCellCount*oe+re,E,L,B))return}_convertToXCellCoord(u){return Math.max(0,Math.min(this.xCellCount-1,Math.floor(u*this.xScale)))}_convertToYCellCoord(u){return Math.max(0,Math.min(this.yCellCount-1,Math.floor(u*this.yScale)))}_circlesCollide(u,f,v,S,T,E){const L=S-u,B=T-f,q=v+E;return q*q>L*L+B*B}_circleAndRectCollide(u,f,v,S,T,E,L){const B=(E-S)/2,q=Math.abs(u-(S+B));if(q>B+v)return!1;const G=(L-T)/2,ee=Math.abs(f-(T+G));if(ee>G+v)return!1;if(q<=B||ee<=G)return!0;const J=q-B,re=ee-G;return J*J+re*re<=v*v}}const Of={unknown:0,flipRequired:1,flipNotRequired:2},qp=Math.tan(85*Math.PI/180);function vl(x,u,f,v,S,T,E){const L=a.bC();if(f)if(T.name==="globe"){const B=a.bD(S,u);a.aB(L,L,B)}else{const B=a.bE([],E);L[0]=B[0],L[1]=B[1],L[4]=B[2],L[5]=B[3],v||a.bB(L,L,S.angle)}else a.aB(L,S.labelPlaneMatrix,x);return L}function w0(x,u,f,v,S,T,E){const L=vl(x,u,f,v,S,T,E);return T.name==="globe"&&f||(L[2]=L[6]=L[10]=L[14]=0),L}function Fx(x,u,f,v,S,T,E){if(f){if(T.name==="globe"){const L=vl(x,u,f,v,S,T,E);return a.bl(L,L),a.aB(L,x,L),L}{const L=a.bz(x),B=a.bA([]);return B[0]=E[0],B[1]=E[1],B[4]=E[2],B[5]=E[3],a.aB(L,L,B),v||a.bB(L,L,-S.angle),L}}return S.glCoordMatrix}function xu(x,u,f,v){const S=[x,u,f,1];f?a.aC(S,S,v):Zr(S,S,v);const T=S[3];return S[0]/=T,S[1]/=T,S[2]/=T,S}function Us(x,u){return Math.min(.5+x/u*.5,1.5)}function tE(x,u){const f=x[0]/x[3],v=x[1]/x[3];return f>=-u[0]&&f<=u[0]&&v>=-u[1]&&v<=u[1]}function rE(x,u,f,v,S,T,E,L,B,q,G=1){const ee=f.transform,J=v?x.textSizeData:x.iconSizeData,re=a.bK(J,f.transform.zoom,G),oe=ee.projection.name==="globe",se=[256/f.width*2+1,256/f.height*2+1],me=v?x.text.dynamicLayoutVertexArray:x.icon.dynamicLayoutVertexArray;me.clear();let fe=null;oe&&(fe=v?x.text.globeExtVertexArray:x.icon.globeExtVertexArray);const Ne=x.lineVertexArray,Ae=v?x.text.placedSymbolArray:x.icon.placedSymbolArray,Te=f.transform.width/f.transform.height;let Ze,$e=!1;for(let He=0;HeMath.abs(f)?{useVertical:!0}:x===a.bL.vertical?v>0?{needsFlipping:!0}:null:u!==Of.unknown&&function(S,T){return S===0||Math.abs(T/S)>qp}(f,v)?u===Of.flipRequired?{needsFlipping:!0}:null:f<0?{needsFlipping:!0}:null}function uS(x,u,f,v,S,T,E,L,B,q,G,ee,J,re,oe,se,me,fe,Ne,Ae){const Te=u/24,Ze=x.lineOffsetX*Te,$e=x.lineOffsetY*Te,{lineStartIndex:He,glyphStartIndex:ze,numGlyphs:De,segment:Qe,writingMode:ht,flipState:ot}=x,Tt=He+x.lineLength,At=Bt=>{if(G){const[Mt,kt,Zt]=Bt.up,yr=q.length;a.bN(G,yr+0,Mt,kt,Zt),a.bN(G,yr+1,Mt,kt,Zt),a.bN(G,yr+2,Mt,kt,Zt),a.bN(G,yr+3,Mt,kt,Zt)}const[or,wt,st]=Bt.point;a.bO(q,or,wt,st,Bt.angle)};if(De>1){const Bt=nE(Te,L,Ze,$e,f,ee,J,x,B,T,re,se,!1,me,fe,Ne,Ae);if(!Bt)return{notEnoughRoom:!0};if(v&&!f){let[or,wt,st]=Bt.first.point,[Mt,kt,Zt]=Bt.last.point;[or,wt]=xu(or,wt,st,E),[Mt,kt]=xu(Mt,kt,Zt,E);const yr=fn(ht,ot,(Mt-or)*oe,kt-wt);if(x.flipState=yr&&yr.needsFlipping?Of.flipRequired:Of.flipNotRequired,yr)return yr}At(Bt.first);for(let or=ze+1;or0?Mt:vu(J,st,or,1,S,void 0,me,fe.canonical),Zt=fn(ht,ot,(kt[0]-or[0])*oe,kt[1]-or[1]);if(x.flipState=Zt&&Zt.needsFlipping?Of.flipRequired:Of.flipNotRequired,Zt)return Zt}const Bt=fg(Te*L.getoffsetX(ze),Ze,$e,f,ee,J,Qe,He,Tt,B,T,re,se,!1,!1,me,fe,Ne,Ae);if(!Bt)return{notEnoughRoom:!0};At(Bt)}return{}}function zx(x,u,f,v,S){const{x:T,y:E,z:L}=v.projectTilePoint(x.x,x.y,u);if(!S)return xu(T,E,L,f);const[B,q,G]=S.getElevation(x,S.elevation,S.elevationFeature);return xu(T+B,E+q,L+G,f)}function vu(x,u,f,v,S,T,E,L){const B=zx(x.sub(u)._unit()._add(x),L,S,E,T);return a.av(B,f,B),a.aw(B,B),a.bH(B,f,B,v)}function fg(x,u,f,v,S,T,E,L,B,q,G,ee,J,re,oe,se,me,fe,Ne){const Ae=v?x-u:x+u;let Te=Ae>0?1:-1,Ze=0;v&&(Te*=-1,Ze=Math.PI),Te<0&&(Ze+=Math.PI);let $e=L+E+(Te>0?0:1)|0,He=S,ze=S,De=0,Qe=0;const ht=Math.abs(Ae),ot=[],Tt=[];let At=T,Bt=At,or=a.bF([]);const wt=()=>vu(Bt,At,ze,ht-De+1,G,J,se,me.canonical);for(;De+Qe<=ht;){if($e+=Te,$e=B)return null;if(ze=He,Bt=At,ot.push(ze),re&&Tt.push(Bt),At=new a.P(q.getx($e),q.gety($e)),He=ee[$e],!He){const Fr=zx(At,me.canonical,G,se,J);He=Fr[3]>0?ee[$e]=Fr:wt()}De+=Qe;const lr=a.av([],He,ze),Ur=a.bG(ze,He);if(f&&Ur>0&&Qe>0&&a.bJ(or,lr)/(Qe*Ur)0,Ae),He=q*$e.perspectiveRatio,ze=(v.x1*f+L.x-v.padding)*He+$e.point.x,De=(v.y1*f+L.y-v.padding)*He+$e.point.y,Qe=(v.x2*f+L.x+v.padding)*He+$e.point.x,ht=(v.y2*f+L.y+v.padding)*He+$e.point.y,ot=$e.perspectiveRatio<=.55||$e.occluded;return!this.isInsideGrid(ze,De,Qe,ht)||!B&&this.grid.hitTest(ze,De,Qe,ht,ee)||ot?{box:[],offscreen:!1,occluded:$e.occluded}:{box:[ze,De,Qe,ht],offscreen:this.isOffscreen(ze,De,Qe,ht),occluded:!1}}placeCollisionCircles(u,f,v,S,T,E,L,B,q,G,ee,J,re,oe,se,me){const fe=[],Ne=this.transform.elevation,Ae=u.getProjection(),Te=u.elevationType==="road",Ze=!!Ne||Te,$e=a.bV.getAtTileOffsetFunc(me,this.transform.center.lat,this.transform.worldSize,Ae),He=new a.P(v.tileAnchorX,v.tileAnchorY),ze=new a.P(v.tileAnchorX,v.tileAnchorY);let{x:De,y:Qe,z:ht}=Ae.projectTilePoint(ze.x,ze.y,me.canonical),ot=null;if(Ze){const Ur=Te?u.getElevationFeatureForText(S):null;ot={getElevation:$e,elevation:Ne,elevationFeature:Ur};const[Fr,Tr,Mr]=$e(He,Ne,Ur);De+=Fr,Qe+=Tr,ht+=Mr}const Tt=Ae.name==="globe",At=this.projectAndGetPerspectiveRatio(B,De,Qe,ht,me,Tt||!!Ne||this.transform.pitch>0,Ae),{perspectiveRatio:Bt}=At,or=(J?L/Bt:L*Bt)/a.bY,wt=xu(De,Qe,ht,q),st=v.lineOffsetX*or,Mt=v.lineOffsetY*or,kt=a.an(u.layers[0].layout.get("text-max-angle")),Zt=Math.cos(kt),yr=At.signedDistanceFromCamera>0?nE(or,E,st,Mt,Te&&v.flipState===1,wt,ze,v,T,q,{},Ze&&!J?ot:null,J&&Ze,Ae,me,J,Zt):null;let Pr=!1,fr=!1,lr=!0;if(yr&&!At.occluded){const Ur=.5*oe*Bt+se,Fr=new a.P(-100,-100),Tr=new a.P(this.screenRightBoundary,this.screenBottomBoundary),Mr=new Lx,{first:tn,last:Cn}=yr,as=tn.path.length;let Is=[];for(let Sn=as-1;Sn>=1;Sn--)Is.push(tn.path[Sn]);for(let Sn=1;Sn(Ze&&!Tt&&(Ys=$e(VsSn[3]<=0)&&(Is=[]));let Cs=[];if(Is.length>0){let Sn=1/0,Ds=-1/0,Ys=1/0,Vs=-1/0;for(const ws of Is)Sn=Math.min(Sn,ws[0]),Ys=Math.min(Ys,ws[1]),Ds=Math.max(Ds,ws[0]),Vs=Math.max(Vs,ws[1]);Ds>=Fr.x&&Sn<=Tr.x&&Vs>=Fr.y&&Ys<=Tr.y&&(Cs=[Is.map(ws=>new a.P(ws[0],ws[1]))],(SnTr.x||YsTr.y)&&(Cs=a.bW(Cs,Fr.x,Fr.y,Tr.x,Tr.y)))}for(const Sn of Cs){Mr.reset(Sn,.25*Ur);let Ds=0;Ds=Mr.length<=.5*Ur?1:Math.ceil(Mr.paddedLength/qr)+1;for(let Ys=0;Ys0?(a.aC(B,B,u),this.fogState&&T&&L.name!=="globe"&&(q=function(J,re,oe,se,me,fe){const Ne=fe.calculateFogTileMatrix(me),Ae=[re,oe,se];return a.af(Ae,Ae,Ne),Ir(J,a.ag(Ae),fe.pitch,fe._fov)}(this.fogState,f,v,S,T.toUnwrapped(),this.transform)>.9)):Zr(B,B,u);const G=B[3];return{point:new a.P((B[0]/G+1)/2*this.transform.width+fs,(-B[1]/G+1)/2*this.transform.height+fs),perspectiveRatio:Math.min(.5+this.transform.getCameraToCenterDistance(L)/G*.5,1.5),signedDistanceFromCamera:G,occluded:E&&B[2]>G||q}}isOffscreen(u,f,v,S){return v=this.screenRightBoundary||Sthis.screenBottomBoundary}isInsideGrid(u,f,v,S){return v>=0&&u=0&&fv.collisionGroupID===f}}return this.collisionGroups[u]}}function tl(x,u,f,v,S){const{horizontalAlign:T,verticalAlign:E}=a.c1(x),L=-(T-.5)*u,B=-(E-.5)*f,q=a.c2(x,v);return new a.P(L+q[0]*S,B+q[1]*S)}function Ta(x,u,f,v,S){const T=new a.P(x,u);return f&&T._rotate(v?S:-S),T}class a4{constructor(u,f,v,S,T,E){this.transform=u.clone(),this.projection=u.projection.name,this.collisionIndex=new Zs(this.transform,T),this.buildingIndex=E,this.placements={},this.opacities={},this.variableOffsets={},this.stale=!1,this.commitTime=0,this.fadeDuration=f,this.retainedQueryData={},this.collisionGroups=new $x(v),this.collisionCircleArrays={},this.prevPlacement=S,S&&(S.prevPlacement=void 0),this.placedOrientations={},this.lastReplacementSourceUpdateTime=0}getBucketParts(u,f,v,S,T=1){const E=v.getBucket(f),L=v.latestFeatureIndex;if(!E||!L||f.fqid!==E.layerIds[0])return;const B=E.layers[0].layout,q=E.layers[0].paint,G=v.collisionBoxArray,ee=Math.pow(2,this.transform.zoom-v.tileID.overscaledZ),J=v.tileSize/a.al,re=v.tileID.toUnwrapped();this.transform.setProjection(E.projection);const oe=(se=v.tileID,me=E.getProjection(),fe=this.transform,me.name===this.projection?fe.calculateProjMatrix(se.toUnwrapped()):lS(fe,me,se));var se,me,fe;const Ne=B.get("text-pitch-alignment")==="map",Ae=B.get("text-rotation-alignment")==="map";f.compileFilter(f.options);const Te=f.dynamicFilter(),Ze=f.dynamicFilterNeedsFeature(),$e=this.transform.calculatePixelsToTileUnitsMatrix(v),He=w0(oe,v.tileID.canonical,Ne,Ae,this.transform,E.getProjection(),$e);let ze=null;const De=E.getProjection().createInversionMatrix(this.transform,v.tileID.canonical);if(Ne){const st=Fx(oe,v.tileID.canonical,Ne,Ae,this.transform,E.getProjection(),$e);ze=a.aB([],this.transform.labelPlaneMatrix,st)}let Qe=null;Te&&v.latestFeatureIndex&&(Qe={unwrappedTileID:re,dynamicFilter:Te,dynamicFilterNeedsFeature:Ze}),this.retainedQueryData[E.bucketInstanceId]=new Bx(E.bucketInstanceId,L,E.sourceLayerIndex,E.index,v.tileID);const[ht,ot]=E.layers[0].layout.get("text-size-scale-range"),Tt=a.aA(T,ht,ot),[At,Bt]=B.get("icon-size-scale-range"),or=a.aA(T,At,Bt),wt={bucket:E,layout:B,paint:q,posMatrix:oe,invMatrix:De,mercatorCenter:[a.aF(this.transform.center.lng),a.aJ(this.transform.center.lat)],textLabelPlaneMatrix:He,labelToScreenMatrix:ze,clippingData:Qe,scale:ee,textPixelRatio:J,holdingForFade:v.holdingForFade(),collisionBoxArray:G,partiallyEvaluatedTextSize:a.bK(E.textSizeData,this.transform.zoom,Tt),partiallyEvaluatedIconSize:a.bK(E.iconSizeData,this.transform.zoom,or),collisionGroup:this.collisionGroups.get(E.sourceID),latestFeatureIndex:v.latestFeatureIndex};if(S)for(const st of E.sortKeyRanges){const{sortKey:Mt,symbolInstanceStart:kt,symbolInstanceEnd:Zt}=st;u.push({sortKey:Mt,symbolInstanceStart:kt,symbolInstanceEnd:Zt,parameters:wt})}else u.push({symbolInstanceStart:0,symbolInstanceEnd:E.symbolInstances.length,parameters:wt})}attemptAnchorPlacement(u,f,v,S,T,E,L,B,q,G,ee,J,re,oe,se,me,fe,Ne,Ae,Te,Ze){const{textOffset0:$e,textOffset1:He,crossTileID:ze}=se,De=[$e,He],Qe=tl(u,E,L,De,B),ht=this.collisionIndex.placeCollisionBox(fe,B,f,v,S,T,Ta(Qe.x,Qe.y,q,G,this.transform.angle),oe,ee,J,re.predicate);if(Ae){const ot=fe.getSymbolInstanceIconSize(Ze,this.transform.zoom,se.placedIconSymbolIndex);if(this.collisionIndex.placeCollisionBox(fe,ot,Ae,v,S,T,Ta(Qe.x,Qe.y,q,G,this.transform.angle),oe,ee,J,re.predicate).box.length===0)return}if(ht.box.length>0){let ot;return this.prevPlacement&&this.prevPlacement.variableOffsets[ze]&&this.prevPlacement.placements[ze]&&this.prevPlacement.placements[ze].text&&(ot=this.prevPlacement.variableOffsets[ze].anchor),this.variableOffsets[ze]={textOffset:De,width:E,height:L,anchor:u,textScale:B,prevAnchor:ot},this.markUsedJustification(fe,u,se,Ne),fe.allowVerticalPlacement&&(this.markUsedOrientation(fe,Ne,se),this.placedOrientations[ze]=Ne),{shift:Qe,placedGlyphBoxes:ht}}}placeLayerBucketPart(u,f,v,S,T=1){const{bucket:E,layout:L,paint:B,posMatrix:q,textLabelPlaneMatrix:G,labelToScreenMatrix:ee,clippingData:J,textPixelRatio:re,mercatorCenter:oe,invMatrix:se,holdingForFade:me,collisionBoxArray:fe,partiallyEvaluatedTextSize:Ne,partiallyEvaluatedIconSize:Ae,collisionGroup:Te,latestFeatureIndex:Ze}=u.parameters,$e=L.get("text-optional"),He=L.get("icon-optional"),ze=L.get("text-allow-overlap"),De=L.get("icon-allow-overlap"),Qe=L.get("text-rotation-alignment")==="map",ht=L.get("icon-rotation-alignment")==="map",ot=L.get("text-pitch-alignment")==="map",Tt=B.get("symbol-z-offset"),At=L.get("symbol-elevation-reference")==="sea",Bt=L.get("symbol-placement"),[or,wt]=L.get("text-size-scale-range"),[st,Mt]=L.get("icon-size-scale-range"),kt=a.aA(T,or,wt),Zt=a.aA(T,st,Mt),yr=L.get("text-variable-anchor"),Pr=Qe&&Bt!=="point",fr=ht&&Bt!=="point",lr=yr&&E.hasTextData(),Ur=E.hasIconTextFit()&&lr&&E.hasIconData();this.transform.setProjection(E.projection);const Fr=lr||Pr,Tr=fr||Ur;let Mr=ze&&(De||!E.hasIconData()||He),tn=De&&(ze||!E.hasTextData()||$e);const Cn=!Tt.isConstant();!E.collisionArrays&&fe&&E.deserializeCollisionBoxes(fe),v&&S&&E.updateCollisionDebugBuffers(this.transform.zoom,fe,kt,Zt);const as=(qr,Cs,Sn)=>{const{crossTileID:Ds,numVerticalGlyphVertices:Ys}=qr;let Vs=null;if(J&&J.dynamicFilterNeedsFeature||Cn){const ra=this.retainedQueryData[E.bucketInstanceId];Vs=Ze.loadFeature({featureIndex:qr.featureIndex,bucketIndex:ra.bucketIndex,sourceLayerIndex:ra.sourceLayerIndex,layoutVertexArrayOffset:0});const ma=Vs.properties?Vs.properties.worldview:null;if(E.localizable&&E.worldview&&typeof ma=="string")if(ma==="all")Vs.properties.$localized=!0;else{if(!ma.split(",").includes(E.worldview))return;Vs.properties.$localized=!0,Vs.properties.worldview=E.worldview}}if(J&&!(0,J.dynamicFilter)({zoom:this.transform.zoom,pitch:this.transform.pitch,worldview:E.worldview},Vs,this.retainedQueryData[E.bucketInstanceId].tileID.canonical,new a.P(qr.tileAnchorX,qr.tileAnchorY),this.transform.calculateDistanceTileData(J.unwrappedTileID)))return this.placements[Ds]=new $s(!1,!1,!1,!0),void f.add(Ds);const ws=Tt.evaluate(Vs,{});if(f.has(Ds))return;if(me)return void(this.placements[Ds]=new $s(!1,!1,!1));let An=!1,Rs=!1,Qi=!0,Li=!1,Ls=!1,ms=null,Pn={box:null,offscreen:null,occluded:null},Ti={box:null},ua=null,Wi=null,ci=null,Ll=0,Uo=0,Ba=0;Sn.textFeatureIndex?Ll=Sn.textFeatureIndex:qr.useRuntimeCollisionCircles&&(Ll=qr.featureIndex),Sn.verticalTextFeatureIndex&&(Uo=Sn.verticalTextFeatureIndex);const nl=E.elevationFeatures?E.elevationFeatures[qr.elevationFeatureIndex]:void 0,sl=ra=>{ra.tileID=this.retainedQueryData[E.bucketInstanceId].tileID;const ma=this.transform.elevation;ra.elevation=At?ws:ws+a.bV.getAtTileOffset(ra.tileID,new a.P(ra.tileAnchorX,ra.tileAnchorY),ma,nl),ra.elevation+=qr.zOffset},To=Sn.textBox;if(To){sl(To);const ra=ui=>{let wa=a.bL.horizontal;if(E.allowVerticalPlacement&&!ui&&this.prevPlacement){const Ji=this.prevPlacement.placedOrientations[Ds];Ji&&(this.placedOrientations[Ds]=Ji,wa=Ji,this.markUsedOrientation(E,wa,qr))}return wa},ma=(ui,wa)=>{if(E.allowVerticalPlacement&&Ys>0&&Sn.verticalTextBox){for(const Ji of E.writingModes)if(Ji===a.bL.vertical?(Pn=wa(),Ti=Pn):Pn=ui(),Pn&&Pn.box&&Pn.box.length)break}else Pn=ui()};if(yr){let ui=yr;if(this.prevPlacement&&this.prevPlacement.variableOffsets[Ds]){const Gi=this.prevPlacement.variableOffsets[Ds];ui.indexOf(Gi.anchor)>0&&(ui=ui.filter(ku=>ku!==Gi.anchor),ui.unshift(Gi.anchor))}const wa=(Gi,ku,mv)=>{const td=E.getSymbolInstanceTextSize(Ne,qr,this.transform.zoom,Cs),gv=(Gi.x2-Gi.x1)*td+2*Gi.padding,Lg=(Gi.y2-Gi.y1)*td+2*Gi.padding,$d=qr.hasIconTextFit&&!De?ku:null;$d&&sl($d);let Fh={box:[],offscreen:!1,occluded:!1};const Fg=ze?2*ui.length:ui.length;for(let Yf=0;Yf=ui.length,qr,Cs,E,mv,$d,Ne,Ae);if(zh&&(Fh=zh.placedGlyphBoxes,Fh&&Fh.box&&Fh.box.length)){An=!0,ms=zh.shift;break}}return Fh};ma(()=>wa(To,Sn.iconBox,a.bL.horizontal),()=>{const Gi=Sn.verticalTextBox;return Gi&&sl(Gi),E.allowVerticalPlacement&&!(Pn&&Pn.box&&Pn.box.length)&&Ys>0&&Gi?wa(Gi,Sn.verticalIconBox,a.bL.vertical):{box:null,offscreen:null,occluded:null}}),Pn&&(An=Pn.box,Qi=Pn.offscreen,Li=Pn.occluded);const Ji=ra(!(!Pn||!Pn.box));if(!An&&this.prevPlacement){const Gi=this.prevPlacement.variableOffsets[Ds];Gi&&(this.variableOffsets[Ds]=Gi,this.markUsedJustification(E,Gi.anchor,qr,Ji))}}else{const ui=(wa,Ji)=>{const Gi=E.getSymbolInstanceTextSize(Ne,qr,this.transform.zoom,Cs),ku=this.collisionIndex.placeCollisionBox(E,Gi,wa,oe,se,Fr,new a.P(0,0),ze,re,q,Te.predicate);return ku&&ku.box&&ku.box.length&&(this.markUsedOrientation(E,Ji,qr),this.placedOrientations[Ds]=Ji),ku};ma(()=>ui(To,a.bL.horizontal),()=>{const wa=Sn.verticalTextBox;return E.allowVerticalPlacement&&Ys>0&&wa?(sl(wa),ui(wa,a.bL.vertical)):{box:null,offscreen:null,occluded:null}}),ra(!!(Pn&&Pn.box&&Pn.box.length))}}if(ua=Pn,An=ua&&ua.box&&ua.box.length>0,Qi=ua&&ua.offscreen,Li=ua&&ua.occluded,qr.useRuntimeCollisionCircles){const ra=qr.centerJustifiedTextSymbolIndex>=0?qr.centerJustifiedTextSymbolIndex:qr.verticalPlacedTextSymbolIndex,ma=E.text.placedSymbolArray.get(ra),ui=a.bM(E.textSizeData,Ne,ma),wa=L.get("text-padding");Wi=this.collisionIndex.placeCollisionCircles(E,ze,ma,ra,E.lineVertexArray,E.glyphOffsetArray,ui,q,G,ee,v,ot,Te.predicate,qr.collisionCircleDiameter*ui/a.bY,wa,this.retainedQueryData[E.bucketInstanceId].tileID),An=ze||Wi.circles.length>0&&!Wi.collisionDetected,Qi=Qi&&Wi.offscreen,Li=Wi.occluded}if(Sn.iconFeatureIndex&&(Ba=Sn.iconFeatureIndex),Sn.iconBox){const ra=ma=>{sl(ma);const ui=qr.hasIconTextFit&&ms?Ta(ms.x,ms.y,Qe,ot,this.transform.angle):new a.P(0,0),wa=E.getSymbolInstanceIconSize(Ae,this.transform.zoom,qr.placedIconSymbolIndex);return this.collisionIndex.placeCollisionBox(E,wa,ma,oe,se,Tr,ui,De,re,q,Te.predicate)};Ti&&Ti.box&&Ti.box.length&&Sn.verticalIconBox?(ci=ra(Sn.verticalIconBox),Rs=ci.box.length>0):(ci=ra(Sn.iconBox),Rs=ci.box.length>0),Qi=Qi&&ci.offscreen,Ls=ci.occluded}const Hc=$e||qr.numHorizontalGlyphVertices===0&&Ys===0,Cu=He||qr.numIconVertices===0;if(Hc||Cu?Cu?Hc||(Rs=Rs&&An):An=Rs&&An:Rs=An=Rs&&An,An&&ua&&ua.box&&this.collisionIndex.insertCollisionBox(ua.box,L.get("text-ignore-placement"),E.bucketInstanceId,Ti&&Ti.box&&Uo?Uo:Ll,Te.ID),Rs&&ci&&this.collisionIndex.insertCollisionBox(ci.box,L.get("icon-ignore-placement"),E.bucketInstanceId,Ba,Te.ID),Wi&&(An&&this.collisionIndex.insertCollisionCircles(Wi.circles,L.get("text-ignore-placement"),E.bucketInstanceId,Ll,Te.ID),v)){const ra=E.bucketInstanceId;let ma=this.collisionCircleArrays[ra];ma===void 0&&(ma=this.collisionCircleArrays[ra]=new j0);for(let ui=0;ui=0;--Cs){const Sn=qr[Cs];as(E.symbolInstances.get(Sn),Sn,E.collisionArrays[Sn])}E.hasAnyZOffset&&a.w(`${E.layerIds[0]} layer symbol-z-elevate: symbols are not sorted by elevation if symbol-z-order is evaluated to viewport-y`)}else if(E.hasAnyZOffset){const qr=E.getSortedIndexesByZOffset();for(let Cs=0;Cs=0&&(u.text.placedSymbolArray.get(T).crossTileID=ee>=0&&T!==ee?0:q),E>=0&&(u.text.placedSymbolArray.get(E).crossTileID=ee>=0&&E!==ee?0:q),L>=0&&(u.text.placedSymbolArray.get(L).crossTileID=ee>=0&&L!==ee?0:q),B>=0&&(u.text.placedSymbolArray.get(B).crossTileID=ee>=0&&B!==ee?0:q)}markUsedOrientation(u,f,v){const S=f===a.bL.horizontal||f===a.bL.horizontalOnly?f:0,T=f===a.bL.vertical?f:0,{leftJustifiedTextSymbolIndex:E,centerJustifiedTextSymbolIndex:L,rightJustifiedTextSymbolIndex:B,verticalPlacedTextSymbolIndex:q}=v,G=u.text.placedSymbolArray;E>=0&&(G.get(E).placedOrientation=S),L>=0&&(G.get(L).placedOrientation=S),B>=0&&(G.get(B).placedOrientation=S),q>=0&&(G.get(q).placedOrientation=T)}commit(u){this.commitTime=u,this.zoomAtLastRecencyCheck=this.transform.zoom;const f=this.prevPlacement;let v=!1;this.prevZoomAdjustment=f?f.zoomAdjustment(this.transform.zoom):0;const S=f?f.symbolFadeChange(u):1,T=f?f.opacities:{},E=f?f.variableOffsets:{},L=f?f.placedOrientations:{};for(const B in this.placements){const q=this.placements[B],G=T[B];G?(this.opacities[B]=new Id(G,S,q.text,q.icon,null,q.clipped),v=v||q.text!==G.text.placed||q.icon!==G.icon.placed):(this.opacities[B]=new Id(null,S,q.text,q.icon,q.skipFade,q.clipped),v=v||q.text||q.icon)}for(const B in T){const q=T[B];if(!this.opacities[B]){const G=new Id(q,S,!1,!1);G.isHidden()||(this.opacities[B]=G,v=v||q.text.placed||q.icon.placed)}}for(const B in E)this.variableOffsets[B]||!this.opacities[B]||this.opacities[B].isHidden()||(this.variableOffsets[B]=E[B]);for(const B in L)this.placedOrientations[B]||!this.opacities[B]||this.opacities[B].isHidden()||(this.placedOrientations[B]=L[B]);v?this.lastPlacementChangeTime=u:typeof this.lastPlacementChangeTime!="number"&&(this.lastPlacementChangeTime=f?f.lastPlacementChangeTime:u)}updateLayerOpacities(u,f,v,S){S&&(this.lastReplacementSourceUpdateTime=S.updateTime);const T=new Set;for(const E of f){const L=E.getBucket(u);L&&E.latestFeatureIndex&&u.fqid===L.layerIds[0]&&(this.updateBucketOpacities(L,T,E,E.collisionBoxArray,v,S,E.tileID,u.scope),L.elevationType==="offset"&&this.buildingIndex&&this.buildingIndex.updateZOffset(L,E.tileID),L.elevationType==="road"&&L.updateRoadElevation(E.tileID.canonical),L.updateZOffset())}}updateBucketOpacities(u,f,v,S,T,E,L,B){u.hasTextData()&&u.text.opacityVertexArray.clear(),u.hasIconData()&&u.icon.opacityVertexArray.clear(),u.hasIconCollisionBoxData()&&u.iconCollisionBox.collisionVertexArray.clear(),u.hasTextCollisionBoxData()&&u.textCollisionBox.collisionVertexArray.clear();const q=u.layers[0].layout,G=u.layers[0].paint,ee=!!u.layers[0].dynamicFilter(),J=new Id(null,0,!1,!1,!0),re=q.get("text-allow-overlap"),oe=q.get("icon-allow-overlap"),se=q.get("text-variable-anchor"),me=q.get("text-rotation-alignment")==="map",fe=q.get("text-pitch-alignment")==="map",Ne=G.get("symbol-z-offset"),Ae=q.get("symbol-elevation-reference")==="sea",Te=!Ne.isConstant(),Ze=new Id(null,0,re&&(oe||!u.hasIconData()||q.get("icon-optional")),oe&&(re||!u.hasTextData()||q.get("text-optional")),!0);!u.collisionArrays&&S&&(u.hasIconCollisionBoxData()||u.hasTextCollisionBoxData())&&u.deserializeCollisionBoxes(S);const $e=(ze,De,Qe)=>{for(let ht=0;ht0||ht>0,yr=Tt>0,Pr=this.placedOrientations[ot],fr=Pr===a.bL.vertical,lr=Pr===a.bL.horizontal||Pr===a.bL.horizontalOnly;!Zt&&!yr||kt.isHidden()||He++;let Ur=!1;if((Zt||yr)&&E)for(const Fr of u.activeReplacements){if(a.bZ(Fr,T,a.b_.Symbol,B)||Fr.min.x>At||At>Fr.max.x||Fr.min.y>Bt||Bt>Fr.max.y)continue;const Tr=a.b$(At,Bt,L.canonical,Fr.footprintTileId.canonical);if(Ur=a.c0(Tr,Fr.footprint),Ur)break}if(Zt){const Fr=Ur?Hp:Ml(kt.text);$e(u.text,Qe,fr?Hp:Fr),$e(u.text,ht,lr?Hp:Fr);const Tr=kt.text.isHidden(),{leftJustifiedTextSymbolIndex:Mr,centerJustifiedTextSymbolIndex:tn,rightJustifiedTextSymbolIndex:Cn,verticalPlacedTextSymbolIndex:as}=De,Is=u.text.placedSymbolArray,qr=Tr||fr?1:0;Mr>=0&&(Is.get(Mr).hidden=qr),tn>=0&&(Is.get(tn).hidden=qr),Cn>=0&&(Is.get(Cn).hidden=qr),as>=0&&(Is.get(as).hidden=Tr||lr?1:0);const Cs=this.variableOffsets[ot];Cs&&this.markUsedJustification(u,Cs.anchor,De,Pr);const Sn=this.placedOrientations[ot];Sn&&(this.markUsedJustification(u,"left",De,Sn),this.markUsedOrientation(u,Sn,De))}if(yr){const Fr=Ur?Hp:Ml(kt.icon),{placedIconSymbolIndex:Tr,verticalPlacedIconSymbolIndex:Mr}=De,tn=u.icon.placedSymbolArray,Cn=kt.icon.isHidden()?1:0;Tr>=0&&($e(u.icon,Tt,fr?Hp:Fr),tn.get(Tr).hidden=Cn),Mr>=0&&($e(u.icon,De.numVerticalIconVertices,lr?Hp:Fr),tn.get(Mr).hidden=Cn)}if(u.hasIconCollisionBoxData()||u.hasTextCollisionBoxData()){const Fr=u.collisionArrays[ze];if(Fr){let Tr=new a.P(0,0),Mr=!0;if(Fr.textBox||Fr.verticalTextBox){if(se){const Cn=this.variableOffsets[ot];Cn?(Tr=tl(Cn.anchor,Cn.width,Cn.height,Cn.textOffset,Cn.textScale),me&&Tr._rotate(fe?this.transform.angle:-this.transform.angle)):Mr=!1}ee&&(Mr=!kt.clipped),Fr.textBox&&Rf(u.textCollisionBox.collisionVertexArray,kt.text.placed,!Mr||fr,st,Ae,Tr.x,Tr.y),Fr.verticalTextBox&&Rf(u.textCollisionBox.collisionVertexArray,kt.text.placed,!Mr||lr,st,Ae,Tr.x,Tr.y)}const tn=Mr&&!!(!lr&&Fr.verticalIconBox);Fr.iconBox&&Rf(u.iconCollisionBox.collisionVertexArray,kt.icon.placed,tn,st,Ae,De.hasIconTextFit?Tr.x:0,De.hasIconTextFit?Tr.y:0),Fr.verticalIconBox&&Rf(u.iconCollisionBox.collisionVertexArray,kt.icon.placed,!tn,st,Ae,De.hasIconTextFit?Tr.x:0,De.hasIconTextFit?Tr.y:0)}}}if(u.fullyClipped=He===0,u.sortFeatures(this.transform.angle),this.retainedQueryData[u.bucketInstanceId]&&(this.retainedQueryData[u.bucketInstanceId].featureSortOrder=u.featureSortOrder),u.hasTextData()&&u.text.opacityVertexBuffer&&u.text.opacityVertexBuffer.updateData(u.text.opacityVertexArray),u.hasIconData()&&u.icon.opacityVertexBuffer&&u.icon.opacityVertexBuffer.updateData(u.icon.opacityVertexArray),u.hasIconCollisionBoxData()&&u.iconCollisionBox.collisionVertexBuffer&&u.iconCollisionBox.collisionVertexBuffer.updateData(u.iconCollisionBox.collisionVertexArray),u.hasTextCollisionBoxData()&&u.textCollisionBox.collisionVertexBuffer&&u.textCollisionBox.collisionVertexBuffer.updateData(u.textCollisionBox.collisionVertexArray),u.bucketInstanceId in this.collisionCircleArrays){const ze=this.collisionCircleArrays[u.bucketInstanceId];u.placementInvProjMatrix=ze.invProjMatrix,u.placementViewportMatrix=ze.viewportMatrix,u.collisionCircleArray=ze.circles,delete this.collisionCircleArrays[u.bucketInstanceId]}}symbolFadeChange(u){return this.fadeDuration===0?1:(u-this.commitTime)/this.fadeDuration+this.prevZoomAdjustment}zoomAdjustment(u){return Math.max(0,(this.transform.zoom-u)/1.5)}hasTransitions(u){return this.stale||u-this.lastPlacementChangeTimeu}isStale(){return this.stale}setStale(){this.stale=!0}}function Rf(x,u,f,v,S,T,E){x.emplaceBack(u?1:0,f?1:0,T||0,E||0,v,S?1:0),x.emplaceBack(u?1:0,f?1:0,T||0,E||0,v,S?1:0),x.emplaceBack(u?1:0,f?1:0,T||0,E||0,v,S?1:0),x.emplaceBack(u?1:0,f?1:0,T||0,E||0,v,S?1:0)}const dS=Math.pow(2,25),Ux=Math.pow(2,24),S0=Math.pow(2,17),hS=Math.pow(2,16),N0=Math.pow(2,9),Il=Math.pow(2,8),Nh=Math.pow(2,1);function Ml(x){if(x.opacity===0&&!x.placed)return 0;if(x.opacity===1&&x.placed)return 4294967295;const u=x.placed?1:0,f=Math.floor(127*x.opacity);return f*dS+u*Ux+f*S0+u*hS+f*N0+u*Il+f*Nh+u}const Hp=0;class pg{constructor(u){this._sortAcrossTiles=u.layout.get("symbol-z-order")!=="viewport-y"&&u.layout.get("symbol-sort-key").constantOr(1)!==void 0,this._currentTileIndex=0,this._currentPartIndex=0,this._seenCrossTileIDs=new Set,this._bucketParts=[]}continuePlacement(u,f,v,S,T,E){const L=this._bucketParts;for(;this._currentTileIndexB.sortKey-q.sortKey));this._currentPartIndex{const B=a.o.now()-E;return!this._forceFullPlacement&&B>2};for(;this._currentPlacementIndex>=0;){const B=f[u[this._currentPlacementIndex]],q=this.placement.collisionIndex.transform.zoom;if(B.type==="symbol"&&B.visibility!=="none"&&(!B.minzoom||B.minzoom<=q)&&(!B.maxzoom||B.maxzoom>q)){const G=B,ee=G.layout.get("symbol-z-elevate"),J=G.layout.get("symbol-sort-key").constantOr(1)!==void 0,re=G.layout.get("symbol-z-order"),oe=re==="viewport-y"||re==="auto"&&!(re!=="viewport-y"&&J),se=G.layout.get("text-allow-overlap")||G.layout.get("icon-allow-overlap")||G.layout.get("text-ignore-placement")||G.layout.get("icon-ignore-placement"),me=oe&&se,fe=this._inProgressLayer=this._inProgressLayer||new pg(G),Ne=a.B(B.source,B.scope);if(fe.continuePlacement(ee||me?S[Ne]:v[Ne],this.placement,this._showCollisionBoxes,B,L,T))return;delete this._inProgressLayer}this._currentPlacementIndex--}this._done=!0}commit(u){return this.placement.commit(u),this.placement}}const _u=512/a.al/2;class Ch{constructor(u,f,v){this.tileID=u,this.bucketInstanceId=v,this.index=new a.c4(f.length,16,Int32Array),this.keys=[],this.crossTileIDs=[];const S=u.canonical.x*a.al,T=u.canonical.y*a.al;for(let E=0;Eme-fe);for(const me of se){const fe=this.crossTileIDs[me];if(this.keys[me]===G&&!v.has(fe)){v.add(fe),q.crossTileID=fe;break}}}}}class Ya{constructor(){this.maxCrossTileID=0}generate(){return++this.maxCrossTileID}}class fS{constructor(){this.indexes={},this.usedCrossTileIDs={},this.lng=0}handleWrapJump(u){const f=Math.round((u-this.lng)/360);if(f!==0)for(const v in this.indexes){const S=this.indexes[v],T={};for(const E in S){const L=S[E];L.tileID=L.tileID.unwrapTo(L.tileID.wrap+f),T[L.tileID.key]=L}this.indexes[v]=T}this.lng=u}addBucket(u,f,v){if(this.indexes[u.overscaledZ]&&this.indexes[u.overscaledZ][u.key]){if(this.indexes[u.overscaledZ][u.key].bucketInstanceId===f.bucketInstanceId)return!1;this.removeBucketCrossTileIDs(u.overscaledZ,this.indexes[u.overscaledZ][u.key])}for(let T=0;Tu.overscaledZ)for(const L in E){const B=E[L];B.tileID.isChildOf(u)&&B.findMatches(f.symbolInstances,u,S)}else{const L=E[u.scaledTo(Number(T)).key];L&&L.findMatches(f.symbolInstances,u,S)}}for(let T=0;T{f[v]=!0});for(const v in this.layerIndexes)f[v]||delete this.layerIndexes[v]}}const Md=771;class En{constructor(u,f,v,S){this.blendFunction=u,this.blendColor=f.toNonPremultipliedRenderColor(null),this.mask=v,this.blendEquation=S}}En.Replace=[1,0,1,0],En.disabled=new En(En.Replace,a.ao.transparent,[!1,!1,!1,!1]),En.unblended=new En(En.Replace,a.ao.transparent,[!0,!0,!0,!0]),En.alphaBlended=new En([1,Md,1,Md],a.ao.transparent,[!0,!0,!0,!0]),En.alphaBlendedNonPremultiplied=new En([770,Md,770,Md],a.ao.transparent,[!0,!0,!0,!0]),En.multiply=new En([774,0,774,0],a.ao.transparent,[!0,!0,!0,!0]),En.additive=new En([1,1,1,1],a.ao.transparent,[!0,!0,!0,!0]);class Wr{constructor(u,f,v){this.func=u,this.mask=f,this.range=v}}Wr.ReadOnly=!1,Wr.ReadWrite=!0,Wr.disabled=new Wr(519,Wr.ReadOnly,[0,1]);const C0=7680;class _n{constructor(u,f,v,S,T,E){this.test=u,this.ref=f,this.mask=v,this.fail=S,this.depthFail=T,this.pass=E}}_n.disabled=new _n({func:519,mask:0},0,0,C0,C0,C0);const mg=1029,k0=2305;class vn{constructor(u,f,v){this.enable=u,this.mode=f,this.frontFace=v}}function Od(x,u){const f=a.ca(x,3);a.cc(x,u),a.cg(x,3,f)}function pS(x,u){const f=a.c7([]);return a.c8(f,f,-u),a.c9(f,f,-x),f}function T0(x,u){const f=[x[0],x[1],0],v=[u[0],u[1],0];if(a.ag(f)>=1e-15){const E=a.aw([],f);a.c5(v,E,a.bJ(v,E)),u[0]=v[0],u[1]=v[1]}const S=a.bI([],u,x);if(a.c6(S)<1e-15)return null;const T=Math.atan2(-S[1],S[0]);return pS(Math.atan2(Math.sqrt(x[0]*x[0]+x[1]*x[1]),-x[2]),T)}vn.disabled=new vn(!1,mg,k0),vn.backCCW=new vn(!0,mg,k0),vn.backCW=new vn(!0,mg,2304),vn.frontCW=new vn(!0,1028,2304),vn.frontCCW=new vn(!0,1028,k0);class Ol{constructor(u,f){this.position=u,this.orientation=f}get position(){return this._position}set position(u){if(u){const f=u instanceof a.ae?u:new a.ae(u[0],u[1],u[2]);this._renderWorldCopies&&(f.x=a.bT(f.x,0,1)),this._position=f}else this._position=null}lookAtPoint(u,f,v){if(this.orientation=null,!this.position)return;const S=this.position,T=v||(this._elevation?this._elevation.getAtPointOrZero(a.ae.fromLngLat(u)):0),E=a.ae.fromLngLat(u,T),L=[E.x-S.x,E.y-S.y,E.z-S.z];f||(f=[0,0,1]),f[2]=Math.abs(f[2]),this.orientation=T0(L,f)}setPitchBearing(u,f){this.orientation=pS(a.an(u),a.an(-f))}}class E0{constructor(u,f){this._transform=a.bA([]),this.orientation=f,this.position=u}get mercatorPosition(){const u=this.position;return new a.ae(u[0],u[1],u[2])}get position(){const u=a.ca(this._transform,3);return[u[0],u[1],u[2]]}set position(u){var f;u&&a.cg(this._transform,3,[(f=u)[0],f[1],f[2],1])}get orientation(){return this._orientation}set orientation(u){this._orientation=u||a.c7([]),u&&Od(this._transform,this._orientation)}getPitchBearing(){const u=this.forward(),f=this.right();return{bearing:Math.atan2(-f[1],f[0]),pitch:Math.atan2(Math.sqrt(u[0]*u[0]+u[1]*u[1]),-u[2])}}setPitchBearing(u,f){this._orientation=pS(u,f),Od(this._transform,this._orientation)}forward(){const u=a.ca(this._transform,2);return[-u[0],-u[1],-u[2]]}up(){const u=a.ca(this._transform,1);return[-u[0],-u[1],-u[2]]}right(){const u=a.ca(this._transform,0);return[u[0],u[1],u[2]]}getCameraToWorld(u,f){const v=new Float64Array(16);return a.bl(v,this.getWorldToCamera(u,f)),v}getCameraToWorldMercator(){return this._transform}getWorldToCameraPosition(u,f,v){const S=this.position;a.c5(S,S,-u);const T=new Float64Array(16);return a.bq(T,[v,v,v]),a.br(T,T,S),T[10]*=f,T}getWorldToCamera(u,f){const v=new Float64Array(16),S=new Float64Array(4),T=this.position;return a.cb(S,this._orientation),a.c5(T,T,-u),a.cc(v,S),a.br(v,v,T),v[1]*=-1,v[5]*=-1,v[9]*=-1,v[13]*=-1,v[8]*=f,v[9]*=f,v[10]*=f,v[11]*=f,v}getCameraToClipPerspective(u,f,v,S){const T=new Float64Array(16);return a.cd(T,u,f,v,S),T}getCameraToClipOrthographic(u,f,v,S,T,E){const L=new Float64Array(16);return a.ce(L,u,f,v,S,T,E),L}getDistanceToElevation(u,f=!1){const v=u===0?0:a.cf(u,f?a.a$(this.position[1]):this.position[1]),S=this.forward();return(v-this.position[2])/S[2]}clone(){return new E0([...this.position],[...this.orientation])}}const _o={BaseColor:5,MetallicRoughness:6,Normal:7,Occlusion:8,Emission:9,LUT:10,ShadowMap0:11};class A0{constructor(u=0,f=0,v=0,S=0){if(isNaN(u)||u<0||isNaN(f)||f<0||isNaN(v)||v<0||isNaN(S)||S<0)throw new Error("Invalid value for edge-insets, top, bottom, left and right must all be numbers");this.top=u,this.bottom=f,this.left=v,this.right=S}interpolate(u,f,v){return f.top!=null&&u.top!=null&&(this.top=a.ak(u.top,f.top,v)),f.bottom!=null&&u.bottom!=null&&(this.bottom=a.ak(u.bottom,f.bottom,v)),f.left!=null&&u.left!=null&&(this.left=a.ak(u.left,f.left,v)),f.right!=null&&u.right!=null&&(this.right=a.ak(u.right,f.right,v)),this}getCenter(u,f){const v=a.aA((this.left+u-this.right)/2,0,u),S=a.aA((this.top+f-this.bottom)/2,0,f);return new a.P(v,S)}equals(u){return this.top===u.top&&this.bottom===u.bottom&&this.left===u.left&&this.right===u.right}clone(){return new A0(this.top,this.bottom,this.left,this.right)}toJSON(){return{top:this.top,bottom:this.bottom,left:this.left,right:this.right}}}const Xu=15;class mS{constructor(u,f,v,S,T,E,L){this.tileSize=512,this._renderWorldCopies=T===void 0||T,this._minZoom=u||0,this._maxZoom=f||22,this._minPitch=v??0,this._maxPitch=S??60,this.setProjection(E),this.setMaxBounds(L),this.width=0,this.height=0,this._center=new a.aT(0,0),this.zoom=0,this.angle=0,this._fov=.6435011087932844,this._pitch=0,this._nearZ=0,this._farZ=0,this._unmodified=!0,this._edgeInsets=new A0,this._projMatrixCache={},this._alignedProjMatrixCache={},this._fogTileMatrixCache={},this._expandedProjMatrixCache={},this._distanceTileDataCache={},this._camera=new E0,this._centerAltitude=0,this._averageElevation=0,this.cameraElevationReference="ground",this._pixelsPerMercatorPixel=1,this.globeRadius=0,this.globeCenterInViewSpace=[0,0,0],this._tileCoverLift=0,this.freezeTileCoverage=!1,this._horizonShift=.1,this._orthographicProjectionAtLowPitch=!1,this._allowWorldUnderZoom=!1}clone(){const u=new mS(this._minZoom,this._maxZoom,this._minPitch,this.maxPitch,this._renderWorldCopies,this.getProjection(),this.maxBounds);return u._elevation=this._elevation,u._centerAltitude=this._centerAltitude,u._centerAltitudeValidForExaggeration=this._centerAltitudeValidForExaggeration,u.tileSize=this.tileSize,u.mercatorFromTransition=this.mercatorFromTransition,u.width=this.width,u.height=this.height,u.cameraElevationReference=this.cameraElevationReference,u._center=this._center,u._setZoom(this.zoom),u._seaLevelZoom=this._seaLevelZoom,u.angle=this.angle,u._fov=this._fov,u._pitch=this._pitch,u._nearZ=this._nearZ,u._farZ=this._farZ,u._averageElevation=this._averageElevation,u._orthographicProjectionAtLowPitch=this._orthographicProjectionAtLowPitch,u._unmodified=this._unmodified,u._edgeInsets=this._edgeInsets.clone(),u._camera=this._camera.clone(),u._calcMatrices(),u.freezeTileCoverage=this.freezeTileCoverage,u.frustumCorners=this.frustumCorners,u._allowWorldUnderZoom=this._allowWorldUnderZoom,u}get isOrthographic(){return this.projection.name!=="globe"&&this._orthographicProjectionAtLowPitch&&this.pitch0&&this.elevation.exaggeration()>0&&this._centerAltitudeValidForExaggeration;if(!this._elevation||u===Number.NEGATIVE_INFINITY&&(!f||!this._centerAltitude))return this._centerAltitude=0,this._seaLevelZoom=null,void(this._centerAltitudeValidForExaggeration=void 0);const v=this._elevation;f||this._centerAltitude&&this._centerAltitudeValidForExaggeration&&v.exaggeration()&&this._centerAltitudeValidForExaggeration!==v.exaggeration()?(this._centerAltitude=this._centerAltitude/this._centerAltitudeValidForExaggeration*v.exaggeration(),this._centerAltitudeValidForExaggeration=v.exaggeration()):(this._centerAltitude=u||0,this._centerAltitudeValidForExaggeration=v.exaggeration()),this._updateSeaLevelZoom()}_updateSeaLevelZoom(){if(this._centerAltitudeValidForExaggeration===void 0)return;const u=Math.max(0,(this.pixelsPerMeter*this._centerAltitude+this.cameraToCenterDistance)/this.worldSize);this._seaLevelZoom=this._zoomFromMercatorZ(u)}sampleAverageElevation(){if(!this._elevation)return 0;const u=this._elevation,f=[[.5,.2],[.3,.5],[.5,.5],[.7,.5],[.5,.8]],v=this.horizonLineFromTop();let S=0,T=0;for(let E=0;E{const me=a.cY(J,ee,re,oe,se);B.has(me)||(T.push(new a.aQ(ee,J,re,oe,se)),B.add(me))};for(let ee=0;eeJ.canonical.z)continue;const re=J.canonical,oe=J.overscaledZ,se=J.wrap,me=1<0,Ae=re.y+10,Ze=J.wrap-(Ne?0:1),$e=J.wrap+(fe?0:1),He=Ne?re.x-1:me-1,ze=fe?re.x+1:0;if(E)v[0]<0?(q(oe,$e,re.z,ze,re.y),v[1]<0&&Ae&&(q(oe,se,re.z,re.x,re.y+1),q(oe,$e,re.z,ze,re.y+1)),v[1]>0&&Te&&(q(oe,se,re.z,re.x,re.y-1),q(oe,$e,re.z,ze,re.y-1))):v[0]>0?(q(oe,Ze,re.z,He,re.y),v[1]<0&&Ae&&(q(oe,se,re.z,re.x,re.y+1),q(oe,Ze,re.z,He,re.y+1)),v[1]>0&&Te&&(q(oe,se,re.z,re.x,re.y-1),q(oe,Ze,re.z,He,re.y-1))):v[1]<0&&Ae?q(oe,se,re.z,re.x,re.y+1):Te&&q(oe,se,re.z,re.x,re.y-1);else{const De=J.visibleQuadrants;1&De&&(q(oe,Ze,re.z,He,re.y),Te&&(q(oe,se,re.z,re.x,re.y-1),q(oe,Ze,re.z,He,re.y-1))),2&De&&(q(oe,$e,re.z,ze,re.y),Te&&(q(oe,se,re.z,re.x,re.y-1),q(oe,$e,re.z,ze,re.y-1))),4&De&&(q(oe,Ze,re.z,He,re.y),Ae&&(q(oe,se,re.z,re.x,re.y+1),q(oe,Ze,re.z,He,re.y+1))),8&De&&(q(oe,$e,re.z,ze,re.y),Ae&&(q(oe,se,re.z,re.x,re.y+1),q(oe,$e,re.z,ze,re.y+1)))}}const G=[];for(const ee of T)T.some(J=>ee.isChildOf(J))||G.push(ee);if(T=G.filter(ee=>!u.some(J=>!!(ee.overscaledZ{const fe=me.canonical.x+.5-re[0],Ne=me.canonical.y+.5-re[1];return fe*fe+Ne*Ne{const He=a.cY(Ae,Ne,Te,Ze,$e);T.has(He)||(S.push(new a.aQ(Ne,Ae,Te,Ze,$e)),T.add(He))},L=u.reduce((Ne,Ae)=>Math.max(Ne,Ae.overscaledZ),v),B=1<{const Te=Math.floor(Ne[0]),Ze=Math.floor(Ne[1]),$e=(Ne[0]-Te)*a.al,He=(Ne[1]-Ze)*a.al,ze=Math.floor(Ae[0]),De=Math.floor(Ae[1]),Qe=(Ae[0]-ze)*a.al,ht=(Ae[1]-De)*a.al;for(let ot=-1;ot<=1;ot++){const Tt=Te+ot;if(!(Tt<0||Tt>=B)){G.x=$e-ot*a.al,ee.x=Qe-(Tt-ze)*a.al;for(let At=-1;At<=1;At++){const Bt=Ze+At;G.y=He-At*a.al,ee.y=ht-(Bt-De)*a.al,a.cZ(G,ee,q)&&E(L,0,v,Tt,Bt)}}}},re=f.points,oe=re[a.cv],se=re[a.cw],me=this._projectToGround(oe,re[a.cx]),fe=this._projectToGround(se,re[a.cy]);return J(oe,me),J(se,fe),S}_projectToGround(u,f){return a.cz(a.cA(),u,f,u[2]/(u[2]-f[2]))}coveringTiles(u){let f=this.coveringZoomLevel(u);const v=f,S=this.elevation&&this.elevation.exaggeration(),T=S&&!u.isTerrainDEM,E=this.projection.name==="mercator";if(u.minzoom!==void 0&&fu.maxzoom&&(f=u.maxzoom);const L=this.locationCoordinate(this.center),B=this.center.lat,q=1<{const kt=new a.ae(st.x+25e-6,st.y,st.z),Zt=new a.ae(st.x,st.y+25e-6,st.z),yr=st.toLngLat(),Pr=kt.toLngLat(),fr=Zt.toLngLat(),lr=this.locationCoordinate(yr),Ur=this.locationCoordinate(Pr),Fr=this.locationCoordinate(fr),Tr=Math.hypot(Ur.x-lr.x,Ur.y-lr.y),Mr=Math.hypot(Fr.x-lr.x,Fr.y-lr.y);return Math.sqrt(Tr*Mr)*He/25e-6},De=st=>{const Mt=Ze,kt=$e;return{aabb:a.cF(this,q,0,0,0,st,kt,Mt,this.projection),zoom:0,x:0,y:0,minZ:kt,maxZ:Mt,wrap:st,fullyVisible:!1}},Qe=[];let ht=[];const ot=f,Tt=u.reparseOverscaled?v:f,At=(me-this._centerAltitude)*se,Bt=st=>{if(!this._elevation||!st.tileID||!E)return;const Mt=this._elevation.getMinMaxForTile(st.tileID),kt=st.aabb;Mt?(kt.min[2]=Mt.min,kt.max[2]=Mt.max,kt.center[2]=(kt.min[2]+kt.max[2])/2):(st.shouldSplit=wt(st),st.shouldSplit||(kt.min[2]=kt.max[2]=kt.center[2]=this._centerAltitude))},or=(st,Mt)=>{if(.707*Mt{if(st.zoom=.9)return!0}else if(T&&(Zt=st.aabb.distanceZ(fe)*se),this.projection.isReprojectedInTileSpace&&v<=5){const Mr=Math.pow(2,st.zoom),tn=ze(new a.ae((st.x+.5)/Mr,(st.y+.5)/Mr));yr=tn>.85?1:tn}if(!E&&!ee){const Mr=Math.sqrt(Mt*Mt+kt*kt+Zt*Zt);let tn=(1<0;){const st=Qe.pop(),Mt=st.x,kt=st.y;let Zt=st.fullyVisible;const yr=()=>this.projection.name==="globe"&&(st.y===0||st.y===(1<>1),Ur={aabb:E?st.aabb.quadrant(Pr):a.cF(this,q,st.zoom+1,fr,lr,st.wrap,st.minZ,st.maxZ,this.projection),zoom:st.zoom+1,x:fr,y:lr,wrap:st.wrap,fullyVisible:Zt,tileID:void 0,shouldSplit:void 0,minZ:st.minZ,maxZ:st.maxZ};T&&!ee&&(Ur.tileID=new a.aQ(st.zoom+1===ot?Tt:st.zoom+1,st.wrap,st.zoom+1,fr,lr),Bt(Ur)),Qe.push(Ur)}else{const Pr=st.zoom===ot?Tt:st.zoom;if(u.minzoom&&u.minzoom>Pr)continue;let fr=0;if(!Zt){let Tr=Ne?st.aabb.intersectsPrecise(re):st.aabb.intersectsPreciseFlat(re);if(Tr===0&&yr()){const Mr=new a.cD(st.zoom,Mt,kt);Tr=a.cE(this,q,Mr,!0).intersectsPrecise(re)}if(Tr===0)continue;if(u.calculateQuadrantVisibility)if(re.containsPoint(st.aabb.center))fr=15;else for(let Mr=0;Mr<4;Mr++)st.aabb.quadrant(Mr).intersects(re)!==0&&(fr|=1<{const Zt=[0,0,0,1],yr=[a.al,a.al,0,1],Pr=this.calculateFogTileMatrix(kt.tileID.toUnwrapped());a.aC(Zt,Zt,Pr),a.aC(yr,yr,Pr);const fr=a.cG([],Zt,yr),lr=a.cH([],Zt,yr),Ur=a.c$(fr,lr);if(Ur===0)return!0;let Fr=!1;const Tr=this._elevation;if(Tr&&Ur>st&&Mt!==0){const Mr=this.calculateProjMatrix(kt.tileID.toUnwrapped());let tn;u.isTerrainDEM||(tn=Tr.getMinMaxForTile(kt.tileID)),tn||(tn={min:$e,max:Ze});const Cn=a.cI(this.rotation),as=[Cn[0]*a.al,Cn[1]*a.al,tn.max];a.af(as,as,Mr),Fr=(1-as[1])*this.height*.5st.distanceSq-Mt.distanceSq).map(st=>st.tileID)}resize(u,f){this.width=u,this.height=f,this.pixelsToGLUnits=[2/u,-2/f],this._constrain(),this._calcMatrices()}get unmodified(){return this._unmodified}zoomScale(u){return Math.pow(2,u)}scaleZoom(u){return Math.log2(u)}project(u){const f=a.aA(u.lat,-a.cJ,a.cJ),v=this.projection.project(u.lng,f);return new a.P(v.x*this.worldSize,v.y*this.worldSize)}unproject(u){return this.projection.unproject(u.x/this.worldSize,u.y/this.worldSize)}get point(){return this.project(this.center)}get pointMerc(){return this.point._div(this.worldSize)}get pixelsPerMeterRatio(){return this.pixelsPerMeter/a.cf(1,this.center.lat)/this.worldSize}setLocationAtPoint(u,f){let v,S;const T=this.centerPoint;if(this.projection.name==="globe"){const L=this.worldSize;v=(f.x-T.x)/L,S=(f.y-T.y)/L}else{const L=this.pointCoordinate(f),B=this.pointCoordinate(T);v=L.x-B.x,S=L.y-B.y}const E=this.locationCoordinate(u);this.setLocation(new a.ae(E.x-v,E.y-S))}setLocation(u){this.center=this.coordinateLocation(u),this.projection.wrap&&(this.center=this.center.wrap())}locationPoint(u,f){return this.projection.locationPoint(this,u,f)}locationPoint3D(u,f){return this.projection.locationPoint(this,u,f,!0)}pointLocation(u){return this.coordinateLocation(this.pointCoordinate(u))}pointLocation3D(u,f){return this.coordinateLocation(this.pointCoordinate3D(u,f))}locationCoordinate(u,f){const v=f?a.cf(f,u.lat):void 0,S=this.projection.project(u.lng,u.lat);return new a.ae(S.x,S.y,v)}coordinateLocation(u){return this.projection.unproject(u.x,u.y)}pointRayIntersection(u,f){const v=f??this._centerAltitude,S=[u.x,u.y,0,1],T=[u.x,u.y,1,1];a.aC(S,S,this.pixelMatrixInverse),a.aC(T,T,this.pixelMatrixInverse);const E=T[3];a.cK(S,S,1/S[3]),a.cK(T,T,1/E);const L=S[2],B=T[2];return{p0:S,p1:T,t:L===B?0:(v-L)/(B-L)}}screenPointToMercatorRay(u){const f=[u.x,u.y,0,1],v=[u.x,u.y,1,1];return a.aC(f,f,this.pixelMatrixInverse),a.aC(v,v,this.pixelMatrixInverse),a.cK(f,f,1/f[3]),a.cK(v,v,1/v[3]),f[2]=a.cf(f[2],this._center.lat)*this.worldSize,v[2]=a.cf(v[2],this._center.lat)*this.worldSize,a.cK(f,f,1/this.worldSize),a.cK(v,v,1/this.worldSize),new a.ax([f[0],f[1],f[2]],a.aw([],a.av([],v,f)))}rayIntersectionCoordinate(u){const{p0:f,p1:v,t:S}=u,T=a.cf(f[2],this._center.lat),E=a.cf(v[2],this._center.lat);return new a.ae(a.ak(f[0],v[0],S)/this.worldSize,a.ak(f[1],v[1],S)/this.worldSize,a.ak(T,E,S))}pointCoordinate(u,f=this._centerAltitude){return this.projection.pointCoordinate(this,u.x,u.y,f)}pointCoordinate3D(u,f){if(!this.elevation)return this.pointCoordinate(u,f);let v=this.projection.pointCoordinate3D(this,u.x,u.y);if(v)return new a.ae(v[0],v[1],v[2]);let S=0,T=this.horizonLineFromTop();if(u.y>T)return this.pointCoordinate(u,f);const E=.02*T,L=u.clone();for(let B=0;B<10&&T-S>E;B++){L.y=a.ak(S,T,.66);const q=this.projection.pointCoordinate3D(this,L.x,L.y);q?(T=L.y,v=q):S=L.y}return v?new a.ae(v[0],v[1],v[2]):this.pointCoordinate(u)}isPointAboveHorizon(u){return this.projection.isPointAboveHorizon(this,u)}isPointOnSurface(u){if(u.y<0||u.y>this.height||u.x<0||u.x>this.width)return!1;if(this.elevation||this.zoom>=a.cL)return!this.isPointAboveHorizon(u);const f=this.pointCoordinate(u);return f.y>=0&&f.y<=1}_coordinatePoint(u,f){const v=f&&this.elevation?this.elevation.getAtPointOrZero(u,this._centerAltitude):this._centerAltitude,S=[u.x*this.worldSize,u.y*this.worldSize,v+u.toAltitude(),1];return a.aC(S,S,this.pixelMatrix),S[3]>0?new a.P(S[0]/S[3],S[1]/S[3]):new a.P(Number.MAX_VALUE,Number.MAX_VALUE)}_getBoundsNonRectangular(){const{top:u,left:f}=this._edgeInsets,v=this.height-this._edgeInsets.bottom,S=this.width-this._edgeInsets.right,T=this.pointLocation3D(new a.P(f,u)),E=this.pointLocation3D(new a.P(S,u)),L=this.pointLocation3D(new a.P(S,v)),B=this.pointLocation3D(new a.P(f,v));let q=Math.min(T.lng,E.lng,L.lng,B.lng),G=Math.max(T.lng,E.lng,L.lng,B.lng),ee=Math.min(T.lat,E.lat,L.lat,B.lat),J=Math.max(T.lat,E.lat,L.lat,B.lat);const re=Math.pow(2,-this.zoom)/16*270,oe=this.projection.name==="globe"?1:4,se=(me,fe,Ne,Ae,Te)=>{const Ze=(me+Ne)/2,$e=(fe+Ae)/2,He=new a.P(Ze,$e),{lng:ze,lat:De}=this.pointLocation3D(He),Qe=Math.max(0,q-ze,ee-De,ze-G,De-J);q=Math.min(q,ze),G=Math.max(G,ze),ee=Math.min(ee,De),J=Math.max(J,De),(Tere)&&(se(me,fe,Ze,$e,Te+1),se(Ze,$e,Ne,Ae,Te+1))};if(se(f,u,S,u,1),se(S,u,S,v,1),se(S,v,f,v,1),se(f,v,f,u,1),this.projection.name==="globe"){const[me,fe]=a.cM(this);me?(J=90,G=180,q=-180):fe&&(ee=-90,G=180,q=-180)}return new a.aI(new a.aT(q,ee),new a.aT(G,J))}_getBoundsRectangular(u,f){const{top:v,left:S}=this._edgeInsets,T=this.height-this._edgeInsets.bottom,E=this.width-this._edgeInsets.right,L=new a.P(S,v),B=new a.P(E,v),q=new a.P(E,T),G=new a.P(S,T);let ee=this.pointCoordinate(L,u),J=this.pointCoordinate(B,u);const re=this.pointCoordinate(q,f),oe=this.pointCoordinate(G,f),se=(me,fe)=>(fe.y-me.y)/(fe.x-me.x);return ee.y>1&&J.y>=0?ee=new a.ae((1-oe.y)/se(oe,ee)+oe.x,1):ee.y<0&&J.y<=1&&(ee=new a.ae(-oe.y/se(oe,ee)+oe.x,0)),J.y>1&&ee.y>=0?J=new a.ae((1-re.y)/se(re,J)+re.x,1):J.y<0&&ee.y<=1&&(J=new a.ae(-re.y/se(re,J)+re.x,0)),new a.aI().extend(this.coordinateLocation(ee)).extend(this.coordinateLocation(J)).extend(this.coordinateLocation(oe)).extend(this.coordinateLocation(re))}_getBoundsRectangularTerrain(){const u=this.elevation;if(!u.visibleDemTiles.length||u.isUsingMockSource())return this._getBoundsRectangular(0,0);const f=u.visibleDemTiles.reduce((v,S)=>{if(S.dem){const T=S.dem.tree;v.min=Math.min(v.min,T.minimums[0]),v.max=Math.max(v.max,T.maximums[0])}return v},{min:Number.MAX_VALUE,max:0});return this._getBoundsRectangular(f.min*u.exaggeration(),f.max*u.exaggeration())}getBounds(){return this.projection.name==="mercator"||this.projection.name==="equirectangular"?this._terrainEnabled()?this._getBoundsRectangularTerrain():this._getBoundsRectangular(0,0):this._getBoundsNonRectangular()}horizonLineFromTop(u=!0){const f=this.height/2/Math.tan(this._fov/2)/Math.tan(Math.max(this._pitch,.1))-this.centerOffset.y,v=this.height/2-f*(1-this._horizonShift);return u?Math.max(0,v):v}getMaxBounds(){return this.maxBounds}setMaxBounds(u){this.maxBounds=u,this.minLat=-a.cJ,this.maxLat=a.cJ,this.minLng=-180,this.maxLng=180,u&&(this.minLat=u.getSouth(),this.maxLat=u.getNorth(),this.minLng=u.getWest(),this.maxLng=u.getEast(),this.maxLngee&&(L=ee-q),ee-Gre&&(E=re-B),re-J{for(let wt=0;wt<16;wt++)Tt[wt]=a.ak(At[wt],Bt[wt],or)})(L,L,B,a.d0(this.pitch>=Xu?1:this.pitch/Xu))}else L=B;const q=a.cP([],B,E);let G=a.cP([],L,E);if(this.projection.isReprojectedInTileSpace){const De=this.locationCoordinate(this.center),Qe=a.bA([]);a.br(Qe,Qe,[De.x*this.worldSize,De.y*this.worldSize,0]),a.aB(Qe,Qe,a.cQ(this)),a.br(Qe,Qe,[-De.x*this.worldSize,-De.y*this.worldSize,0]),a.aB(G,G,Qe),a.aB(q,q,Qe),this.inverseAdjustmentMatrix=a.cR(this)}else this.inverseAdjustmentMatrix=[1,0,0,1];if(this.mercatorMatrix=a.cS([],G,[this.worldSize,this.worldSize,this.worldSize/T,1]),this.projMatrix=G,this.invProjMatrix=a.bl(new Float64Array(16),this.projMatrix),f){const De=this._camera.getCameraToClipPerspective(this._fov,this.width/this.height,this._nearZ,1/0);De[8]=2*-u.x/this.width,De[9]=2*u.y/this.height,this.expandedFarZProjMatrix=a.cP([],De,E)}else this.expandedFarZProjMatrix=this.projMatrix;const ee=a.bl([],L);this.frustumCorners=a.cT.fromInvProjectionMatrix(ee,this.horizonLineFromTop(),this.height),this.cameraFrustum=a.cB.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,0,!f);const J=new Float32Array(16);a.bA(J),a.cS(J,J,[1,-1,1]),a.cU(J,J,this._pitch),a.bB(J,J,this.angle);const re=a.cd(new Float32Array(16),this._fov,this.width/this.height,this._nearZ,this._farZ);this.starsProjMatrix=a.bz(re);const oe=(Math.PI/2-this._pitch)*(this.height/this._fov)*this._horizonShift;re[8]=2*-u.x/this.width,re[9]=2*(u.y+oe)/this.height,this.skyboxMatrix=a.aB(J,re,J);const se=this.point,me=se.x,fe=se.y,Ne=this.width%2/2,Ae=this.height%2/2,Te=Math.cos(this.angle),Ze=Math.sin(this.angle),$e=me-Math.round(me)+Te*Ne+Ze*Ae,He=fe-Math.round(fe)+Te*Ae+Ze*Ne,ze=new Float64Array(G);if(a.br(ze,ze,[$e>.5?$e-1:$e,He>.5?He-1:He,0]),this.alignedProjMatrix=ze,G=a.bC(),a.cS(G,G,[this.width/2,-this.height/2,1]),a.br(G,G,[1,-1,0]),this.labelPlaneMatrix=G,G=a.bC(),a.cS(G,G,[1,-1,1]),a.br(G,G,[-1,-1,0]),a.cS(G,G,[2/this.width,2/this.height,1]),this.glCoordMatrix=G,this.pixelMatrix=a.aB(new Float64Array(16),this.labelPlaneMatrix,q),this._calcFogMatrices(),this._distanceTileDataCache={},G=a.bl(new Float64Array(16),this.pixelMatrix),!G)throw new Error("failed to invert matrix");if(this.pixelMatrixInverse=G,this.projection.name==="globe"||this.mercatorFromTransition){this.globeMatrix=a.cV(this);const De=[this.globeMatrix[12],this.globeMatrix[13],this.globeMatrix[14]];this.globeCenterInViewSpace=a.af(De,De,E),this.globeRadius=this.worldSize/2/Math.PI-1}else this.globeMatrix=G;this._projMatrixCache={},this._alignedProjMatrixCache={},this._pixelsToTileUnitsCache={},this._expandedProjMatrixCache={}}_calcFogMatrices(){this._fogTileMatrixCache={};const u=this.cameraWorldSizeForFog,f=this.cameraPixelsPerMeter,v=this._camera.position,S=1/this.height/this._pixelsPerMercatorPixel,T=[u,u,f];a.c5(T,T,S),a.c5(v,v,-1),a.cW(v,v,T);const E=a.bC();a.br(E,E,v),a.cS(E,E,T),this.mercatorFogMatrix=E,this.worldToFogMatrix=this._camera.getWorldToCameraPosition(u,f,S)}_computeCameraPosition(u){const f=(u=u||this.pixelsPerMeter)/this.pixelsPerMeter,v=this._camera.forward(),S=this.point,T=this._mercatorZfromZoom(this._seaLevelZoom?this._seaLevelZoom:this._zoom)*f-u/this.worldSize*this._centerAltitude;return[S.x/this.worldSize-v[0]*T,S.y/this.worldSize-v[1]*T,u/this.worldSize*this._centerAltitude-v[2]*T]}_updateCameraState(){this.height&&(this._camera.setPitchBearing(this._pitch,this.angle),this._camera.position=this._computeCameraPosition())}_translateCameraConstrained(u){const f=this._maxCameraBoundsDistance()*Math.cos(this._pitch),v=this._camera.position[2],S=u[2];let T=1;this.projection.wrap&&(this.center=this.center.wrap()),S>0&&(T=Math.min((f-v)/S,1)),this._camera.position=a.bH([],this._camera.position,u,T),this._updateStateFromCamera()}_updateStateFromCamera(){const u=this._camera.position,f=this._camera.forward(),{pitch:v,bearing:S}=this._camera.getPitchBearing(),T=a.cf(this._centerAltitude,this.center.lat)*this._pixelsPerMercatorPixel,E=this._mercatorZfromZoom(this._maxZoom)*Math.cos(a.an(this._maxPitch)),L=Math.max((u[2]-T)/Math.cos(v),E),B=this._zoomFromMercatorZ(L);a.bH(u,u,f,L),this._pitch=a.aA(v,a.an(this.minPitch),a.an(this.maxPitch)),this.angle=a.bT(S,-Math.PI,Math.PI),this._setZoom(a.aA(B,this._minZoom,this._maxZoom)),this._updateSeaLevelZoom(),this._center=this.coordinateLocation(new a.ae(u[0],u[1],u[2])),this._unmodified=!1,this._constrain(),this._calcMatrices()}_worldSizeFromZoom(u){return Math.pow(2,u)*this.tileSize}_mercatorZfromZoom(u){return this.cameraToCenterDistance/this._worldSizeFromZoom(u)}_minimumHeightOverTerrain(){const u=Math.min(this._seaLevelZoom!=null?this._seaLevelZoom:this._zoom,this._maxZoom)+4;return this._mercatorZfromZoom(u)}_zoomFromMercatorZ(u){return this.scaleZoom(this.cameraToCenterDistance/(Math.max(0,u)*this.tileSize))}zoomFromMercatorZAdjusted(u){let f=0,v=a.cL,S=0,T=1/0;for(;v-f>1e-6&&v>f;){const E=f+.5*(v-f),L=this.tileSize*Math.pow(2,E),B=this.getCameraToCenterDistance(this.projection,E,L),q=this.scaleZoom(B/(Math.max(0,u)*this.tileSize)),G=Math.abs(E-q);Gq||J.y>1)return!0}return!1}isHorizonVisible(){return this.pitch+a.cX(this.fovAboveCenter)>88||this.anyCornerOffEdge(new a.P(0,0),new a.P(this.width,this.height))}zoomDeltaToMovement(u,f){const v=a.ag(a.av([],this._camera.position,u)),S=this._zoomFromMercatorZ(v)+f;return v-this._mercatorZfromZoom(S)}getCameraPoint(){if(this.projection.name==="globe"){const u=function([f,v,S],T){const E=[f,v,S,1];a.aC(E,E,T);const L=E[3]=Math.max(E[3],1e-6);return E[0]/=L,E[1]/=L,E[2]/=L,E}([this.globeMatrix[12],this.globeMatrix[13],this.globeMatrix[14]],this.pixelMatrix);return new a.P(u[0],u[1])}{const u=Math.tan(this._pitch)*(this.cameraToCenterDistance||1);return this.centerPoint.add(new a.P(0,u))}}getCameraToCenterDistance(u,f=this.zoom,v=this.worldSize){const S=a.cO(u,f,this.width,this.height,1024),T=u.pixelSpaceConversion(this.center.lat,v,S);let E=.5/Math.tan(.5*this._fov)*this.height*T;return this.isOrthographic&&(E=a.ak(1,E,a.d0(this.pitch>=Xu?1:this.pitch/Xu))),E}getWorldToCameraMatrix(){const u=this._camera.getWorldToCamera(this.worldSize,this.projection.zAxisUnit==="meters"?this.pixelsPerMeter:1);return this.projection.name==="globe"&&a.aB(u,u,this.globeMatrix),u}getFrustum(u){return a.cB.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,u,this.projection.zAxisUnit==="meters")}}const Df=(x,u)=>{if(u>0&&x.terrain&&a.w("Cutoff is currently disabled on terrain"),u<=0||x.terrain)return{shouldRenderCutoff:!1,uniformValues:{u_cutoff_params:[0,0,0,1]}};const f=x.transform,v=Math.max(Math.abs(f._zoom-(x.minCutoffZoom-1)),1),S=f.isLODDisabled(!1)?a.ah(60,45,f.pitch):a.ah(30,15,f.pitch),T=f._farZ-f._nearZ,E=u*f.height,L=((1-(B=S))*f.cameraToCenterDistance+B*(f._farZ+E))*v;var B;return{shouldRenderCutoff:S<1,uniformValues:{u_cutoff_params:[f._nearZ,f._farZ,(L-f._nearZ)/T,(L-E-f._nearZ)/T]}}},bu=2048;class Vx{constructor(u,f){this.aabb=u,this.lastCascade=f}}class o4{add(u,f){const v=this.receivers[u.key];v!==void 0?(v.aabb.min[0]=Math.min(v.aabb.min[0],f.min[0]),v.aabb.min[1]=Math.min(v.aabb.min[1],f.min[1]),v.aabb.min[2]=Math.min(v.aabb.min[2],f.min[2]),v.aabb.max[0]=Math.max(v.aabb.max[0],f.max[0]),v.aabb.max[1]=Math.max(v.aabb.max[1],f.max[1]),v.aabb.max[2]=Math.max(v.aabb.max[2],f.max[2])):this.receivers[u.key]=new Vx(f,null)}clear(){this.receivers={}}get(u){return this.receivers[u.key]}computeRequiredCascades(u,f,v){const S=a.d9.fromPoints(u.points);let T=0;for(const E in this.receivers){const L=this.receivers[E];if(!L||!S.intersectsAabb(L.aabb))continue;L.aabb.min=S.closestPoint(L.aabb.min),L.aabb.max=S.closestPoint(L.aabb.max);const B=L.aabb.getCorners();for(let q=0;q1||J[1]<-1||J[1]>1){G=!1;break}}if(L.lastCascade=q,T=Math.max(T,q),G)break}}return T+1}}class gg{constructor(u){this.painter=u,this._enabled=!1,this._shadowLayerCount=0,this._numCascadesToRender=0,this._cascades=[],this._groundShadowTiles=[],this._receivers=new o4,this._depthMode=new Wr(u.context.gl.LEQUAL,Wr.ReadWrite,[0,1]),this._uniformValues={u_light_matrix_0:new Float32Array(16),u_light_matrix_1:new Float32Array(16),u_shadow_intensity:0,u_fade_range:[0,0],u_shadow_normal_offset:[1,1,1],u_shadow_texel_size:1,u_shadow_map_resolution:1,u_shadow_direction:[0,0,1],u_shadow_bias:[36e-5,.0012,.012],u_shadowmap_0:0,u_shadowmap_1:0},this._forceDisable=!1,this.useNormalOffset=!1}destroy(){for(const u of this._cascades)u.texture.destroy(),u.framebuffer.destroy();this._cascades=[]}updateShadowParameters(u,f){const v=this.painter;if(this._enabled=!1,this._shadowLayerCount=0,this._receivers.clear(),!f||!f.properties)return;const S=f.properties.get("shadow-intensity");if(!f.shadowsEnabled()||S<=0||(this._shadowLayerCount=v.style.order.reduce((oe,se)=>{const me=v.style._mergedLayers[se];return oe+(me.hasShadowPass()&&!me.isHidden(u.zoom)?1:0)},0),this._enabled=this._shadowLayerCount>0,!this.enabled))return;const T=v.context,E=bu,L=bu;if(this._cascades.length===0||bu!==this._cascades[0].texture.size[0]){this._cascades=[];for(let oe=0;oe<2;++oe){const se=v._shadowMapDebug,me=T.gl,fe=T.createFramebuffer(E,L,se?1:0,"texture"),Ne=new a.T(T,{width:E,height:L,data:null},me.DEPTH_COMPONENT16);if(fe.depthAttachment.set(Ne.texture),se){const Ae=new a.T(T,{width:E,height:L,data:null},me.RGBA8);fe.colorAttachment0.set(Ae.texture)}this._cascades.push({framebuffer:fe,texture:Ne,matrix:[],far:0,boundingSphereRadius:0,frustum:new a.cB,scale:0})}}this.shadowDirection=Hx(f);let B=0;if(u.elevation){const oe=u.elevation,se=[1e4,-1e4];oe.visibleDemTiles.filter(me=>me.dem).forEach(me=>{const fe=me.dem.tree;se[0]=Math.min(se[0],fe.minimums[0]),se[1]=Math.max(se[1],fe.maximums[0])}),se[0]!==1e4&&(B=(se[1]-se[0])*oe.exaggeration())}const q=1.5*u.cameraToCenterDistance,G=3*q,ee=new Float64Array(16);for(let oe=0;oe=0)return{};const T=function(B,q,G){const ee=G/(1<0&&(a.d8(T[1],T[1],[S[0]*E,0,0]),a.d8(T[2],T[2],[S[0]*E,0,0])),S[1]<0?(a.d8(T[0],T[0],[0,S[1]*E,0]),a.d8(T[1],T[1],[0,S[1]*E,0])):S[1]>0&&(a.d8(T[2],T[2],[0,S[1]*E,0]),a.d8(T[3],T[3],[0,S[1]*E,0]));const L={};return L.vertices=T,L.planes=[qx(T[1],T[0],T[4]),qx(T[2],T[1],T[5]),qx(T[3],T[2],T[6]),qx(T[0],T[3],T[7])],L}addShadowReceiver(u,f,v){this._receivers.add(u,a.d9.fromTileIdAndHeight(u,f,v))}getMaxCascadeForTile(u){const f=this._receivers.get(u);return f&&f.lastCascade?f.lastCascade:0}}function qx(x,u,f){const v=a.av([],f,u),S=a.av([],x,u),T=a.bI([],v,S),E=a.ag(T);return E===0?[0,0,1,0]:(a.c5(T,T,1/E),[T[0],T[1],T[2],-a.bJ(T,u)])}function Hx(x){const u=x.properties.get("direction"),f=a.d4(u.x,u.y,u.z);f[2]=a.aA(f[2],0,75);const v=a.d6([f[0],f[1],f[2]]);return a.d5(v.x,v.y,v.z)}function kh(x,u,f){const v=u.properties.get("color-use-theme")==="none",S=u.properties.get("color"),T=u.properties.get("intensity"),E=u.properties.get("direction"),L=[E.x,E.y,E.z],B=f.properties.get("color-use-theme")==="none",q=f.properties.get("color"),G=f.properties.get("intensity"),ee=Math.max(a.bJ([0,0,1],L),0),J=[0,0,0];a.c5(J,q.toPremultipliedRenderColor(B?null:x.getLut(u.scope)).toArray01Linear().slice(0,3),G);const re=[0,0,0];return a.c5(re,S.toPremultipliedRenderColor(v?null:x.getLut(f.scope)).toArray01Linear().slice(0,3),ee*T),a.db([J[0]>0?J[0]/(J[0]+re[0]):0,J[1]>0?J[1]/(J[1]+re[1]):0,J[2]>0?J[2]/(J[2]+re[2]):0])}function Lf(x,u,f,v,S,T){const E=x.zoom,L=x.scale,B=x.worldSize,q=1/B,G=x.aspect,ee=Math.sqrt(1+G*G)*Math.tan(.5*x.fovX),J=ee*ee,re=v-f,oe=v+f;let se,me;J>re/oe?(se=v,me=v*ee):(se=.5*oe*(1+J),me=.5*Math.sqrt(re*re+2*(v*v+f*f)*J+oe*oe*J*J));const fe=x.projection.pixelsPerMeter(x.center.lat,B),Ne=x._camera.getCameraToWorldMercator(),Ae=[0,0,-se*q];a.af(Ae,Ae,Ne);let Te=me*q;const Ze=x._edgeInsets;if(!(Ze.left===0&&Ze.top===0&&Ze.right===0&&Ze.bottom===0||Ze.left===Ze.right&&Ze.top===Ze.bottom)){const Zt=x._camera.getWorldToCamera(x.worldSize,x.projection.zAxisUnit==="meters"?fe:1),yr=x._camera.getCameraToClipPerspective(x._fov,x.width/x.height,f,v);yr[8]=2*-x.centerOffset.x/x.width,yr[9]=2*x.centerOffset.y/x.height;const Pr=new Float64Array(16);a.cP(Pr,yr,Zt);const fr=new Float64Array(16);a.bl(fr,Pr);const lr=a.cB.fromInvProjectionMatrix(fr,B,E,!0);for(const Ur of lr.points){const Fr=(($e=Ur)[0]/=L,$e[1]/=L,$e[2]=a.cf($e[2],x._center.lat),$e);Te=Math.max(Te,a.c6(a.da([],Ae,Fr)))}}var $e;Te*=S/(S-1);const He=Math.acos(u[2]),ze=Math.atan2(-u[0],-u[1]),De=new E0;De.position=Ae,De.setPitchBearing(He,ze);const Qe=De.getWorldToCamera(B,fe),ht=Te*B,ot=Math.min(x._mercatorZfromZoom(17)*B*-2,-2*ht),Tt=De.getCameraToClipOrthographic(-ht,ht,-ht,ht,ot,(ht+T*fe)/u[2]),At=new Float64Array(16);a.aB(At,Tt,Qe);const Bt=a.d5(Math.floor(1e6*Ae[0])/1e6*B,Math.floor(1e6*Ae[1])/1e6*B,0),or=.5*S,wt=[0,0,0];a.af(wt,Bt,At),a.c5(wt,wt,or);const st=[Math.floor(wt[0]),Math.floor(wt[1]),Math.floor(wt[2])],Mt=[0,0,0];a.av(Mt,wt,st),a.c5(Mt,Mt,-1/or);const kt=new Float64Array(16);return a.bA(kt),a.br(kt,kt,Mt),a.aB(At,kt,At),[At,ht]}class l4 extends a.E{constructor(u){super(),this.requestManager=u,this.models={"":{}},this.modelUris={"":{}},this.modelByURL={},this.numModelsLoading={}}loadModel(u,f){return a.dc(this.requestManager.transformRequest(f,a.R.Model).url).then(v=>{if(!v)return;const S=a.dd(v),T=new a.de(u,f,void 0,void 0,S);return T.computeBoundsAndApplyParent(),T}).catch(v=>{if(v&&v.status===404)return null;this.fire(new a.y(new Error(`Could not load model ${u} from ${f}: ${v.message}`)))})}load(u,f,v={forceReload:!1}){this.models[f]||(this.models[f]={});const S=Object.keys(u),T=[],E=[];for(const L of S){const B=u[L];this.hasURLBeenRequested(B)&&!v.forceReload||(this.modelByURL[B]={modelId:L,scope:f},T.push(this.loadModel(L,B)),E.push(L)),this.models[f][L]||(this.models[f][L]={model:null,numReferences:1})}this.numModelsLoading[f]=(this.numModelsLoading[f]||0)+E.length,Promise.allSettled(T).then(L=>{for(let B=0;B{this.fire(new a.y(new Error(`Could not load models: ${L.message}`)))})}isLoaded(){for(const u in this.numModelsLoading)if(this.numModelsLoading[u]>0)return!1;return!0}hasModel(u,f,v={exactIdMatch:!1}){return!!(v.exactIdMatch?this.getModel(u,f):this.getModelByURL(this.modelUris[f][u]))}getModel(u,f){return this.models[f]||(this.models[f]={}),this.models[f][u]?this.models[f][u].model:void 0}getModelByURL(u){if(!u)return null;const f=this.modelByURL[u];return f?this.models[f.scope][f.modelId].model:null}hasModelBeenAdded(u,f){return this.models[f]&&this.models[f][u]!==void 0}getModelURIs(u){return this.modelUris[u]||{}}addModel(u,f,v){this.models[v]||(this.models[v]={}),this.modelUris[v]||(this.modelUris[v]={});const S=this.requestManager.normalizeModelURL(f);if((this.hasModel(u,v,{exactIdMatch:!0})||this.hasModelBeenAdded(u,v))&&this.modelUris[v][u]===S)this.models[v][u].numReferences++;else if(this.hasURLBeenRequested(S)){const{scope:T,modelId:E}=this.modelByURL[S];this.models[T][E].numReferences++}else this.modelUris[v][u]=S,this.load({[u]:this.modelUris[v][u]},v)}addModelURLs(u,f){this.models[f]||(this.models[f]={}),this.modelUris[f]||(this.modelUris[f]={});const v=this.modelUris[f];for(const S in u)v[S]=this.requestManager.normalizeModelURL(u[S])}reloadModels(u){this.load(this.modelUris[u],u,{forceReload:!0})}addModelsFromBucket(u,f){this.models[f]||(this.models[f]={}),this.modelUris[f]||(this.modelUris[f]={});const v={};for(const S of u)this.hasModel(S,f,{exactIdMatch:!0})||this.hasURLBeenRequested(S)?this.models[f][S].numReferences++:this.modelUris[f][S]&&!this.hasURLBeenRequested(S)?v[S]=this.modelUris[f][S]:!this.hasURLBeenRequested(S)&&a.df(S,!1)&&(this.modelUris[f][S]=this.requestManager.normalizeModelURL(S),v[S]=this.modelUris[f][S]);this.load(v,f)}hasURLBeenRequested(u){return this.modelByURL[u]!==void 0}removeModel(u,f,v=!1,S=!1){if(this.models[f]&&this.models[f][u]&&(this.models[f][u].numReferences--,this.models[f][u].numReferences===0||S)){const T=this.modelUris[f][u];v||delete this.modelUris[f][u],delete this.modelByURL[T];const E=this.models[f][u].model;if(!E)return;delete this.models[f][u],E.destroy()}}destroy(){for(const u of Object.keys(this.models))for(const f of Object.keys(this.models[u])){const v=this.models[u][f].model;delete this.models[u][f],v&&v.destroy()}this.models={"":{}},this.modelUris={"":{}},this.modelByURL={},this.numModelsLoading={}}listModels(u){return this.models[u]||(this.models[u]={}),Object.keys(this.models[u])}upload(u,f){this.models[f]||(this.models[f]={});for(const v in this.models[f])this.models[f][v].model&&this.models[f][v].model.upload(u.context)}}const gS=a.a6.colorTheme,c4=new a.a9({data:new a.aa(gS.data)});function sE(x){if(!x.metadata||!x.metadata.content_area)return;const u=a.o.devicePixelRatio,{left:f,top:v,width:S,height:T}=x.metadata.content_area,E=f*u,L=v*u;return[E,L,E+S*u,L+T*u]}function iE(x){if(x)return x.map(([u,f])=>[u*a.o.devicePixelRatio,f*a.o.devicePixelRatio])}class yS{constructor(u,f,v){this.id=u,this.scope=f,this.sourceCache=v,this.pendingRequests=new Set,this.missingRequests=new Set}addPendingRequest(u){this.missingRequests.has(u.name)||this.pendingRequests.has(u.name)||this.pendingRequests.add(u.name)}hasPendingRequests(){return this.pendingRequests.size>0}resolvePendingRequests(){const u=new Map;if(!this.sourceCache.loaded())return u;const f=this.sourceCache.getVisibleCoordinates();if(f.length===0)return u;const v=this.sourceCache.getSource();if(!(v instanceof xl))return u;const S=f.map(E=>this.sourceCache.getTile(E)),T=v.getImages(S,Array.from(this.pendingRequests));for(const[E,L]of T)u.set(a.I.from({name:E,iconsetId:this.id}),L),this.pendingRequests.delete(E);for(const E of this.pendingRequests)this.missingRequests.add(E);return this.pendingRequests.clear(),u}}const Ff=(x,u)=>Re(x,u&&u.filter(f=>f.identifier!=="source.canvas")),aE=a.aH(bs,["addLayer","removeLayer","setLights","setPaintProperty","setLayoutProperty","setLayerProperty","setSlot","setFilter","addSource","removeSource","setLayerZoomRange","setLight","setTransition","setGeoJSONSourceData","setTerrain","setFog","setSnow","setRain","setProjection","setCamera","addImport","removeImport","updateImport","addIconset","removeIconset"]),oE=a.aH(bs,["setCenter","setZoom","setBearing","setPitch"]),P0=new Set(["background","sky","slot","custom"]),zf={version:8,layers:[],sources:{}},Wx={duration:300,delay:0};class wu extends a.E{constructor(u,f={}){super(),this.map=u,this.scope=f.scope||"",this.globalId=null,this.fragments=[],this.importDepth=f.importDepth||0,this.importsCache=f.importsCache||new Map,this.resolvedImports=f.resolvedImports||new Set,this.transition=Object.assign({},Wx),this._buildingIndex=new i4(this),this.crossTileSymbolIndex=new Yu,this._mergedOrder=[],this._drapedFirstOrder=[],this._mergedLayers={},this._mergedIndoor={},this._mergedSourceCaches={},this._mergedOtherSourceCaches={},this._mergedSymbolSourceCaches={},this._clipLayerPresent=!1,this._hasAppearances=!1,this._has3DLayers=!1,this._hasCircleLayers=!1,this._hasSymbolLayers=!1,this._importedAsBasemap=!1,this._changes=f.styleChanges||new Kt,this._hasDataDrivenEmissive=!1,this.dispatcher=f.dispatcher?f.dispatcher:new a.D(a.dh(),this),f.imageManager?this.imageManager=f.imageManager:(this.imageManager=new rt(this.map._spriteFormat),this.imageManager.setEventedParent(this)),this.imageManager.addScope(this.scope),this.glyphManager=f.glyphManager?f.glyphManager:new a.di(u._requestManager,f.localFontFamily?a.dj.all:f.localIdeographFontFamily?a.dj.ideographs:a.dj.none,f.localFontFamily||f.localIdeographFontFamily),f.modelManager?this.modelManager=f.modelManager:(this.modelManager=new l4(u._requestManager),this.modelManager.setEventedParent(this)),this._layers={},this._sourceCaches={},this._otherSourceCaches={},this._symbolSourceCaches={},this._loaded=!1,this._precompileDone=!1,this._shouldPrecompile=!1,this._availableImages=[],this._availableModels={},this._order=[],this._markersNeedUpdate=!1,this.options=f.configOptions?f.configOptions:new Map,this._configDependentLayers=f.configDependentLayers?f.configDependentLayers:new Set,this._indoorDependentLayers=f.indoorDependentLayers?f.indoorDependentLayers:new Set,this._config=f.config,this._styleColorTheme={lut:null,lutLoading:!1,lutLoadingCorrelationID:0,colorTheme:null,colorThemeOverride:f.colorThemeOverride},this._styleColorThemeForScope={},this._initialConfig=f.initialConfig,this.dispatcher.broadcast("setReferrer",a.dk());const v=this;this._rtlTextPluginCallback=wu.registerForPluginStateChange(S=>{v.dispatcher.broadcast("syncRTLPluginState",{pluginStatus:S.pluginStatus,pluginURL:S.pluginURL},(T,E)=>{if(a.dl(T),E&&E.every(L=>L))for(const L in v._sourceCaches){const B=v._sourceCaches[L],q=B.getSource().type;q!=="vector"&&q!=="geojson"||B.reload()}})}),this.on("data",S=>{if(S.dataType!=="source"||S.sourceDataType!=="metadata")return;const T=this.getOwnSource(S.sourceId);if(T&&T.vectorLayerIds)for(const E in this._layers){const L=this._layers[E];L.source===T.id&&this._validateLayer(L)}})}load(u){return u?(typeof u=="string"?this.loadURL(u):this.loadJSON(u),this):this}_getGlobalId(u){if(!u)return null;if(typeof u=="string"){if(a.h(u))return u;const f=a.dm(u);if(!f.startsWith("http"))try{return new URL(f,location.href).toString()}catch{return f}return f}return`json://${a.dn(JSON.stringify(u))}`}_diffStyle(u,f,v){this.globalId=this._getGlobalId(u);const S=(T,E)=>{try{E(null,this.setState(T,v))}catch(L){E(L,!1)}};if(typeof u=="string"){const T=this.map._requestManager.normalizeStyleURL(u),E=this.map._requestManager.transformRequest(T,a.R.Style);a.m(E,(L,B)=>{L?this.fire(new a.y(L)):B&&S(B,f)})}else typeof u=="object"&&S(u,f)}loadURL(u,f={}){this.fire(new a.z("dataloading",{dataType:"style"}));const v=typeof f.validate=="boolean"?f.validate:!a.h(u);this.globalId=this._getGlobalId(u),u=this.map._requestManager.normalizeStyleURL(u,f.accessToken),this.resolvedImports.add(u);const S=this.importsCache.get(u);if(S)return this._load(S,v);const T=this.map._requestManager.transformRequest(u,a.R.Style);this._request=a.m(T,(E,L)=>{if(this._request=null,E)this.fire(new a.y(E));else if(L)return this.importsCache.set(u,L),this._load(L,v)})}loadJSON(u,f={}){this.fire(new a.z("dataloading",{dataType:"style"})),this.globalId=this._getGlobalId(u),this._request=a.o.frame(()=>{this._request=null,this._load(u,f.validate!==!1)})}loadEmpty(){this.fire(new a.z("dataloading",{dataType:"style"})),this._load(zf,!1)}_loadImports(u,f,v){if(this.importDepth>=4)return a.w("Style doesn't support nesting deeper than 5"),Promise.resolve();const S=[];for(const T of u){const E=this._createFragmentStyle(T),L=new Promise(G=>{E.once("style.import.load",G),E.once("error",G)}).then(()=>this.mergeAll());if(S.push(L),this.resolvedImports.has(T.url)){E.loadEmpty();continue}const B=T.data||this.importsCache.get(T.url);B?(E.loadJSON(B,{validate:f}),this._isInternalStyle(B)&&(E.globalId=null)):T.url?E.loadURL(T.url,{validate:f}):E.loadEmpty();const q={style:E,id:T.id,config:T.config};if(v){const G=this.fragments.findIndex(({id:ee})=>ee===v);this.fragments=this.fragments.slice(0,G).concat(q).concat(this.fragments.slice(G))}else this.fragments.push(q)}return Promise.allSettled(S)}getImportGlobalIds(u=this,f=new Set){for(const v of u.fragments)v.style.globalId&&f.add(v.style.globalId),this.getImportGlobalIds(v.style,f);return[...f.values()]}_createFragmentStyle(u){const f=this.scope?a.B(u.id,this.scope):u.id;let v;const S=this._initialConfig&&this._initialConfig[f];(u.config||S)&&(v=Object.assign({},u.config,S));const T=new wu(this.map,{scope:f,styleChanges:this._changes,importDepth:this.importDepth+1,importsCache:this.importsCache,resolvedImports:new Set(this.resolvedImports),dispatcher:this.dispatcher,imageManager:this.imageManager,glyphManager:this.glyphManager,modelManager:this.modelManager,config:v,configOptions:this.options,colorThemeOverride:u["color-theme"],configDependentLayers:this._configDependentLayers,indoorDependentLayers:this._indoorDependentLayers});return T.setEventedParent(this.map,{style:T}),T}_reloadImports(){this.mergeAll(),this._updateMapProjection(),this.updateConfigDependencies(),this._updateLayers(this._indoorDependentLayers),this.map._triggerCameraUpdate(this.camera),this.dispatcher.broadcast("setLayers",{layers:this._serializeLayers(this._order),scope:this.scope,options:this.options}),this._shouldPrecompile=this.map._precompilePrograms&&this.isRootStyle()}_isInternalStyle(u){return this.isRootStyle()&&(u.fragment||!!u.schema&&u.fragment!==!1)}_load(u,f){if(this._isInternalStyle(u)){const T=Object.assign({},zf,{imports:[{id:"basemap",data:u,url:""}]},u.center?{center:u.center}:{},u.bearing?{bearing:u.bearing}:{},u.pitch?{pitch:u.pitch}:{},u.zoom?{zoom:u.zoom}:{},u.light?{light:u.light}:{});return this._importedAsBasemap=!0,void this._load(T,f)}if(this.updateConfig(this._config,u.schema),f&&Ff(this,ki(u)))return;this._loaded=!0,this.stylesheet=a.dp(u);const v=()=>{for(const B in u.sources)this.addSource(B,u.sources[B],{validate:!1,isInitialLoad:!0});if(u.iconsets)for(const B in u.iconsets)this.addIconset(B,u.iconsets[B]);u.sprite?this._loadIconset(u.sprite):(this.imageManager.setLoaded(!0,this.scope),this.dispatcher.broadcast("spriteLoaded",{scope:this.scope,isLoaded:!0})),!this.glyphManager.url&&u.glyphs&&this.glyphManager.setURL(u.glyphs);const T=Ox(this.stylesheet.layers);if(this._order=T.map(B=>B.id),this.stylesheet.light&&a.w("The `light` root property is deprecated, prefer using `lights` with `flat` light type instead."),this.stylesheet.lights)if(this.stylesheet.lights.length===1&&this.stylesheet.lights[0].type==="flat"){const B=this.stylesheet.lights[0];this.light=new lt(B.properties,B.id)}else this.setLights(this.stylesheet.lights);this.light||(this.light=new lt(this.stylesheet.light)),this._layers={};for(const B of T){const q=a.du(B,this.scope,this._styleColorTheme.lut,this.options);q.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(q.fqid),q.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(q.fqid),this._hasAppearances=this._hasAppearances||q.getAppearances().length!==0,q.setEventedParent(this,{layer:{id:q.id}}),this._layers[q.id]=q;const G=this.getOwnLayerSourceCache(q),ee=!!this.directionalLight&&this.directionalLight.shadowsEnabled();G&&q.canCastShadows()&&ee&&(G.castsShadows=!0)}this.stylesheet.featuresets&&this.setFeaturesetSelectors(this.stylesheet.featuresets),this.stylesheet.models&&this.addModelURLs(this.stylesheet.models);const E=this.stylesheet.terrain;E&&(this.checkCanvasFingerprintNoise(),this.disableElevatedTerrain||this.terrainSetForDrapingOnly()||this._createTerrain(E,1)),this.stylesheet.fog&&this._createFog(this.stylesheet.fog),this.stylesheet.snow&&this._createSnow(this.stylesheet.snow),this.stylesheet.rain&&this._createRain(this.stylesheet.rain),this.stylesheet.transition&&this.setTransition(this.stylesheet.transition),this.fire(new a.z("data",{dataType:"style"}));const L=this.isRootStyle();u.imports?this._loadImports(u.imports,f).then(()=>{this._reloadImports(),this.fire(new a.z(L?"style.load":"style.import.load"))}).catch(B=>{this.fire(new a.y(new Error("Failed to load imports",B))),this.fire(new a.z(L?"style.load":"style.import.load"))}):(this._reloadImports(),this.fire(new a.z(L?"style.load":"style.import.load")))};this._styleColorTheme.colorTheme=this.stylesheet["color-theme"];const S=this._styleColorTheme.colorThemeOverride?this._styleColorTheme.colorThemeOverride:this._styleColorTheme.colorTheme;if(S){const T=this._evaluateColorThemeData(S);this._loadColorTheme(T).then(()=>{v()}).catch(E=>{a.w(`Couldn't load color theme from the stylesheet: ${E}`),v()})}else this._styleColorTheme.lut=null,v()}isRootStyle(){return this.importDepth===0}hasAppearances(){return this._hasAppearances||this.fragments.some(u=>u.style.hasAppearances())}mergeAll(){let u,f,v,S,T,E,L,B,q,G;const ee={};this.terrain&&this.terrain.scope!==this.scope&&delete this.terrain,this.forEachFragmentStyle(J=>{if(J.stylesheet){if(J.light!=null&&(u=J.light),J.stylesheet.lights)for(const re of J.stylesheet.lights)re.type==="ambient"&&J.ambientLight!=null&&(f=J.ambientLight),re.type==="directional"&&J.directionalLight!=null&&(v=J.directionalLight);S=this._prioritizeTerrain(S,J.terrain,J.stylesheet.terrain),J.stylesheet.fog&&J.fog!=null&&(T=J.fog),J.stylesheet.snow&&J.snow!=null&&(E=J.snow),J.stylesheet.rain&&J.rain!=null&&(L=J.rain),J.stylesheet.camera!=null&&(G=J.stylesheet.camera),J.stylesheet.projection!=null&&(B=J.stylesheet.projection),J.stylesheet.transition!=null&&(q=J.stylesheet.transition),ee[J.scope]=J._styleColorTheme}}),this.light=u,this.ambientLight=f,this.directionalLight=v,this.fog=T,this.snow=E,this.rain=L,this._styleColorThemeForScope=ee,S===null?delete this.terrain:this.terrain=S,this.camera=G||{"camera-projection":"perspective"},this.projection=B||{name:"mercator"},this.transition=Object.assign({},Wx,q),this.mergeSources(),this.mergeLayers(),this.mergeIndoor()}forEachFragmentStyle(u){const f=v=>{for(const S of v.fragments)f(S.style);u(v)};f(this)}_prioritizeTerrain(u,f,v){const S=u&&u.drapeRenderMode===0;return v===null?f&&f.drapeRenderMode===0?f:S?u:null:f!=null&&(!u||S||f&&f.drapeRenderMode===1)?f:u}mergeTerrain(){let u;this.terrain&&this.terrain.scope!==this.scope&&delete this.terrain,this.forEachFragmentStyle(f=>{u=this._prioritizeTerrain(u,f.terrain,f.stylesheet.terrain)}),u===null?delete this.terrain:this.terrain=u}mergeProjection(){let u;this.forEachFragmentStyle(f=>{f.stylesheet.projection!=null&&(u=f.stylesheet.projection)}),this.projection=u||{name:"mercator"}}mergeSources(){const u={},f={},v={};this.forEachFragmentStyle(S=>{for(const T in S._sourceCaches){const E=a.B(T,S.scope);u[E]=S._sourceCaches[T]}for(const T in S._otherSourceCaches){const E=a.B(T,S.scope);f[E]=S._otherSourceCaches[T]}for(const T in S._symbolSourceCaches){const E=a.B(T,S.scope);v[E]=S._symbolSourceCaches[T]}}),this._mergedSourceCaches=u,this._mergedOtherSourceCaches=f,this._mergedSymbolSourceCaches=v}mergeIndoor(){this.forEachFragmentStyle(u=>{if(u.stylesheet&&u.stylesheet.indoor)for(const f of Object.values(u.stylesheet.indoor)){const v=f,S=a.B(v.sourceId,u.scope);this._mergedIndoor[S]=new Set(v.sourceLayers||[])}})}mergeLayers(){const u={},f=[],v={};this._mergedSlots=[],this._has3DLayers=!1,this._hasCircleLayers=!1,this._hasSymbolLayers=!1,this.forEachFragmentStyle(E=>{for(const L of E._order){const B=E._layers[L];if(B.type==="slot"){const q=a.dq(L);if(u[q])continue;u[q]=[]}B.slot&&u[B.slot]?u[B.slot].push(B):f.push(B)}}),this._mergedOrder=[];let S=-1;const T=(E=[])=>{for(const L of E)if(L.type==="slot"){const B=a.dq(L.id);u[B]&&T(u[B]),this._mergedSlots.push(B)}else{const B=a.B(L.id,L.scope);this._mergedOrder.push(B),v[B]=L,L.is3D(!!this.terrain)&&(this._has3DLayers=!0,S=this._mergedOrder.length-1),L.type==="circle"&&(this._hasCircleLayers=!0),L.type==="symbol"&&(this._hasSymbolLayers=!0),L.type==="clip"&&(this._clipLayerPresent=!0)}};if(T(f),this._has3DLayers){const E={};for(let L=0;LE[L]-E[B])}this._mergedLayers=v,this.updateDrapeFirstLayers(),this._buildingIndex.processLayersChanged(),this._updateDataDrivenEmissiveStrength()}terrainSetForDrapingOnly(){return!!this.terrain&&this.terrain.drapeRenderMode===0}getCamera(){return this.stylesheet.camera}setCamera(u){return this.stylesheet.camera=Object.assign({},this.stylesheet.camera,u),this.camera=this.stylesheet.camera,this}_evaluateColorThemeData(u){return u.data?function(f,v,S,T){const E=Object.assign({},v);for(const B of Object.keys(gS))E[B]===void 0&&(E[B]=gS[B].default);const L=new a.a8(c4,f,new Map(S));return L.setTransitionOrValue(E,S),L.untransitioned().possiblyEvaluate(new a.ac(0,{worldview:void 0}))}(this.scope,u,this.options).get("data"):null}_loadColorTheme(u){this._styleColorTheme.lutLoading=!0,this._styleColorTheme.lutLoadingCorrelationID+=1;const f=this._styleColorTheme.lutLoadingCorrelationID;return new Promise((v,S)=>{const T="data:image/png;base64,";if(!u||u.length===0)return this._styleColorTheme.lut=null,this._styleColorTheme.lutLoading=!1,void v();let E=u;E.startsWith(T)||(E=T+E);const L=a.I.from("mapbox-reserved-lut"),B=new Image;B.src=E,B.onerror=()=>{this._styleColorTheme.lutLoading=!1,S(new Error("Failed to load image data"))},B.onload=()=>{if(this._styleColorTheme.lutLoadingCorrelationID!==f)return void v();this._styleColorTheme.lutLoading=!1;const{width:q,height:G,data:ee}=a.o.getImageData(B);if(G>32)return void S(new Error("The height of the image must be less than or equal to 32 pixels."));if(q!==G*G)return void S(new Error("The width of the image must be equal to the height squared."));this.getImage(L)&&this.removeImage(L),this.addImage(L,{data:new a.q({width:q,height:G},ee),pixelRatio:1,sdf:!1,usvg:!1,version:0});const J=this.imageManager.getImage(L,this.scope);J?(this._styleColorTheme.lut={image:J.data,data:u},v()):S(new Error("Missing LUT image."))}})}getLut(u){const f=this._styleColorThemeForScope[u];return f?f.lut:null}setProjection(u){u?this.stylesheet.projection=u:delete this.stylesheet.projection,this.mergeProjection(),this._updateMapProjection()}applyProjectionUpdate(){this._loaded&&(this.dispatcher.broadcast("setProjection",this.map.transform.projectionOptions),this.map.transform.projection.requiresDraping?(this.getTerrain()||this.stylesheet.terrain)&&!this.disableElevatedTerrain||this.setTerrainForDraping():this.terrainSetForDrapingOnly()&&this.setTerrain(null,0))}_updateMapProjection(){this.isRootStyle()&&(this.map._useExplicitProjection?this.applyProjectionUpdate():this.map._prioritizeAndUpdateProjection(null,this.projection))}_loadSprite(u){this._spriteRequest=function(f,v,S){let T,E,L;const B=a.o.devicePixelRatio>1?"@2x":"";let q=a.m(v.transformRequest(v.normalizeSpriteURL(f,B,".json"),a.R.SpriteJSON),(J,re)=>{q=null,L||(L=J,T=re,ee())}),G=a.n(v.transformRequest(v.normalizeSpriteURL(f,B,".png"),a.R.SpriteImage),(J,re)=>{G=null,L||(L=J,E=re,ee())});function ee(){if(L)S(L);else if(T&&E){const J=a.o.getImageData(E),re={};for(const oe in T){const{width:se,height:me,x:fe,y:Ne,sdf:Ae,pixelRatio:Te,stretchX:Ze,stretchY:$e,content:He}=T[oe],ze=new a.q({width:se,height:me});a.q.copy(J,ze,{x:fe,y:Ne},{x:0,y:0},{width:se,height:me},null),re[oe]={data:ze,pixelRatio:Te!==void 0?Te:1,sdf:Ae!==void 0&&Ae,stretchX:Ze,stretchY:$e,content:He,usvg:!1,version:0}}S(null,re)}}return{cancel(){q&&(q.cancel(),q=null),G&&(G.cancel(),G=null)}}}(u,this.map._requestManager,(f,v)=>{if(this._spriteRequest=null,f)this.fire(new a.y(f));else if(v){const S=new Map;for(const T in v)S.set(a.I.from(T),v[T]);this.addImages(S)}this.imageManager.setLoaded(!0,this.scope),this.dispatcher.broadcast("spriteLoaded",{scope:this.scope,isLoaded:!0}),this.fire(new a.z("data",{dataType:"style"}))})}addIconset(u,f){if(f.type==="sprite")return void this._loadSprite(f.url);const v=this.getOwnSourceCache(f.source);if(!v)return void this.fire(new a.y(new Error(`Source "${f.source}" as specified by iconset "${u}" does not exist and cannot be used as an iconset source`)));const S=v.getSource();if(S.type!=="raster-array")return void this.fire(new a.y(new Error(`Source "${f.source}" as specified by iconset "${u}" is not a "raster-array" source and cannot be used as an iconset source`)));S.partial=!1;const T=new yS(u,this.scope,v);this.imageManager.addImageProvider(T,this.scope)}removeIconset(u){this.imageManager.removeImageProvider(u,this.scope)}_loadIconset(u){if(!a.h(u)&&this.map._spriteFormat!=="icon_set"||this.map._spriteFormat==="raster")return void this._loadSprite(u);const f=this.map._spriteFormat==="auto";var v,S;this._spriteRequest=(S=(T,E)=>{if(this._spriteRequest=null,T)f?this._loadSprite(u):this.fire(new a.y(T));else if(E){const L=new Map;for(const B in E)L.set(a.I.from(B),E[B]);this.addImages(L)}this.imageManager.setLoaded(!0,this.scope),this.dispatcher.broadcast("spriteLoaded",{scope:this.scope,isLoaded:!0}),this.fire(new a.z("data",{dataType:"style"}))},a.bu((v=this.map._requestManager).transformRequest(v.normalizeIconsetURL(u),a.R.Iconset),(T,E)=>{if(T)return void S(T);const L={},B=a.dg(new a.bt(E));for(const q of B.icons){const G={version:1,pixelRatio:a.o.devicePixelRatio,content:sE(q),stretchX:q.metadata?iE(q.metadata.stretch_x_areas):void 0,stretchY:q.metadata?iE(q.metadata.stretch_y_areas):void 0,sdf:!1,usvg:!0,icon:q};L[q.name]=G}S(null,L)}))}_validateLayer(u){const f=this.getOwnSource(u.source);if(!f)return;const v=u.sourceLayer;v&&(f.type==="geojson"||f.vectorLayerIds&&f.vectorLayerIds.indexOf(v)===-1)&&this.fire(new a.y(new Error(`Source layer "${v}" does not exist on source "${f.id}" as specified by style layer "${u.id}"`)))}loaded(){if(!this._loaded||Object.keys(this._changes.getUpdatedSourceCaches()).length)return!1;for(const u in this._sourceCaches)if(!this._sourceCaches[u].loaded())return!1;if(!this.imageManager.isLoaded()||this.imageManager.hasPatternsInFlight()||!this.modelManager.isLoaded()||this._styleColorTheme.lutLoading)return!1;for(const{style:u}of this.fragments)if(!u.loaded())return!1;return!0}_serializeImports(){if(this.stylesheet.imports)return this.stylesheet.imports.map((u,f)=>{const v=this.fragments[f];return v&&v.style&&(u.data=v.style.serialize()),u})}_serializeSources(){const u={};for(const f in this._sourceCaches){const v=this._sourceCaches[f].getSource();u[v.id]||(u[v.id]=v.serialize())}return u}_serializeLayers(u){const f=[];for(const v of u){const S=this._layers[v];S&&S.type!=="custom"&&f.push(S.serialize())}return f}hasLightTransitions(){return!(!this.light||!this.light.hasTransition())||!(!this.ambientLight||!this.ambientLight.hasTransition())||!(!this.directionalLight||!this.directionalLight.hasTransition())}hasFogTransition(){return!!this.fog&&this.fog.hasTransition()}hasSnowTransition(){return!!this.snow&&this.snow.hasTransition()}hasRainTransition(){return!!this.rain&&this.rain.hasTransition()}hasTransitions(){if(this.hasLightTransitions()||this.hasFogTransition()||this.hasSnowTransition()||this.hasRainTransition())return!0;for(const u in this._sourceCaches)if(this._sourceCaches[u].hasTransition())return!0;for(const u in this._layers)if(this._layers[u].hasTransition())return!0;return!1}_updateDataDrivenEmissiveStrength(){for(const u in this._mergedLayers){const f=this._mergedLayers[u];if(f._transitionablePaint&&f._transitionablePaint._values){const v=f._transitionablePaint._values["line-emissive-strength"];if(v&&v.value&&v.value.isDataDriven())return void(this._hasDataDrivenEmissive=!0)}}this._hasDataDrivenEmissive=!1}hasDataDrivenEmissiveStrength(){return this._hasDataDrivenEmissive}get order(){return this.terrain?this._drapedFirstOrder:this._mergedOrder}_getOrder(u){return u?this.order:this._mergedOrder}isLayerDraped(u){return!!this.terrain&&u.isDraped(this.getLayerSourceCache(u))}_checkLoaded(){if(!this._loaded)throw new Error("Style is not done loading")}_checkLayer(u){const f=this.getOwnLayer(u);if(f)return f;this.fire(new a.y(new Error(`The layer '${u}' does not exist in the map's style.`)))}_checkSource(u){const f=this.getOwnSource(u);if(f)return f;this.fire(new a.y(new Error(`The source '${u}' does not exist in the map's style.`)))}precompilePrograms(u,f){const v=this.map.painter;if(v)for(let S=u.minzoom||0;S<(u.maxzoom||25.5);S++){const T=u.getProgramIds();if(T)for(const E of T){const L=u.getDefaultProgramParams(E,f.zoom,this._styleColorTheme.lut);L&&(v.style=this,this.fog&&(v._fogVisible=!0,L.overrideFog=!0,v.getOrCreateProgram(E,L)),v._fogVisible=!1,L.overrideFog=!1,v.getOrCreateProgram(E,L),(this.stylesheet.terrain||this.stylesheet.projection&&this.stylesheet.projection.name==="globe")&&(L.overrideRtt=!0,v.getOrCreateProgram(E,L)))}}}update(u){if(!this._loaded)return;this.ambientLight&&this.ambientLight.recalculate(u),this.directionalLight&&this.directionalLight.recalculate(u);const f=this.calculateLightsBrightness();u.brightness=f||0,f!==this._brightness&&(this._brightness=f,this.dispatcher.broadcast("setBrightness",f)),u.worldview!==this._worldview&&(this._worldview=u.worldview,this.dispatcher.broadcast("setWorldview",this._worldview));const v=this._changes.isDirty();let S=!1;if(this._changes.isDirty()){const L=this._changes.getLayerUpdatesByScope();for(const B in L){const{updatedIds:q,removedIds:G}=L[B];(q||G)&&(this._updateWorkerLayers(B,q,G),S=!0)}this.updateSourceCaches(),this._updateTilesForChangedImages(),this.updateLayers(u),this.light&&this.light.updateTransitions(u),this.ambientLight&&this.ambientLight.updateTransitions(u),this.directionalLight&&this.directionalLight.updateTransitions(u),this.fog&&this.fog.updateTransitions(u),this.snow&&this.snow.updateTransitions(u),this.rain&&this.rain.updateTransitions(u),this._changes.reset()}const T={};for(const L in this._mergedSourceCaches){const B=this._mergedSourceCaches[L];T[L]=B.used,B.used=!1,B.tileCoverLift=0}for(const L of this._mergedOrder){const B=this._mergedLayers[L];if(B.visibility!=="none"&&B.recalculate(u,this._availableImages),!B.isHidden(u.zoom)){const q=this.getLayerSourceCache(B);q&&(q.used=!0,q.tileCoverLift=Math.max(q.tileCoverLift,B.tileCoverLift()))}!this._precompileDone&&this._shouldPrecompile&&("requestIdleCallback"in window?requestIdleCallback(()=>{this.precompilePrograms(B,u)}):this.precompilePrograms(B,u))}this._shouldPrecompile&&(this._precompileDone=!0),this.terrain&&S&&this.mergeLayers();const E=this.imageManager.getPendingImageProviders();for(const L of E)L.sourceCache.used=!0;for(const L in T){const B=this._mergedSourceCaches[L];T[L]!==B.used&&B.getSource().fire(new a.z("data",{sourceDataType:"visibility",dataType:"source",sourceId:B.getSource().id}))}this.light&&this.light.recalculate(u),this.terrain&&this.terrain.recalculate(u),this.fog&&this.fog.recalculate(u),this.snow&&this.snow.recalculate(u),this.rain&&this.rain.recalculate(u),this.z=u.zoom,this._markersNeedUpdate&&(this._updateMarkersOpacity(),this._markersNeedUpdate=!1),this.imageManager.clearUpdatedImages(this.scope),v&&this.fire(new a.z("data",{dataType:"style"}))}updateImageProviders(){const u=this.imageManager.getPendingImageProviders();for(const f of u){const v=f.resolvePendingRequests(),S=this.getFragmentStyle(f.scope);S&&S.addImages(v)}}_updateTilesForChangedImages(){const u={};for(const f in this._mergedSourceCaches){const v=this._mergedSourceCaches[f].getSource().scope;u[v]=u[v]||this._changes.getUpdatedImages(v),u[v].length!==0&&this._mergedSourceCaches[f].reloadTilesForDependencies(["icons","patterns"],u[v])}for(const f in u)this._changes.resetUpdatedImages(f)}_updateWorkerLayers(u,f,v){const S=this.getFragmentStyle(u);S&&this.dispatcher.broadcast("updateLayers",{layers:f?S._serializeLayers(f):[],scope:u,removedIds:v||[],options:S.options})}setState(u,f){if(this._checkLoaded(),Ff(this,ki(u)))return!1;(u=a.dp(u)).layers=Ox(u.layers);const v=function(E,L){if(!E)return[{command:bs.setStyle,args:[L]}];let B=[];try{if(!a.by(E.version,L.version))return[{command:bs.setStyle,args:[L]}];if(a.by(E.center,L.center)||B.push({command:bs.setCenter,args:[L.center]}),a.by(E.zoom,L.zoom)||B.push({command:bs.setZoom,args:[L.zoom]}),a.by(E.bearing,L.bearing)||B.push({command:bs.setBearing,args:[L.bearing]}),a.by(E.pitch,L.pitch)||B.push({command:bs.setPitch,args:[L.pitch]}),a.by(E.sprite,L.sprite)||B.push({command:bs.setSprite,args:[L.sprite]}),a.by(E.glyphs,L.glyphs)||B.push({command:bs.setGlyphs,args:[L.glyphs]}),a.by(E.imports,L.imports)||function(re=[],oe=[],se){oe=oe||[];const me=(re=re||[]).map(Rx),fe=oe.map(Rx),Ne=re.reduce(Dx,{}),Ae=oe.reduce(Dx,{}),Te=me.slice();let Ze,$e,He,ze;for(Ze=0,$e=0;Ze{re.source&&q[re.source]?B.push({command:bs.removeLayer,args:[re.id]}):ee.push(re)});let J=E.terrain;J&&q[J.source]&&(B.push({command:bs.setTerrain,args:[void 0]}),J=void 0),B=B.concat(G),a.by(J,L.terrain)||B.push({command:bs.setTerrain,args:[L.terrain]}),function(re,oe,se){oe=oe||[];const me=(re=re||[]).map(Rx),fe=oe.map(Rx),Ne=re.reduce(Dx,{}),Ae=oe.reduce(Dx,{}),Te=me.slice(),Ze=Object.create(null);let $e,He,ze,De,Qe,ht,ot;for($e=0,He=0;$e!(E.command in oE));if(v.length===0)return!1;const S=v.filter(E=>!(E.command in aE));if(S.length>0)throw new Error(`Unimplemented: ${S.map(E=>E.command).join(", ")}.`);const T=[];return v.forEach(E=>{T.push(this[E.command](...E.args))}),f&&Promise.all(T).then(f).catch(f),this.stylesheet=u,this.mergeAll(),this.dispatcher.broadcast("setLayers",{layers:this._serializeLayers(this._order),scope:this.scope,options:this.options}),!0}_updateWorkerImages(){this._availableImages=this.imageManager.listImages(this.scope),this.dispatcher.broadcast("setImages",{scope:this.scope,images:this._availableImages})}_updateWorkerModels(){this._availableModels=this.modelManager.getModelURIs(this.scope),this.dispatcher.broadcast("setModels",{scope:this.scope,models:this._availableModels})}addImages(u){if(u.size===0)return this;for(const[f,v]of u.entries()){if(this.getImage(f))return this.fire(new a.y(new Error(`An image with the name "${f.name}" already exists.`)));this.imageManager.addImage(f,this.scope,v),this._changes.updateImage(f,this.scope)}return this._updateWorkerImages(),this.fire(new a.z("data",{dataType:"style"})),this}addImage(u,f){return this.getImage(u)?this.fire(new a.y(new Error(`An image with the name "${u.name}" already exists.`))):(this.imageManager.addImage(u,this.scope,f),this._changes.updateImage(u,this.scope),this._updateWorkerImages(),this.fire(new a.z("data",{dataType:"style"})),this)}updateImage(u,f,v=!1){this.imageManager.updateImage(u,this.scope,f),v&&(this._changes.updateImage(u,this.scope),this._updateWorkerImages(),this.fire(new a.z("data",{dataType:"style"})))}getImage(u){return this.imageManager.getImage(u,this.scope)}removeImage(u){return this.getImage(u)?(this.imageManager.removeImage(u,this.scope),this._changes.updateImage(u,this.scope),this._updateWorkerImages(),this.fire(new a.z("data",{dataType:"style"})),this):this.fire(new a.y(new Error("No image with this name exists.")))}listImages(){return this._checkLoaded(),this._availableImages.slice()}getActualScope(){return this._importedAsBasemap?"basemap":this.scope}addModelURLs(u){return this.modelManager.addModelURLs(u,this.getActualScope()),this._updateWorkerModels(),this.fire(new a.z("data",{dataType:"style"})),this}addModel(u,f,v={}){return this._checkLoaded(),this._validate(ue,`models.${u}`,f,null,v)||(this.modelManager.addModel(u,f,this.getActualScope()),this.fire(new a.z("data",{dataType:"style"}))),this}hasModel(u){return this.modelManager.hasModel(u,this.getActualScope())}removeModel(u){return this.hasModel(u)?(this.modelManager.removeModel(u,this.getActualScope(),!1,!0),this.fire(new a.z("data",{dataType:"style"})),this):this.fire(new a.y(new Error("No model with this ID exists.")))}listModels(){return this._checkLoaded(),this.modelManager.listModels(this.getActualScope())}addSource(u,f,v={}){if(this._checkLoaded(),this.getOwnSource(u)!==void 0)throw new Error(`There is already a source with ID "${u}".`);if(!f.type)throw new Error(`The type property must be defined, but only the following properties were given: ${Object.keys(f).join(", ")}.`);if(["vector","raster","geojson","video","image"].indexOf(f.type)>=0&&this._validate(yo,`sources.${u}`,f,null,v))return;this.map&&this.map._collectResourceTiming&&(f.collectResourceTiming=!0);const S=lo(u,f,this.dispatcher,this);S.scope=this.scope,S.setEventedParent(this,()=>({isSourceLoaded:this._isSourceCacheLoaded(S.id),source:S.serialize(),sourceId:S.id}));const T=E=>{const L=(E?"symbol:":"other:")+S.id,B=a.B(L,this.scope),q=this._sourceCaches[L]=new jc(B,S,E);(E?this._symbolSourceCaches:this._otherSourceCaches)[S.id]=q,q.onAdd(this.map)};T(!1),f.type!=="vector"&&f.type!=="geojson"||T(!0),S.onAdd&&S.onAdd(this.map),v.isInitialLoad||(this.mergeSources(),this._changes.setDirty())}removeSource(u){this._checkLoaded();const f=this.getOwnSource(u);if(!f)throw new Error("There is no source with this ID");for(const S in this._layers)if(this._layers[S].source===u)return this.fire(new a.y(new Error(`Source "${u}" cannot be removed while layer "${S}" is using it.`)));if(this.terrain&&this.terrain.scope===this.scope&&this.terrain.get().source===u)return this.fire(new a.y(new Error(`Source "${u}" cannot be removed while terrain is using it.`)));if(this.stylesheet.iconsets){const S=Object.entries(this.stylesheet.iconsets).find(([T,E])=>E.type==="source"&&E.source===u);if(S)return this.fire(new a.y(new Error(`Source "${u}" cannot be removed while iconset "${S[0]}" is using it.`)))}const v=this.getOwnSourceCaches(u);for(const S of v){const T=a.dq(S.id);delete this._sourceCaches[T],this._changes.discardSourceCacheUpdate(S.id),S.fire(new a.z("data",{sourceDataType:"metadata",dataType:"source",sourceId:S.getSource().id})),S.setEventedParent(null),S.clearTiles()}return delete this._otherSourceCaches[u],delete this._symbolSourceCaches[u],this.mergeSources(),f.setEventedParent(null),f.onRemove&&f.onRemove(this.map),this._changes.setDirty(),this}setGeoJSONSourceData(u,f){this._checkLoaded(),this.getOwnSource(u).setData(f),this._changes.setDirty()}getOwnSource(u){const f=this.getOwnSourceCache(u);return f&&f.getSource()}getOwnSources(){const u=[];for(const f in this._otherSourceCaches){const v=this.getOwnSourceCache(f);v&&u.push(v.getSource())}return u}areTilesLoaded(){const u=this._mergedSourceCaches;for(const f in u){const v=u[f]._tiles;for(const S in v){const T=v[S];if(T.state!=="loaded"&&T.state!=="errored")return!1}}return!0}setLights(u){if(this._checkLoaded(),!u)return delete this.ambientLight,void delete this.directionalLight;const f=this._getTransitionParameters();for(const T of u){if(this._validate(xo,"lights",T))return;switch(T.type){case"ambient":if(this.ambientLight){const E=this.ambientLight;E.set(T),E.updateTransitions(f)}else this.ambientLight=new _s(T,Mi||(Mi=new a.a9({color:new a.aa(a.a6.properties_light_ambient.color),"color-use-theme":new a.aa({type:"string",default:"default","property-type":"data-constant"}),intensity:new a.aa(a.a6.properties_light_ambient.intensity)})),this.scope,this.options);break;case"directional":if(this.directionalLight){const E=this.directionalLight;E.set(T),E.updateTransitions(f)}else this.directionalLight=new _s(T,Zi||(Zi=new a.a9({direction:new a.ap(a.a6.properties_light_directional.direction),color:new a.aa(a.a6.properties_light_directional.color),"color-use-theme":new a.aa({type:"string",default:"default","property-type":"data-constant"}),intensity:new a.aa(a.a6.properties_light_directional.intensity),"cast-shadows":new a.aa(a.a6.properties_light_directional["cast-shadows"]),"shadow-quality":new a.aa(a.a6.properties_light_directional["shadow-quality"]),"shadow-intensity":new a.aa(a.a6.properties_light_directional["shadow-intensity"])})),this.scope,this.options)}}const v=Object.assign(f,{worldview:this.map.getWorldview()}),S=new a.ac(this.z||0,v);this.ambientLight&&this.ambientLight.recalculate(S),this.directionalLight&&this.directionalLight.recalculate(S),this._brightness=this.calculateLightsBrightness(),this.dispatcher.broadcast("setBrightness",this._brightness)}calculateLightsBrightness(){const u=this.directionalLight,f=this.ambientLight;if(!u||!f)return;const v=J=>.2126*(J[0]<=.03928?J[0]/12.92:Math.pow((J[0]+.055)/1.055,2.4))+.7152*(J[1]<=.03928?J[1]/12.92:Math.pow((J[1]+.055)/1.055,2.4))+.0722*(J[2]<=.03928?J[2]/12.92:Math.pow((J[2]+.055)/1.055,2.4)),S=u.properties.get("color").toNonPremultipliedRenderColor(null).toArray01(),T=u.properties.get("intensity"),E=u.properties.get("direction"),L=1-a.d4(E.x,E.y,E.z)[2]/90,B=v(S)*T*L,q=f.properties.get("color").toNonPremultipliedRenderColor(null).toArray01(),G=f.properties.get("intensity"),ee=v(q)*G;return Number(((B+ee)/2).toFixed(6))}getBrightness(){return this._brightness}getLights(){if(!this.enable3dLights())return null;const u=[];return this.directionalLight&&u.push(this.directionalLight.get()),this.ambientLight&&u.push(this.ambientLight.get()),u}enable3dLights(){return!!this.ambientLight&&!!this.directionalLight}getFragmentStyle(u){if(u==null||u===""&&this.isRootStyle())return this;if(a.dr(u)){const f=a.ds(u),v=this.fragments.find(({id:T})=>T===f);if(!v)return;const S=a.dq(u);return v.style.getFragmentStyle(S)}{const f=this.fragments.find(({id:v})=>v===u);return f?f.style:void 0}}setFeaturesetSelectors(u){if(!u)return;const f={},v=(S,T="")=>`${S}::${T}`;this._featuresetSelectors={};for(const S in u){const T=this._featuresetSelectors[S]=[];for(const E of u[S].selectors){if(E.featureNamespace){const B=this.getOwnLayer(E.layer);if(!B){a.w(`Layer is undefined for selector: ${E.layer}`);continue}const q=v(B.source,B.sourceLayer);if(q in f&&f[q]!==E.featureNamespace){a.w(`"featureNamespace ${E.featureNamespace} of featureset ${S}'s selector is not associated to the same source, skip this selector`);continue}f[q]=E.featureNamespace}let L;if(E.properties)for(const B in E.properties){const q=a.U(E.properties[B]);q.result==="success"&&(L=L||{},L[B]=q.value)}T.push({layerId:E.layer,namespace:E.featureNamespace,properties:L,uniqueFeatureID:E._uniqueFeatureID})}}}getFeaturesetDescriptors(u){const f=this.getFragmentStyle(u);if(!f||!f.stylesheet.featuresets)return[];const v=[];for(const S in f.stylesheet.featuresets)v.push({featuresetId:S,importId:f.scope?f.scope:void 0});return v}getFeaturesetLayers(u,f){const v=this.getFragmentStyle(f),S=v.stylesheet.featuresets;if(!S||!S[u])return this.fire(new a.y(new Error(`The featureset '${u}' does not exist in the map's style and cannot be queried.`))),[];const T=[];for(const E of S[u].selectors){const L=v.getOwnLayer(E.layer);L&&T.push(L)}return T}getConfigProperty(u,f){const v=this.getFragmentStyle(u);if(!v)return null;const S=a.B(f,v.scope),T=v.options.get(S),E=T?T.value||T.default:null;return E?E.serialize():null}isIndoorEnabled(){return Object.keys(this._mergedIndoor).length>0}getIndoorSourceLayers(u,f){const v=a.B(u,f);return this._mergedIndoor[v]}setIndoorData(u,f){this.map.indoor.setIndoorData(f)}updateIndoorDependentLayers(){this._updateLayers(this._indoorDependentLayers),this.map._styleDirty=!0,this.map.triggerRepaint()}setConfigProperty(u,f,v){const S=this.getFragmentStyle(u);if(!S)return;const T=S.stylesheet.schema;if(!T||!T[f])return;const E=a.U(v);if(E.result!=="success")return void Ff(this,E.value);const L=E.value.expression,B=a.B(f,S.scope),q=S.options.get(B);if(!q)return;let G;const{minValue:ee,maxValue:J,stepValue:re,type:oe,values:se}=T[f],me=a.U(T[f].default);me.result==="success"&&(G=me.value.expression),G?(this.options.set(B,Object.assign({},q,{value:L,default:G,minValue:ee,maxValue:J,stepValue:re,type:oe,values:se})),this.updateConfigDependencies(f)):this.fire(new a.y(new Error(`No schema defined for the config option "${f}" in the "${u}" fragment.`)))}getConfig(u){const f=this.getFragmentStyle(u);if(!f)return null;const v=f.stylesheet.schema;if(!v)return null;const S={};for(const T in v){const E=a.B(T,f.scope),L=f.options.get(E),B=L?L.value||L.default:null;S[T]=B?B.serialize():null}return S}setConfig(u,f){const v=this.getFragmentStyle(u);v&&(v.updateConfig(f,v.stylesheet.schema),this.updateConfigDependencies())}getSchema(u){const f=this.getFragmentStyle(u);return f?f.stylesheet.schema:null}setSchema(u,f){const v=this.getFragmentStyle(u);v&&(v.stylesheet.schema=f,v.updateConfig(v._config,f),this.updateConfigDependencies())}updateConfig(u,f){if(this._config=u,u||f)if(f)for(const v in f){let S,T;const E=a.U(f[v].default);if(E.result==="success"&&(S=E.value.expression),u&&u[v]!==void 0){const J=a.U(u[v]);J.result==="success"&&(T=J.value.expression)}const{minValue:L,maxValue:B,stepValue:q,type:G,values:ee}=f[v];if(S){const J=a.B(v,this.scope);this.options.set(J,{default:S,value:T,minValue:L,maxValue:B,stepValue:q,type:G,values:ee})}else this.fire(new a.y(new Error(`No schema defined for config option "${v}".`)))}else this.fire(new a.y(new Error("Attempting to set config for a style without schema.")))}_updateLayers(u,f=()=>!0){for(const v of u){const S=this.getLayer(v);S&&f(S)&&(S.possiblyEvaluateVisibility(),this._updateLayer(S),this._changes.setDirty())}}updateConfigDependencies(u){this._updateLayers(this._configDependentLayers,f=>!u||f.expressionDependencies.configDependencies.has(u)),this.ambientLight&&this.ambientLight.updateConfig(this.options),this.directionalLight&&this.directionalLight.updateConfig(this.options),this.fog&&this.fog.updateConfig(this.options),this.snow&&this.snow.updateConfig(this.options),this.rain&&this.rain.updateConfig(this.options),this.forEachFragmentStyle(f=>{const v=f._styleColorTheme.colorThemeOverride?f._styleColorTheme.colorThemeOverride:f._styleColorTheme.colorTheme;if(v){const S=f._evaluateColorThemeData(v);(!f._styleColorTheme.lut&&S!==""||f._styleColorTheme.lut&&S!==f._styleColorTheme.lut.data)&&f.setColorTheme(v)}}),this._changes.setDirty()}addLayer(u,f,v={}){this._checkLoaded();const S=u.id;if(this._layers[S])return void this.fire(new a.y(new Error(`Layer with id "${S}" already exists on this map`)));let T;if(u.type==="custom"){if(Ff(this,a.dt(u)))return;T=a.du(u,this.scope,this._styleColorTheme.lut,this.options)}else{if(typeof u.source=="object"&&(this.addSource(S,u.source),u=a.dp(u),u=Object.assign(u,{source:S})),this._validate(Px,`layers.${S}`,u,{arrayIndex:-1},v))return;T=a.du(u,this.scope,this._styleColorTheme.lut,this.options),this._validateLayer(T),T.setEventedParent(this,{layer:{id:S}})}const E=a.B(T.source,T.scope);T.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(E),T.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(E);let L=this._order.length;if(f){const ee=this._order.indexOf(f);if(ee===-1)return void this.fire(new a.y(new Error(`Layer with id "${f}" does not exist on this map.`)));T.slot===this._layers[f].slot?L=ee:a.w(`Layer with id "${f}" has a different slot. Layers can only be rearranged within the same slot.`)}this._order.splice(L,0,S),this._layerOrderChanged=!0,this._layers[S]=T;const B=this.getOwnLayerSourceCache(T),q=!!this.directionalLight&&this.directionalLight.shadowsEnabled();B&&T.canCastShadows()&&q&&(B.castsShadows=!0);const G=this._changes.getRemovedLayer(T);if(G&&T.source&&B&&T.type!=="custom"){this._changes.discardLayerRemoval(T);const ee=a.B(T.source,T.scope);G.type!==T.type?this._changes.updateSourceCache(ee,"clear"):(this._changes.updateSourceCache(ee,"reload"),B.pause())}this._updateLayer(T),T.onAdd&&T.onAdd(this.map),T.scope=this.scope,this.mergeLayers()}moveLayer(u,f){this._checkLoaded();const v=this._checkLayer(u);if(!v||u===f)return;const S=this._order.indexOf(u);this._order.splice(S,1);let T=this._order.length;if(f){const E=this._order.indexOf(f);if(E===-1)return void this.fire(new a.y(new Error(`Layer with id "${f}" does not exist on this map.`)));v.slot===this._layers[f].slot?T=E:a.w(`Layer with id "${f}" has a different slot. Layers can only be rearranged within the same slot.`)}this._order.splice(T,0,u),this._changes.setDirty(),this._layerOrderChanged=!0,this.mergeLayers()}removeLayer(u){this._checkLoaded();const f=this._checkLayer(u);if(!f)return;f.setEventedParent(null);const v=this._order.indexOf(u);this._order.splice(v,1),delete this._layers[u],this._changes.setDirty(),this._layerOrderChanged=!0,this._configDependentLayers.delete(f.fqid),this._indoorDependentLayers.delete(f.fqid),this._changes.removeLayer(f);const S=this.getOwnLayerSourceCache(f);if(S&&S.castsShadows){let T=!1;for(const E in this._layers)if(this._layers[E].source===f.source&&this._layers[E].canCastShadows()){T=!0;break}S.castsShadows=T}f.onRemove&&f.onRemove(this.map),this.mergeLayers()}getOwnLayer(u){return this._layers[u]}hasLayer(u){return u in this._mergedLayers}hasLayerType(u){for(const f in this._layers)if(this._layers[f].type===u)return!0;return!1}setLayerZoomRange(u,f,v){this._checkLoaded();const S=this._checkLayer(u);S&&(S.minzoom===f&&S.maxzoom===v||(f!=null&&(S.minzoom=f),v!=null&&(S.maxzoom=v),this._updateLayer(S)))}getSlots(){return this._checkLoaded(),this._mergedSlots}setSlot(u,f){this._checkLoaded();const v=this._checkLayer(u);v&&v.slot!==f&&(v.slot=f,this._updateLayer(v))}setFilter(u,f,v={}){this._checkLoaded();const S=this._checkLayer(u);if(S&&!a.by(S.filter,f))return f==null?(S.filter=void 0,void this._updateLayer(S)):void(this._validate(jh,`layers.${S.id}.filter`,f,{layerType:S.type},v)||(S.filter=a.dp(f),this._updateLayer(S)))}getFilter(u){const f=this._checkLayer(u);if(f)return a.dp(f.filter)}setLayoutProperty(u,f,v,S={}){this._checkLoaded();const T=this._checkLayer(u);if(T&&!a.by(T.getLayoutProperty(f),v)){if(v!=null&&(!S||S.validate!==!1)&&Ff(T,vt.call(ki,{key:`layers.${u}.layout.${f}`,layerType:T.type,objectKey:f,value:v,styleSpec:a.a6,style:{glyphs:!0,sprite:!0}})))return;T.setLayoutProperty(f,v),T.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(T.fqid),T.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(T.fqid),this._updateLayer(T)}}setLayerProperty(u,f,v,S={}){this._checkLoaded();const T=this._checkLayer(u);T&&(f==="appearances"?(T.setAppearances(v),this._changes.setDirty()):T.isPaintProperty(f)?this.setPaintProperty(u,f,v,S):this.setLayoutProperty(u,f,v,S))}getLayoutProperty(u,f){const v=this._checkLayer(u);if(v)return v.getLayoutProperty(f)}setPaintProperty(u,f,v,S={}){this._checkLoaded();const T=this._checkLayer(u);if(!T||a.by(T.getPaintProperty(f),v)||v!=null&&(!S||S.validate!==!1)&&Ff(T,Fp.call(ki,{key:`layers.${u}.paint.${f}`,layerType:T.type,objectKey:f,value:v,styleSpec:a.a6})))return;const E=T.setPaintProperty(f,v);T.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(T.fqid),T.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(T.fqid),E&&this._updateLayer(T),this._changes.updatePaintProperties(T)}getPaintProperty(u,f){const v=this._checkLayer(u);if(v)return v.getPaintProperty(f)}setFeatureState(u,f){if(this._checkLoaded(),"target"in u){if("featuresetId"in u.target){const{featuresetId:B,importId:q}=u.target,G=this.getFragmentStyle(q),ee=G.getFeaturesetLayers(B);for(const{source:J,sourceLayer:re}of ee)G.setFeatureState({id:u.id,source:J,sourceLayer:re},f)}else if("layerId"in u.target){const{layerId:B}=u.target,q=this.getLayer(B);this.setFeatureState({id:u.id,source:q.source,sourceLayer:q.sourceLayer},f)}return}const v=u.source,S=u.sourceLayer,T=this._checkSource(v);if(!T)return;const E=T.type;if(E==="geojson"&&S)return void this.fire(new a.y(new Error("GeoJSON sources cannot have a sourceLayer parameter.")));if(E==="vector"&&!S)return void this.fire(new a.y(new Error("The sourceLayer parameter must be provided for vector source types.")));u.id===void 0&&this.fire(new a.y(new Error("The feature id parameter must be provided.")));const L=this.getOwnSourceCaches(v);for(const B of L)B.setFeatureState(S,u.id,f)}removeFeatureState(u,f){if(this._checkLoaded(),"target"in u){if("featuresetId"in u.target){const{featuresetId:B,importId:q}=u.target,G=this.getFragmentStyle(q),ee=G.getFeaturesetLayers(B);for(const{source:J,sourceLayer:re}of ee)G.removeFeatureState({id:u.id,source:J,sourceLayer:re},f)}else if("layerId"in u.target){const{layerId:B}=u.target,q=this.getLayer(B);this.removeFeatureState({id:u.id,source:q.source,sourceLayer:q.sourceLayer},f)}return}const v=u.source,S=this._checkSource(v);if(!S)return;const T=S.type,E=T==="vector"?u.sourceLayer:void 0;if(T==="vector"&&!E)return void this.fire(new a.y(new Error("The sourceLayer parameter must be provided for vector source types.")));if(f&&typeof u.id!="string"&&typeof u.id!="number")return void this.fire(new a.y(new Error("A feature id is required to remove its specific state property.")));const L=this.getOwnSourceCaches(v);for(const B of L)B.removeFeatureState(E,u.id,f)}getFeatureState(u){if(this._checkLoaded(),"target"in u){let T;if("featuresetId"in u.target){const{featuresetId:E,importId:L}=u.target,B=this.getFragmentStyle(L),q=B.getFeaturesetLayers(E);for(const{source:G,sourceLayer:ee}of q){const J=B.getFeatureState({id:u.id,source:G,sourceLayer:ee});if(J&&!T)T=J;else if(!a.by(T,J))return void this.fire(new a.y(new Error("The same feature id exists in multiple sources in the featureset, but their feature states are not consistent through the sources.")))}}else if("layerId"in u.target){const{layerId:E}=u.target,L=this.getLayer(E);T=this.getFeatureState({id:u.id,source:L.source,sourceLayer:L.sourceLayer})}return T}const f=u.source,v=u.sourceLayer,S=this._checkSource(f);if(S){if(S.type!=="vector"||v)return u.id===void 0&&this.fire(new a.y(new Error("The feature id parameter must be provided."))),this.getOwnSourceCaches(f)[0].getFeatureState(v,u.id);this.fire(new a.y(new Error("The sourceLayer parameter must be provided for vector source types.")))}}setTransition(u){return this.stylesheet.transition=Object.assign({},this.stylesheet.transition,u),this.transition=this.stylesheet.transition,this}getTransition(){return Object.assign({},this.stylesheet.transition)}serialize(){this._checkLoaded();const u=this.getTerrain(),f=u&&this.terrain&&this.terrain.scope===this.scope?u:this.stylesheet.terrain;return a.dv({version:this.stylesheet.version,name:this.stylesheet.name,metadata:this.stylesheet.metadata,fragment:this.stylesheet.fragment,iconsets:this.stylesheet.iconsets,imports:this._serializeImports(),schema:this.stylesheet.schema,camera:this.stylesheet.camera,light:this.stylesheet.light,lights:this.stylesheet.lights,terrain:f,fog:this.stylesheet.fog,snow:this.stylesheet.snow,rain:this.stylesheet.rain,center:this.stylesheet.center,"color-theme":this.stylesheet["color-theme"],zoom:this.stylesheet.zoom,bearing:this.stylesheet.bearing,pitch:this.stylesheet.pitch,sprite:this.stylesheet.sprite,glyphs:this.stylesheet.glyphs,transition:this.stylesheet.transition,projection:this.stylesheet.projection,sources:this._serializeSources(),layers:this._serializeLayers(this._order)},v=>v!==void 0)}_updateFilteredLayers(u){for(const f of Object.values(this._mergedLayers))u(f)&&this._updateLayer(f)}_updateLayer(u){this._changes.updateLayer(u);const f=this.getLayerSourceCache(u),v=a.B(u.source,u.scope),S=this._changes.getUpdatedSourceCaches();u.source&&!S[v]&&f&&f.getSource().type!=="raster"&&(this._changes.updateSourceCache(v,"reload"),f.pause()),u.invalidateCompiledFilter()}_flattenAndSortRenderedFeatures(u){const f=L=>this._mergedLayers[L].is3D(!!this.terrain),v=this.order,S={},T=[];for(let L=v.length-1;L>=0;L--){const B=v[L];if(f(B)){S[B]=L;for(const q of u){const G=q[B];if(G)for(const ee of G)T.push(ee)}}}T.sort((L,B)=>B.intersectionZ-L.intersectionZ);const E=[];for(let L=v.length-1;L>=0;L--){const B=v[L];if(f(B))for(let q=T.length-1;q>=0;q--){const G=T[q].feature;if(G.layer&&S[G.layer.id]{if(P0.has(G.type))return;const ee=this.getOwnLayerSourceCache(G),J=T[ee.id]=T[ee.id]||{sourceCache:ee,layers:{},has3DLayers:!1};G.is3D(!!this.terrain)&&(J.has3DLayers=!0),J.layers[G.fqid]=J.layers[G.fqid]||{styleLayer:G,targets:[]},J.layers[G.fqid].targets.push({filter:S})};if(f&&f.layers){if(!Array.isArray(f.layers))return this.fire(new a.y(new Error("parameters.layers must be an Array."))),[];for(const G of f.layers){const ee=this._layers[G];if(!ee)return this.fire(new a.y(new Error(`The layer '${G}' does not exist in the map's style and cannot be queried for features.`))),[];E(ee)}}else for(const G in this._layers)E(this._layers[G]);const L=this._queryRenderedFeatures(u,T,v),B=this._flattenAndSortRenderedFeatures(L),q=[];for(const G of B)a.dw(G.layer.id)===this.scope&&q.push(G);return q}queryRenderedFeatureset(u,f,v){let S;f&&!Array.isArray(f)&&f.filter&&(this._validate(jh,"queryRenderedFeatures.filter",f.filter,null,f),S=a.b6(f.filter));const T="mock",E=[];if(f&&f.target)E.push(Object.assign({},f,{targetId:T,filter:S}));else{const G=this.getFeaturesetDescriptors();for(const ee of G)E.push({targetId:T,filter:S,target:ee});for(const{style:ee}of this.fragments){const J=ee.getFeaturesetDescriptors();for(const re of J)E.push({targetId:T,filter:S,target:re})}}const L=this.queryRenderedTargets(u,E,v),B=[],q=new Set;for(const G of L)for(const ee of G.variants[T])hg(ee,G,q)||B.push(new a.dx(G,ee));return B}queryRenderedTargets(u,f,v){const S={},T=(L,B,q,G)=>{const ee=S[B.id]=S[B.id]||{sourceCache:B,layers:{},has3DLayers:!1};if(ee.layers[L.fqid]=ee.layers[L.fqid]||{styleLayer:L,targets:[]},L.is3D(!!this.terrain)&&(ee.has3DLayers=!0),!G)return q.uniqueFeatureID=!1,void ee.layers[L.fqid].targets.push(q);ee.layers[L.fqid].targets.push(Object.assign({},q,{namespace:G.namespace,properties:G.properties,uniqueFeatureID:G.uniqueFeatureID}))};for(const L of f)if("featuresetId"in L.target){const{featuresetId:B,importId:q}=L.target,G=this.getFragmentStyle(q);if(!G||!G._featuresetSelectors)continue;const ee=G._featuresetSelectors[B];if(!ee){this.fire(new a.y(new Error(`The featureset '${B}' does not exist in the map's style and cannot be queried for features.`)));continue}for(const J of ee){const re=G.getOwnLayer(J.layerId);re&&!P0.has(re.type)&&T(re,G.getOwnLayerSourceCache(re),L,J)}}else if("layerId"in L.target){const{layerId:B}=L.target,q=this.getLayer(B);if(!q||P0.has(q.type))continue;T(q,this.getLayerSourceCache(q),L)}const E=this._queryRenderedFeatures(u,S,v);return this._flattenAndSortRenderedFeatures(E)}_queryRenderedFeatures(u,f,v){const S=[],T=!!this.map._showQueryGeometry,E=Xi.createFromScreenPoints(u,v);for(const L in f){const B=p0(E,f[L],this._availableImages,v,T);Object.keys(B).length&&S.push(B)}if(this.placement)for(const L in f){if(!f[L].sourceCache._onlySymbols)continue;const B=m0(E.screenGeometry,f[L],this._availableImages,this.placement.collisionIndex,this.placement.retainedQueryData,this.map.getWorldview());Object.keys(B).length&&S.push(B)}return S}querySourceFeatures(u,f){const v=f&&f.filter;v&&this._validate(jh,"querySourceFeatures.filter",v,null,f);let S=[];const T=this.getOwnSourceCaches(u);for(const E of T)S=S.concat(g0(E,f));return S}addSourceType(u,f,v){return wu.getSourceType(u)?v(new Error(`A source type called "${u}" already exists.`)):(wu.setSourceType(u,f),f.workerSourceURL?void this.dispatcher.broadcast("loadWorkerSource",{name:u,url:f.workerSourceURL},v):v(null,null))}getFlatLight(){return this.light.getLight()}setFlatLight(u,f,v={}){this._checkLoaded();const S=this.light.getLight();let T=!1;for(const L in u)if(!a.by(u[L],S[L])){T=!0;break}if(!T)return;const E=this._getTransitionParameters();this.light.setLight(u,f,v),this.light.updateTransitions(E)}getTerrain(){return this.terrain&&this.terrain.drapeRenderMode===1?this.terrain.get():null}setTerrainForDraping(){this.setTerrain({source:"",exaggeration:0},0)}checkCanvasFingerprintNoise(){this.disableElevatedTerrain===void 0&&(this.disableElevatedTerrain=a.o.hasCanvasFingerprintNoise(),this.disableElevatedTerrain&&a.w("Terrain and hillshade are disabled because of Canvas2D limitations when fingerprinting protection is enabled (e.g. in private browsing mode)."))}setTerrain(u,f=1){if(this._checkLoaded(),!u)return this.terrainSetForDrapingOnly()||(delete this.terrain,this.map.transform.projection.requiresDraping&&this.setTerrainForDraping()),f===0&&delete this.terrain,u===null?this.stylesheet.terrain=null:delete this.stylesheet.terrain,this._force3DLayerUpdate(),void(this._markersNeedUpdate=!0);this.checkCanvasFingerprintNoise();let v=u;const S=!("source"in u)||u.source==null;if(f===1){if(this.disableElevatedTerrain)return;if("source"in v&&typeof v.source=="object"){const L="terrain-dem-src";this.addSource(L,v.source),v=a.dp(v),v=Object.assign(v,{source:L})}const T=Object.assign({},v),E={};if(this.terrain&&S){T.source=this.terrain.get().source;const L=this.terrain?this.getFragmentStyle(this.terrain.scope):null;L&&(E.style=L.serialize())}if(this._validate(zc,"terrain",T,E))return}if(!this.terrain||this.terrain.scope!==this.scope&&!S||this.terrain&&f!==this.terrain.drapeRenderMode){if(!v)return;this._createTerrain(v,f),this.fire(new a.z("data",{dataType:"style"}))}else{const T=this.terrain,E=T.get();for(const L of Object.keys(a.a6.terrain))!v.hasOwnProperty(L)&&a.a6.terrain[L].default&&(v[L]=a.a6.terrain[L].default);for(const L in u)if(!a.by(u[L],E[L])){T.set(u,this.options),this.stylesheet.terrain=u;const B=this._getTransitionParameters({duration:0});T.updateTransitions(B),this.fire(new a.z("data",{dataType:"style"}));break}}this.mergeTerrain(),this.updateDrapeFirstLayers(),this._markersNeedUpdate=!0}_createFog(u){const f=this.fog=new Vr(u,this.map.transform,this.scope,this.options);this.stylesheet.fog=f.get();const v=this._getTransitionParameters({duration:0});f.updateTransitions(v)}_createSnow(u){const f=this.snow=new Oa(u,this.map.transform,this.scope,this.options);this.stylesheet.snow=f.get();const v=this._getTransitionParameters({duration:0});f.updateTransitions(v)}_createRain(u){const f=this.rain=new Yi(u,this.map.transform,this.scope,this.options);this.stylesheet.rain=f.get();const v=this._getTransitionParameters({duration:0});f.updateTransitions(v)}_updateMarkersOpacity(){this.map._markers.length!==0&&this.map._requestDomTask(()=>{for(const u of this.map._markers)u._evaluateOpacity()})}getFog(){return this.fog?this.fog.get():null}setFog(u){if(this._checkLoaded(),!u)return delete this.fog,delete this.stylesheet.fog,void(this._markersNeedUpdate=!0);if(this.fog){const f=this.fog;if(!a.by(f.get(),u)){f.set(u,this.options),this.stylesheet.fog=f.get();const v=this._getTransitionParameters({duration:0});f.updateTransitions(v)}}else this._createFog(u);this._markersNeedUpdate=!0}getSnow(){return this.snow?this.snow.get():null}setSnow(u){if(this._checkLoaded(),!u)return delete this.snow,void delete this.stylesheet.snow;if(this.snow){const f=this.snow;if(!a.by(f.get(),u)){f.set(u,this.options),this.stylesheet.snow=f.get();const v=this._getTransitionParameters({duration:0});f.updateTransitions(v)}}else this._createSnow(u);this._markersNeedUpdate=!0}getRain(){return this.rain?this.rain.get():null}setRain(u){if(this._checkLoaded(),!u)return delete this.rain,void delete this.stylesheet.rain;if(this.rain){const f=this.rain;if(!a.by(f.get(),u)){f.set(u,this.options),this.stylesheet.rain=f.get();const v=this._getTransitionParameters({duration:0});f.updateTransitions(v)}}else this._createRain(u);this._markersNeedUpdate=!0}_reloadColorTheme(){const u=()=>{for(const S in this._layers)this._layers[S].lut=this._styleColorTheme.lut;for(const S in this._sourceCaches)this._sourceCaches[S].clearTiles()},f=this._styleColorTheme.colorThemeOverride?this._styleColorTheme.colorThemeOverride:this._styleColorTheme.colorTheme;if(!f)return this._styleColorTheme.lut=null,void u();const v=this._evaluateColorThemeData(f);this._loadColorTheme(v).then(()=>{this.fire(new a.z("colorthemeset")),u()}).catch(S=>{a.w(`Couldn't set color theme: ${S}`)})}setColorTheme(u){this._checkLoaded(),this._styleColorTheme.colorThemeOverride&&a.w("Note: setColorTheme is called on a style with a color-theme override, the passed color-theme won't be visible."),this._styleColorTheme.colorTheme=u,this._reloadColorTheme()}setImportColorTheme(u,f){const v=this.getFragmentStyle(u);v&&(v._styleColorTheme.colorThemeOverride=f,v._reloadColorTheme())}_getTransitionParameters(u){return{now:a.o.now(),transition:Object.assign(this.transition,u)}}updateDrapeFirstLayers(){if(!this.terrain)return;const u=[],f=[];for(const v of this._mergedOrder)this.isLayerDraped(this._mergedLayers[v])?u.push(v):f.push(v);this._drapedFirstOrder=[],this._drapedFirstOrder.push(...u),this._drapedFirstOrder.push(...f)}_createTerrain(u,f){const v=this.terrain=new dt(u,f,this.scope,this.options,this.map.getWorldview());f===1&&(this.stylesheet.terrain=u),this.mergeTerrain(),this.updateDrapeFirstLayers(),this._force3DLayerUpdate();const S=this._getTransitionParameters({duration:0});v.updateTransitions(S)}_force3DLayerUpdate(){for(const u in this._layers){const f=this._layers[u];f.type==="fill-extrusion"&&this._updateLayer(f)}}_forceSymbolLayerUpdate(){for(const u in this._layers){const f=this._layers[u];f.type==="symbol"&&this._updateLayer(f)}}_validate(u,f,v,S,T={}){if(T&&T.validate===!1)return!1;const E=Object.assign({},this.serialize());return Ff(this,u.call(ki,Object.assign({key:f,style:E,value:v,styleSpec:a.a6},S)))}_remove(){this._request&&(this._request.cancel(),this._request=null),this._spriteRequest&&(this._spriteRequest.cancel(),this._spriteRequest=null),a.dy.off("pluginStateChange",this._rtlTextPluginCallback);for(const u in this._mergedLayers)this._mergedLayers[u].setEventedParent(null);for(const u in this._mergedSourceCaches)this._mergedSourceCaches[u].clearTiles(),this._mergedSourceCaches[u].setEventedParent(null);this.imageManager.removeScope(this.scope),this.setEventedParent(null),delete this.fog,delete this.snow,delete this.rain,delete this.terrain,delete this.ambientLight,delete this.directionalLight,this.isRootStyle()&&(this.imageManager.setEventedParent(null),this.imageManager.destroy(),this.modelManager.setEventedParent(null),this.modelManager.destroy(),this.dispatcher.remove())}clearSource(u){const f=this.getSourceCaches(u);for(const v of f)v.clearTiles()}clearSources(){for(const u in this._mergedSourceCaches)this._mergedSourceCaches[u].clearTiles()}clearLayers(){for(const u in this._mergedLayers){const f=this._mergedLayers[u];f._clear&&f._clear()}}reloadSource(u){const f=this.getSourceCaches(u);for(const v of f)v.resume(),v.reload()}reloadSources(){for(const u of this.getSources())u.reload&&u.reload()}reloadModels(){this.modelManager.reloadModels(""),this.forEachFragmentStyle(u=>{u.modelManager.reloadModels(u.scope)})}updateSources(u){let f;this.directionalLight&&(f=Hx(this.directionalLight));const v=new Set,S=new Set;for(const T in this._mergedLayers){const E=this._mergedLayers[T];E.type==="building"&&v.add(E.source),E.hasElevation()&&!S.has(E.source)&&S.add(E.source)}for(const T in this._mergedSourceCaches){const E=this._mergedSourceCaches[T],L=S.has(E._source.id);v.has(E._source.id)&&(E._source.reparseOverscaled=!1),E.update(u,void 0,void 0,f,L)}}_generateCollisionBoxes(){for(const u in this._sourceCaches){const f=this._sourceCaches[u];f.resume(),f.reload()}}_updatePlacement(u,f,v,S,T,E,L=!1){let B=!1,q=!1;const G={},ee={};for(const se of this._mergedOrder){const me=this._mergedLayers[se];if(me.type!=="symbol")continue;const fe=a.B(me.source,me.scope);let Ne=G[fe];if(!Ne){const Te=this.getLayerSourceCache(me);if(!Te)continue;const Ze=Te.getRenderableIds(!0).map($e=>Te.getTileByID($e));ee[fe]=Ze.slice(),Ne=G[fe]=Ze.sort(($e,He)=>He.tileID.overscaledZ-$e.tileID.overscaledZ||($e.tileID.isLessThan(He.tileID)?-1:1))}const Ae=this.crossTileSymbolIndex.addLayer(me,Ne,f.center.lng,f.projection);B=B||Ae}this.crossTileSymbolIndex.pruneUnusedLayers(this._mergedOrder),L=L||this._layerOrderChanged,this._layerOrderChanged&&this.fire(new a.z("neworder"));const J=!!(this.placement&&!f.equals(this.placement.transform)),re=!!(this.placement&&(this.placement.lastReplacementSourceUpdateTime!==0&&!E||this.placement.lastReplacementSourceUpdateTime!==E.updateTime)),oe=(J||re||B||this.placement&&this.placement.isStale())&&S===0;if((L||!this.pauseablePlacement||oe||S!==0&&this.pauseablePlacement.isDone()&&!this.placement.stillRecent(a.o.now(),f.zoom))&&(this.pauseablePlacement=new co(f,this._mergedOrder,L||S===0,v,S,T,this.placement,this.fog&&f.projection.supportsFog?this.fog.state:null,this._buildingIndex),this._layerOrderChanged=!1),this.pauseablePlacement.isDone()?this.placement.setStale():(this.pauseablePlacement.continuePlacement(this._mergedOrder,this._mergedLayers,G,ee,this.map.painter.scaleFactor),this.pauseablePlacement.isDone()&&(this.placement=this.pauseablePlacement.commit(a.o.now()),q=!0),B&&this.pauseablePlacement.placement.setStale()),q||B){this._buildingIndex.onNewFrame(f.zoom);for(let se=0;seT===u.id)!==-1)return void this.fire(new a.y(new Error(`Import with id '${u.id}' already exists in the map's style.`)));if(!f)return v.push(u),this._loadImports([u],!0);const S=v.findIndex(({id:T})=>T===f);return S===-1&&this.fire(new a.y(new Error(`Import with id "${f}" does not exist on this map.`))),this.stylesheet.imports=v.slice(0,S).concat(u).concat(v.slice(S)),this._loadImports([u],!0,f)}updateImport(u,f){this._checkLoaded();const v=this.stylesheet.imports||[],S=this.getImportIndex(u);return S===-1?this:typeof f=="string"?(this.setImportUrl(u,f),this):(f.url&&f.url!==v[S].url&&this.setImportUrl(u,f.url),a.by(f.config,v[S].config)||this.setImportConfig(u,f.config,f.data.schema),a.by(f.data,v[S].data)||this.setImportData(u,f.data),this)}moveImport(u,f){this._checkLoaded();let v=this.stylesheet.imports||[];const S=this.getImportIndex(u);if(S===-1)return this;const T=this.getImportIndex(f);if(T===-1)return this;const E=v[S],L=this.fragments[S];return v=v.filter(({id:B})=>B!==u),this.fragments=this.fragments.filter(({id:B})=>B!==u),this.stylesheet.imports=v.slice(0,T).concat(E).concat(v.slice(T)),this.fragments=this.fragments.slice(0,T).concat(L).concat(this.fragments.slice(T)),this.mergeLayers(),this}setImportUrl(u,f){this._checkLoaded();const v=this.stylesheet.imports||[],S=this.getImportIndex(u);if(S===-1)return this;v[S].url=f;const T=this.fragments[S];return T.style=this._createFragmentStyle(v[S]),T.style.on("style.import.load",()=>this.mergeAll()),T.style.loadURL(f),this}setImportData(u,f){this._checkLoaded();const v=this.getImportIndex(u),S=this.stylesheet.imports||[];return v===-1?this:f?(this.fragments[v].style.setState(f),this._reloadImports(),this):(delete S[v].data,this.setImportUrl(u,S[v].url))}setImportConfig(u,f,v){this._checkLoaded();const S=this.getImportIndex(u),T=this.stylesheet.imports||[];if(S===-1)return this;f?T[S].config=f:delete T[S].config;const E=this.fragments[S];v&&E.style.stylesheet&&(E.style.stylesheet.schema=v);const L=E.style.stylesheet&&E.style.stylesheet.schema;return E.config=f,E.style.updateConfig(f,L),this.updateConfigDependencies(),this}removeImport(u){this._checkLoaded();const f=this.stylesheet.imports||[],v=this.getImportIndex(u);v!==-1&&(f.splice(v,1),this.fragments[v].style._remove(),this.fragments.splice(v,1),this._reloadImports())}getImportIndex(u){const f=(this.stylesheet.imports||[]).findIndex(v=>v.id===u);return f===-1&&this.fire(new a.y(new Error(`Import '${u}' does not exist in the map's style and cannot be updated.`))),f}getLayer(u){return this._mergedLayers[u]}getSources(){const u=[];for(const f in this._mergedOtherSourceCaches){const v=this._mergedOtherSourceCaches[f];v&&u.push(v.getSource())}return u}getSource(u,f){const v=this.getSourceCache(u,f);return v&&v.getSource()}getLayerSource(u){const f=this.getLayerSourceCache(u);return f&&f.getSource()}getSourceCache(u,f){const v=a.B(u,f);return this._mergedOtherSourceCaches[v]}getLayerSourceCache(u){const f=a.B(u.source,u.scope);return u.type==="symbol"?this._mergedSymbolSourceCaches[f]:this._mergedOtherSourceCaches[f]}getSourceCaches(u){if(u==null)return Object.values(this._mergedSourceCaches);const f=[];return this._mergedOtherSourceCaches[u]&&f.push(this._mergedOtherSourceCaches[u]),this._mergedSymbolSourceCaches[u]&&f.push(this._mergedSymbolSourceCaches[u]),f}updateSourceCaches(){const u=this._changes.getUpdatedSourceCaches();for(const f in u){const v=u[f];v==="reload"?this.reloadSource(f):v==="clear"&&this.clearSource(f)}}updateLayers(u){const f=this._changes.getUpdatedPaintProperties();for(const v of f){const S=this.getLayer(v);S&&S.updateTransitions(u)}}getGlyphsUrl(){return this.stylesheet.glyphs}setGlyphsUrl(u){this.stylesheet.glyphs=u,this.glyphManager.setURL(u)}getImages(u,f,v){this.imageManager.getImages(f.images,f.scope,v),this._updateTilesForChangedImages();const S=E=>{if(E){const L=f.images.map(B=>a.I.toString(B));E.setDependencies(f.tileID.key,f.type,L)}},T=a.B(f.source,f.scope);S(this._mergedOtherSourceCaches[T]),S(this._mergedSymbolSourceCaches[T]),f.images.some(E=>E.iconsetId)&&this.fire(new a.z("data",{dataType:"style"}))}rasterizeImages(u,f,v){this.imageManager.rasterizeImages(f,v)}getGlyphs(u,f,v){this.glyphManager.getGlyphs(f.stacks,v)}getResource(u,f,v){return a.dz(f,v)}getOwnSourceCache(u){return this._otherSourceCaches[u]}getOwnLayerSourceCache(u){return u.type==="symbol"?this._symbolSourceCaches[u.source]:this._otherSourceCaches[u.source]}getOwnSourceCaches(u){const f=[];return this._otherSourceCaches[u]&&f.push(this._otherSourceCaches[u]),this._symbolSourceCaches[u]&&f.push(this._symbolSourceCaches[u]),f}_isSourceCacheLoaded(u){const f=this.getOwnSourceCaches(u);return f.length===0?(this.fire(new a.y(new Error(`There is no source with ID '${u}'`))),!1):f.every(v=>v.loaded())}has3DLayers(){return this._has3DLayers}hasSymbolLayers(){return this._hasSymbolLayers}hasCircleLayers(){return this._hasCircleLayers}isLayerClipped(u,f){if(!this._clipLayerPresent&&u.type!=="fill-extrusion"&&u.type!=="building")return!1;const v=u.type==="fill-extrusion"&&(u.sourceLayer==="building"||u.sourceLayer==="procedural_buildings"),S=u.type==="building";if(u.is3D(!!this.terrain)){if(v||S||f&&f.type==="batched-model"||u.type==="model")return!0}else if(u.type==="symbol")return!0;return!1}_clearWorkerCaches(){this.dispatcher.broadcast("clearCaches")}destroy(){this._clearWorkerCaches(),this.fragments.forEach(u=>{u.style._remove()}),this.terrainSetForDrapingOnly()&&(delete this.terrain,delete this.stylesheet.terrain)}}wu.getSourceType=function(x){return Td[x]},wu.setSourceType=function(x,u){Td[x]=u},wu.registerForPluginStateChange=a.dA;class lE extends a.E{constructor(u){super(),this._style=u,this._buildings={},this._activeFloors=new Set,this._activeFloorsVisible=!0,this._indoorState={selectedFloorId:null,lastActiveFloors:null,activeFloorsVisible:!0},a.aY(["_updateUI"],this)}destroy(){this._buildings={},this._activeFloors=new Set,this._indoorState=null}selectFloor(u){u===this._selectedFloorId&&this._activeFloorsVisible||(this._selectedFloorId=u,this._activeFloorsVisible=!0,this._updateActiveFloors())}setActiveFloorsVisibility(u){this._activeFloorsVisible=u,this._updateActiveFloors(),this._updateIndoorSelector()}setIndoorData(u){for(const[f,v]of Object.entries(u.buildings))if(this._buildings[f])for(const S of v.floorIds)this._buildings[f].floors[S]||(this._buildings[f].floors[S]=v.floors[S]);else this._buildings[f]=v;for(const f of u.activeFloors)this._activeFloors.add(f);this._updateIndoorSelector()}getIndoorTileOptions(u,f){const v=this._style.getIndoorSourceLayers(u,f);return v&&this._indoorState?{sourceLayers:v,indoorState:this._indoorState}:null}_updateUI(u,f,v){const S=function(T,E,L,B){let q=null,G=Number.MAX_SAFE_INTEGER;if(B<16)return null;for(const[ee,J]of Object.entries(T)){const re=J.center;if(re){const oe=E.distanceTo(a.aT.convert(re));oe({id:E,name:v.floors[E].name,zIndex:v.floors[E].zIndex})).sort((E,L)=>L.zIndex-E.zIndex);this.fire(new a.z("selector-update",{selectedFloorId:S,activeFloorsVisible:this._activeFloorsVisible,floors:T}))}_updateActiveFloors(){const u=this._activeFloors;this._activeFloors=new Set,this._indoorState={selectedFloorId:this._selectedFloorId,lastActiveFloors:u,activeFloorsVisible:this._activeFloorsVisible},this._style.updateIndoorDependentLayers()}}var yg=` #define EPSILON 0.0000001 #define PI 3.141592653589793 #ifdef RENDER_CUTOFF float cutoff_opacity(vec4 cutoff_params,float depth) {float near=cutoff_params.x;float far=cutoff_params.y;float cutoffStart=cutoff_params.z;float cutoffEnd=cutoff_params.w;float linearDepth=(depth-near)/(far-near);return clamp((linearDepth-cutoffStart)/(cutoffEnd-cutoffStart),0.0,1.0);} #endif`,xg=` #ifdef DUAL_SOURCE_BLENDING layout(location=0,index=0) out vec4 glFragColor;layout(location=0,index=1) out vec4 glFragColorSrc1; #else layout(location=0) out vec4 glFragColor; #endif #ifdef USE_MRT1 layout(location=1) out vec4 out_Target1; #endif highp float unpack_depth(highp vec4 rgba_depth) {const highp vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(rgba_depth,bit_shift)*2.0-1.0;}highp vec4 pack_depth(highp float ndc_z) {highp float depth=ndc_z*0.5+0.5;const highp vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);const highp vec4 bit_mask =vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);highp vec4 res=fract(depth*bit_shift);res-=res.xxyz*bit_mask;return res;} #ifdef INDICATOR_CUTOUT uniform vec3 u_indicator_cutout_centers;uniform vec4 u_indicator_cutout_params; #endif vec4 applyCutout(vec4 color,float height) { #ifdef INDICATOR_CUTOUT float verticalFadeRange=u_indicator_cutout_centers.z*0.25;float holeMinOpacity=mix(1.0,u_indicator_cutout_params.x,smoothstep(u_indicator_cutout_centers.z,u_indicator_cutout_centers.z+verticalFadeRange,height));float holeRadius=max(u_indicator_cutout_params.y,0.0);float holeAspectRatio=u_indicator_cutout_params.z;float fadeStart=u_indicator_cutout_params.w;float distA=distance(vec2(gl_FragCoord.x,gl_FragCoord.y*holeAspectRatio),vec2(u_indicator_cutout_centers[0],u_indicator_cutout_centers[1]*holeAspectRatio));return color*min(smoothstep(fadeStart,holeRadius,distA)+holeMinOpacity,1.0); #else return color; #endif } #ifdef DEBUG_WIREFRAME #define HANDLE_WIREFRAME_DEBUG \\ glFragColor=vec4(0.7,0.0,0.0,0.7); \\ gl_FragDepth=gl_FragCoord.z-0.0001; #else #define HANDLE_WIREFRAME_DEBUG #endif #ifdef RENDER_CUTOFF uniform highp vec4 u_cutoff_params;in float v_cutoff_opacity; #endif vec4 textureLodCustom(sampler2D image,highp vec2 pos,highp vec2 lod_coord) {highp vec2 size=vec2(textureSize(image,0));highp vec2 dx=dFdx(lod_coord.xy*size);highp vec2 dy=dFdy(lod_coord.xy*size);highp float delta_max_sqr=max(dot(dx,dx),dot(dy,dy));highp float lod=0.5*log2(delta_max_sqr);return textureLod(image,pos,lod);}vec4 applyLUT(highp sampler3D lut,vec4 col) {vec3 size=vec3(textureSize(lut,0));vec3 uvw=(col.rbg*float(size-1.0)+0.5)/size;return vec4(texture(lut,uvw).rgb*col.a,col.a);}vec3 applyLUT(highp sampler3D lut,vec3 col) {return applyLUT(lut,vec4(col,1.0)).rgb;}`,xS=` #define EXTENT 8192.0 #define RAD_TO_DEG 180.0/PI #define DEG_TO_RAD PI/180.0 #define GLOBE_RADIUS EXTENT/PI/2.0 float wrap(float n,float min,float max) {float d=max-min;float w=mod(mod(n-min,d)+d,d)+min;return (w==min) ? max : w;} #ifdef PROJECTION_GLOBE_VIEW vec3 mercator_tile_position(mat4 matrix,vec2 tile_anchor,vec3 tile_id,vec2 mercator_center) { #ifndef PROJECTED_POS_ON_VIEWPORT float tiles=tile_id.z;vec2 mercator=(tile_anchor/EXTENT+tile_id.xy)/tiles;mercator-=mercator_center;mercator.x=wrap(mercator.x,-0.5,0.5);vec4 mercator_tile=vec4(mercator.xy*EXTENT,EXTENT/(2.0*PI),1.0);mercator_tile=matrix*mercator_tile;return mercator_tile.xyz; #else return vec3(0.0); #endif }vec3 mix_globe_mercator(vec3 globe,vec3 mercator,float t) {return mix(globe,mercator,t);}mat3 globe_mercator_surface_vectors(vec3 pos_normal,vec3 up_dir,float zoom_transition) {vec3 normal=zoom_transition==0.0 ? pos_normal : normalize(mix(pos_normal,up_dir,zoom_transition));vec3 xAxis=normalize(vec3(normal.z,0.0,-normal.x));vec3 yAxis=normalize(cross(normal,xAxis));return mat3(xAxis,yAxis,normal);} #endif vec2 unpack_float(const float packedValue) {int packedIntValue=int(packedValue);int v0=packedIntValue/256;return vec2(v0,packedIntValue-v0*256);}vec2 unpack_opacity(const float packedOpacity) {int intOpacity=int(packedOpacity)/2;return vec2(float(intOpacity)/127.0,mod(packedOpacity,2.0));}vec4 decode_color(const vec2 encodedColor) {return vec4( unpack_float(encodedColor[0])/255.0,unpack_float(encodedColor[1])/255.0 );}float unpack_mix_vec2(const vec2 packedValue,const float t) {return mix(packedValue[0],packedValue[1],t);}vec4 unpack_mix_color(const vec4 packedColors,const float t) {vec4 minColor=decode_color(vec2(packedColors[0],packedColors[1]));vec4 maxColor=decode_color(vec2(packedColors[2],packedColors[3]));return mix(minColor,maxColor,t);}vec2 get_pattern_pos(const vec2 pixel_coord_upper,const vec2 pixel_coord_lower,const vec2 pattern_size,const vec2 units_to_pixels,const vec2 pos) {vec2 offset=mod(mod(mod(pixel_coord_upper,pattern_size)*256.0,pattern_size)*256.0+pixel_coord_lower,pattern_size);return (units_to_pixels*pos+offset)/pattern_size;}vec2 get_pattern_pos(const vec2 pixel_coord_upper,const vec2 pixel_coord_lower,const vec2 pattern_size,const float tile_units_to_pixels,const vec2 pos) {return get_pattern_pos(pixel_coord_upper,pixel_coord_lower,pattern_size,vec2(tile_units_to_pixels),pos);}float mercatorXfromLng(float lng) {return (180.0+lng)/360.0;}float mercatorYfromLat(float lat) {return (180.0-(RAD_TO_DEG*log(tan(PI/4.0+lat/2.0*DEG_TO_RAD))))/360.0;}vec3 latLngToECEF(vec2 latLng) {latLng=DEG_TO_RAD*latLng;float cosLat=cos(latLng[0]);float sinLat=sin(latLng[0]);float cosLng=cos(latLng[1]);float sinLng=sin(latLng[1]);float sx=cosLat*sinLng*GLOBE_RADIUS;float sy=-sinLat*GLOBE_RADIUS;float sz=cosLat*cosLng*GLOBE_RADIUS;return vec3(sx,sy,sz);} #ifdef RENDER_CUTOFF uniform vec4 u_cutoff_params;out float v_cutoff_opacity; #endif const vec4 AWAY=vec4(-1000.0,-1000.0,-1000.0,1);const float skirtOffset=24575.0;vec3 decomposeToPosAndSkirt(vec2 posWithComposedSkirt) {float skirt=float(posWithComposedSkirt.x >=skirtOffset);vec2 pos=posWithComposedSkirt-vec2(skirt*skirtOffset,0.0);return vec3(pos,skirt);} #ifndef HAS_SHADER_STORAGE_BLOCK_material_buffer #define GET_ATTRIBUTE_float(attrib,matInfo,attrib_id) attrib #define GET_ATTRIBUTE_vec4(attrib,matInfo,attrib_id) attrib #define GET_ATTRIBUTE_vec2(attrib,matInfo,attrib_id) attrib #define DECLARE_MATERIAL_TABLE_INFO #endif`,I0="in highp vec3 a_pos_3f;uniform lowp mat4 u_matrix;out highp vec3 v_uv;void main() {const mat3 half_neg_pi_around_x=mat3(1.0,0.0, 0.0,0.0,0.0,-1.0,0.0,1.0, 0.0);v_uv=half_neg_pi_around_x*a_pos_3f;vec4 pos=u_matrix*vec4(a_pos_3f,1.0);gl_Position=pos.xyww;}",$c=` #define ELEVATION_SCALE 7.0 #define ELEVATION_OFFSET 450.0 #ifdef PROJECTION_GLOBE_VIEW uniform vec3 u_tile_tl_up;uniform vec3 u_tile_tr_up;uniform vec3 u_tile_br_up;uniform vec3 u_tile_bl_up;uniform float u_tile_up_scale;vec3 elevationVector(vec2 pos) {vec2 uv=pos/EXTENT;vec3 up=normalize(mix( mix(u_tile_tl_up,u_tile_tr_up,uv.xxx),mix(u_tile_bl_up,u_tile_br_up,uv.xxx),uv.yyy));return up*u_tile_up_scale;} #else vec3 elevationVector(vec2 pos) { return vec3(0,0,1); } #endif #ifdef TERRAIN uniform highp sampler2D u_dem;uniform highp sampler2D u_dem_prev;uniform vec2 u_dem_tl;uniform vec2 u_dem_tl_prev;uniform float u_dem_scale;uniform float u_dem_scale_prev;uniform float u_dem_size;uniform float u_dem_lerp;uniform float u_exaggeration;uniform float u_meter_to_dem;uniform mat4 u_label_plane_matrix_inv;vec4 tileUvToDemSample(vec2 uv,float dem_size,float dem_scale,vec2 dem_tl) {vec2 pos=dem_size*(uv*dem_scale+dem_tl)+1.0;vec2 f=fract(pos);return vec4((pos-f+0.5)/(dem_size+2.0),f);}float currentElevation(vec2 apos) { #ifdef TERRAIN_DEM_FLOAT_FORMAT vec2 pos=(u_dem_size*(apos/8192.0*u_dem_scale+u_dem_tl)+1.5)/(u_dem_size+2.0);return u_exaggeration*texture(u_dem,pos).r; #else float dd=1.0/(u_dem_size+2.0);vec4 r=tileUvToDemSample(apos/8192.0,u_dem_size,u_dem_scale,u_dem_tl);vec2 pos=r.xy;vec2 f=r.zw;float tl=texture(u_dem,pos).r;float tr=texture(u_dem,pos+vec2(dd,0)).r;float bl=texture(u_dem,pos+vec2(0,dd)).r;float br=texture(u_dem,pos+vec2(dd,dd)).r;return u_exaggeration*mix(mix(tl,tr,f.x),mix(bl,br,f.x),f.y); #endif }float prevElevation(vec2 apos) { #ifdef TERRAIN_DEM_FLOAT_FORMAT vec2 pos=(u_dem_size*(apos/8192.0*u_dem_scale_prev+u_dem_tl_prev)+1.5)/(u_dem_size+2.0);return u_exaggeration*texture(u_dem_prev,pos).r; #else float dd=1.0/(u_dem_size+2.0);vec4 r=tileUvToDemSample(apos/8192.0,u_dem_size,u_dem_scale_prev,u_dem_tl_prev);vec2 pos=r.xy;vec2 f=r.zw;float tl=texture(u_dem_prev,pos).r;float tr=texture(u_dem_prev,pos+vec2(dd,0)).r;float bl=texture(u_dem_prev,pos+vec2(0,dd)).r;float br=texture(u_dem_prev,pos+vec2(dd,dd)).r;return u_exaggeration*mix(mix(tl,tr,f.x),mix(bl,br,f.x),f.y); #endif } #ifdef TERRAIN_VERTEX_MORPHING float elevation(vec2 apos) { #ifdef ZERO_EXAGGERATION return 0.0; #endif float nextElevation=currentElevation(apos);float prevElevation=prevElevation(apos);return mix(prevElevation,nextElevation,u_dem_lerp);} #else float elevation(vec2 apos) { #ifdef ZERO_EXAGGERATION return 0.0; #endif return currentElevation(apos);} #endif vec4 fourSample(vec2 pos,vec2 off) {float tl=texture(u_dem,pos).r;float tr=texture(u_dem,pos+vec2(off.x,0.0)).r;float bl=texture(u_dem,pos+vec2(0.0,off.y)).r;float br=texture(u_dem,pos+off).r;return vec4(tl,tr,bl,br);}float flatElevation(vec2 pack) {vec2 apos=floor(pack/8.0);vec2 span=10.0*(pack-apos*8.0);vec2 uvTex=(apos-vec2(1.0,1.0))/8190.0;float size=u_dem_size+2.0;float dd=1.0/size;vec2 pos=u_dem_size*(uvTex*u_dem_scale+u_dem_tl)+1.0;vec2 f=fract(pos);pos=(pos-f+0.5)*dd;vec4 h=fourSample(pos,vec2(dd));float z=mix(mix(h.x,h.y,f.x),mix(h.z,h.w,f.x),f.y);vec2 w=floor(0.5*(span*u_meter_to_dem-1.0));vec2 d=dd*w;h=fourSample(pos-d,2.0*d+vec2(dd));vec4 diff=abs(h.xzxy-h.ywzw);vec2 slope=min(vec2(0.25),u_meter_to_dem*0.5*(diff.xz+diff.yw)/(2.0*w+vec2(1.0)));vec2 fix=slope*span;float base=z+max(fix.x,fix.y);return u_exaggeration*base;}float elevationFromUint16(float word) {return u_exaggeration*(word/ELEVATION_SCALE-ELEVATION_OFFSET);} #else float elevation(vec2 pos) { return 0.0; } #endif #ifdef DEPTH_OCCLUSION uniform highp sampler2D u_depth;uniform highp vec2 u_depth_size_inv;uniform highp vec2 u_depth_range_unpack;uniform highp float u_occluder_half_size;uniform highp float u_occlusion_depth_offset; #ifdef DEPTH_D24 float unpack_depth(float depth) {return depth*u_depth_range_unpack.x+u_depth_range_unpack.y;}vec4 unpack_depth4(vec4 depth) {return depth*u_depth_range_unpack.x+vec4(u_depth_range_unpack.y);} #else highp float unpack_depth_rgba(vec4 rgba_depth) {const highp vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(rgba_depth,bit_shift)*2.0-1.0;} #endif bool isOccluded(vec4 frag) {vec3 coord=frag.xyz/frag.w; #ifdef CLIP_ZERO_TO_ONE coord.z=-1.0+2.0*coord.z; #endif #ifdef DEPTH_D24 float depth=unpack_depth(texture(u_depth,(coord.xy+1.0)*0.5).r); #else float depth=unpack_depth_rgba(texture(u_depth,(coord.xy+1.0)*0.5)); #endif return coord.z+u_occlusion_depth_offset > depth;}highp vec4 getCornerDepths(vec2 coord) {highp vec3 df=vec3(u_occluder_half_size*u_depth_size_inv,0.0);highp vec2 uv=0.5*coord.xy+0.5; #ifdef DEPTH_D24 highp vec4 depth=vec4( texture(u_depth,uv-df.xz).r,texture(u_depth,uv+df.xz).r,texture(u_depth,uv-df.zy).r,texture(u_depth,uv+df.zy).r );depth=unpack_depth4(depth); #else highp vec4 depth=vec4( unpack_depth_rgba(texture(u_depth,uv-df.xz)),unpack_depth_rgba(texture(u_depth,uv+df.xz)),unpack_depth_rgba(texture(u_depth,uv-df.zy)),unpack_depth_rgba(texture(u_depth,uv+df.zy)) ); #endif return depth;}highp float occlusionFadeMultiSample(vec4 frag) {highp vec3 coord=frag.xyz/frag.w;highp vec2 uv=0.5*coord.xy+0.5; #ifdef CLIP_ZERO_TO_ONE coord.z=-1.0+2.0*coord.z; #endif int NX=3;int NY=4;highp vec2 df=u_occluder_half_size*u_depth_size_inv;highp vec2 oneStep=2.0*u_occluder_half_size*u_depth_size_inv/vec2(NX-1,NY-1);highp float res=0.0;for (int y=0; y < NY;++y) {for (int x=0; x < NX;++x) { #ifdef DEPTH_D24 highp float depth=unpack_depth(texture(u_depth,uv-df+vec2(float(x)*oneStep.x,float(y)*oneStep.y)).r); #else highp float depth=unpack_depth_rgba(texture(u_depth,uv-df+vec2(float(x)*oneStep.x,float(y)*oneStep.y))); #endif res+=1.0-clamp(300.0*(coord.z+u_occlusion_depth_offset-depth),0.0,1.0);}}res=clamp(2.0*res/float(NX*NY)-0.5,0.0,1.0);return res;}highp float occlusionFade(vec4 frag) {highp vec3 coord=frag.xyz/frag.w; #ifdef CLIP_ZERO_TO_ONE coord.z=-1.0+2.0*coord.z; #endif highp vec4 depth=getCornerDepths(coord.xy);return dot(vec4(0.25),vec4(1.0)-clamp(300.0*(vec4(coord.z+u_occlusion_depth_offset)-depth),0.0,1.0));} #else bool isOccluded(vec4 frag) { return false; }highp float occlusionFade(vec4 frag) { return 1.0; }highp float occlusionFadeMultiSample(vec4 frag) { return 1.0; } #endif`,M0=`#ifdef FOG uniform mediump vec4 u_fog_color;uniform mediump vec2 u_fog_range;uniform mediump float u_fog_horizon_blend;uniform mediump mat4 u_fog_matrix;out vec3 v_fog_pos;float fog_range(float depth) {return (depth-u_fog_range[0])/(u_fog_range[1]-u_fog_range[0]);}float fog_horizon_blending(vec3 camera_dir) {float t=max(0.0,camera_dir.z/u_fog_horizon_blend);return u_fog_color.a*exp(-3.0*t*t);}float fog_opacity(float t) {const float decay=6.0;float falloff=1.0-min(1.0,exp(-decay*t));falloff*=falloff*falloff;return u_fog_color.a*min(1.0,1.00747*falloff);}vec3 fog_position(vec3 pos) {return (u_fog_matrix*vec4(pos,1.0)).xyz;}vec3 fog_position(vec2 pos) {return fog_position(vec3(pos,0.0));}float fog(vec3 pos) {float depth=length(pos);float opacity=fog_opacity(fog_range(depth));return opacity*fog_horizon_blending(pos/depth);} #endif`,mr=`#ifdef FOG uniform mediump vec4 u_fog_color;uniform mediump vec2 u_fog_range;uniform mediump float u_fog_horizon_blend;uniform mediump vec2 u_fog_vertical_limit;uniform mediump float u_fog_temporal_offset;in vec3 v_fog_pos;uniform highp vec3 u_frustum_tl;uniform highp vec3 u_frustum_tr;uniform highp vec3 u_frustum_br;uniform highp vec3 u_frustum_bl;uniform highp vec3 u_globe_pos;uniform highp float u_globe_radius;uniform highp vec2 u_viewport;uniform float u_globe_transition;uniform int u_is_globe;float fog_range(float depth) {return (depth-u_fog_range[0])/(u_fog_range[1]-u_fog_range[0]);}float fog_horizon_blending(vec3 camera_dir) {float t=max(0.0,camera_dir.z/u_fog_horizon_blend);return u_fog_color.a*exp(-3.0*t*t);}float fog_opacity(float t) {const float decay=6.0;float falloff=1.0-min(1.0,exp(-decay*t));falloff*=falloff*falloff;return u_fog_color.a*min(1.0,1.00747*falloff);}float globe_glow_progress() {highp vec2 uv=gl_FragCoord.xy/u_viewport; #ifdef FLIP_Y uv.y=1.0-uv.y; #endif highp vec3 ray_dir=mix( mix(u_frustum_tl,u_frustum_tr,uv.x),mix(u_frustum_bl,u_frustum_br,uv.x),1.0-uv.y);highp vec3 dir=normalize(ray_dir);highp vec3 closest_point=dot(u_globe_pos,dir)*dir;highp float sdf=length(closest_point-u_globe_pos)/u_globe_radius;return sdf+PI*0.5;}float fog_opacity(vec3 pos) {float depth=length(pos);return fog_opacity(fog_range(depth));}vec3 fog_apply(vec3 color,vec3 pos,float opacity_limit) {float depth=length(pos);float opacity;if (u_is_globe==1) {float glow_progress=globe_glow_progress();float t=mix(glow_progress,depth,u_globe_transition);opacity=fog_opacity(fog_range(t));} else {opacity=fog_opacity(fog_range(depth));opacity*=fog_horizon_blending(pos/depth);}return mix(color,u_fog_color.rgb,min(opacity,opacity_limit));}vec3 fog_apply(vec3 color,vec3 pos) {return fog_apply(color,pos,1.0);}vec4 fog_apply_from_vert(vec4 color,float fog_opac) {float alpha=EPSILON+color.a;color.rgb=mix(color.rgb/alpha,u_fog_color.rgb,fog_opac)*alpha;return color;}vec3 fog_apply_sky_gradient(vec3 camera_ray,vec3 sky_color) {float horizon_blend=fog_horizon_blending(normalize(camera_ray));return mix(sky_color,u_fog_color.rgb,horizon_blend);}vec4 fog_apply_premultiplied(vec4 color,vec3 pos) {float alpha=EPSILON+color.a;color.rgb=fog_apply(color.rgb/alpha,pos)*alpha;return color;}vec4 fog_apply_premultiplied(vec4 color,vec3 pos,float heightMeters) {float verticalProgress=(u_fog_vertical_limit.x > 0.0 || u_fog_vertical_limit.y > 0.0) ? smoothstep(u_fog_vertical_limit.x,u_fog_vertical_limit.y,heightMeters) : 0.0;float opacityLimit=1.0-smoothstep(0.9,1.0,fog_opacity(pos));return mix(fog_apply_premultiplied(color,pos),color,min(verticalProgress,opacityLimit));}vec3 fog_dither(vec3 color) {return color;}vec4 fog_dither(vec4 color) {return vec4(fog_dither(color.rgb),color.a);} #endif`,vS=`#ifdef RASTER_ARRAY uniform highp sampler2D u_image0;uniform sampler2D u_image1;const vec4 NODATA=vec4(1);ivec4 _raTexLinearCoord(highp vec2 texCoord,highp vec2 texResolution,out highp vec2 fxy) {texCoord=texCoord*texResolution-0.5;fxy=fract(texCoord);texCoord-=fxy;return ivec4(texCoord.xxyy+vec2(1.5,0.5).xyxy);}vec2 _raTexLinearMix(highp vec2 fxy,highp vec4 colorMix,highp float colorOffset,highp vec4 t00,highp vec4 t10,highp vec4 t01,highp vec4 t11) {vec2 c00=t00==NODATA ? vec2(0) : vec2(colorOffset+dot(t00,colorMix),1);vec2 c10=t10==NODATA ? vec2(0) : vec2(colorOffset+dot(t10,colorMix),1);vec2 c01=t01==NODATA ? vec2(0) : vec2(colorOffset+dot(t01,colorMix),1);vec2 c11=t11==NODATA ? vec2(0) : vec2(colorOffset+dot(t11,colorMix),1);return mix(mix(c01,c11,fxy.x),mix(c00,c10,fxy.x),fxy.y);}vec2 raTexture2D_image0_linear(highp vec2 texCoord,highp vec2 texResolution,highp vec4 colorMix,highp float colorOffset) {vec2 fxy;ivec4 c=_raTexLinearCoord(texCoord,texResolution,fxy);return _raTexLinearMix(fxy,colorMix,colorOffset,texelFetch(u_image0,c.yz,0),texelFetch(u_image0,c.xz,0),texelFetch(u_image0,c.yw,0),texelFetch(u_image0,c.xw,0) );}vec2 raTexture2D_image1_linear(highp vec2 texCoord,highp vec2 texResolution,highp vec4 colorMix,highp float colorOffset) {vec2 fxy;ivec4 c=_raTexLinearCoord(texCoord,texResolution,fxy);return _raTexLinearMix(fxy,colorMix,colorOffset,texelFetch(u_image1,c.yz,0),texelFetch(u_image1,c.xz,0),texelFetch(u_image1,c.yw,0),texelFetch(u_image1,c.xw,0) );}vec2 raTexture2D_image0_nearest(highp vec2 texCoord,highp vec2 texResolution,highp vec4 colorMix,highp float colorOffset) {vec4 t=texelFetch(u_image0,ivec2(texCoord*texResolution),0);return t==NODATA ? vec2(0) : vec2(colorOffset+dot(t,colorMix),1);}vec2 raTexture2D_image1_nearest(highp vec2 texCoord,highp vec2 texResolution,highp vec4 colorMix,highp float colorOffset) {vec4 t=texelFetch(u_image1,ivec2(texCoord*texResolution),0);return t==NODATA ? vec2(0) : vec2(colorOffset+dot(t,colorMix),1);} #endif`,O0=`#ifdef RASTER_ARRAY uniform sampler2D u_velocity;uniform mediump vec2 u_velocity_res;uniform mediump float u_max_speed;const vec4 NO_DATA=vec4(1);const vec2 INVALID_VELOCITY=vec2(-1);uniform highp vec2 u_uv_offset;uniform highp float u_data_offset;uniform highp vec2 u_data_scale;ivec4 rasterArrayLinearCoord(highp vec2 texCoord,highp vec2 texResolution,out highp vec2 fxy) {texCoord=texCoord*texResolution-0.5;fxy=fract(texCoord);texCoord-=fxy;return ivec4(texCoord.xxyy+vec2(1.5,0.5).xyxy);}highp vec2 lookup_velocity(highp vec2 uv) {uv=u_uv_offset.x+u_uv_offset.y*uv;highp vec2 fxy;ivec4 c=rasterArrayLinearCoord(uv,u_velocity_res,fxy);highp vec4 tl=texelFetch(u_velocity,c.yz,0);highp vec4 tr=texelFetch(u_velocity,c.xz,0);highp vec4 bl=texelFetch(u_velocity,c.yw,0);highp vec4 br=texelFetch(u_velocity,c.xw,0);if (tl==NO_DATA) {return INVALID_VELOCITY;}if (tr==NO_DATA) {return INVALID_VELOCITY;}if (bl==NO_DATA) {return INVALID_VELOCITY;}if (br==NO_DATA) {return INVALID_VELOCITY;}highp vec4 t=mix(mix(bl,br,fxy.x),mix(tl,tr,fxy.x),fxy.y);highp vec2 velocity=u_data_offset+vec2(dot(t.rg,u_data_scale),dot(t.ba,u_data_scale));velocity.y=-velocity.y;velocity/=max(u_max_speed,length(velocity));return velocity;} #endif uniform highp float u_particle_pos_scale;uniform highp vec2 u_particle_pos_offset;highp vec4 pack_pos_to_rgba(highp vec2 p) {highp vec2 v=(p+u_particle_pos_offset)/u_particle_pos_scale;highp vec4 r=vec4(v.x,fract(v.x*255.0),v.y,fract(v.y*255.0));return vec4(r.x-r.y/255.0,r.y,r.z-r.w/255.0,r.w);}highp vec2 unpack_pos_from_rgba(highp vec4 v) {v=floor(v*255.0+0.5)/255.0;highp vec2 p=vec2(v.x+(v.y/255.0),v.z+(v.w/255.0));return u_particle_pos_scale*p-u_particle_pos_offset;}`,R0=`#ifdef RENDER_SHADOWS uniform mediump vec3 u_shadow_direction;uniform highp vec3 u_shadow_normal_offset;vec3 shadow_normal_offset(vec3 normal) {float tileInMeters=u_shadow_normal_offset[0];vec3 n=vec3(-normal.xy,tileInMeters*normal.z);float dotScale=min(1.0-dot(normal,u_shadow_direction),1.0)*0.5+0.5;return n*dotScale;}vec3 shadow_normal_offset_model(vec3 normal) {vec3 transformed_normal=vec3(-normal.xy,normal.z);float NDotL=dot(normalize(transformed_normal),u_shadow_direction);float dotScale=min(1.0-NDotL,1.0)*0.5+0.5;return normal*dotScale;}float shadow_normal_offset_multiplier0() {return u_shadow_normal_offset[1];}float shadow_normal_offset_multiplier1() {return u_shadow_normal_offset[2];} #endif`,_S=`#ifdef RENDER_SHADOWS precision highp sampler2DShadow;uniform sampler2DShadow u_shadowmap_0;uniform sampler2DShadow u_shadowmap_1;uniform float u_shadow_intensity;uniform float u_shadow_map_resolution;uniform float u_shadow_texel_size;uniform highp vec3 u_shadow_normal_offset;uniform vec2 u_fade_range;uniform mediump vec3 u_shadow_direction;uniform highp vec3 u_shadow_bias;float shadow_sample(sampler2DShadow shadowmap,highp vec3 pos,highp float bias) { #ifdef CLIP_ZERO_TO_ONE highp vec3 coord=vec3(pos.xy*0.5+0.5,pos.z-bias); #else highp vec3 coord=vec3(pos.xy*0.5+0.5,pos.z*0.5+0.5-bias); #endif return texture(shadowmap,coord);}float shadow_occlusion(highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth,highp float bias) {light_view_pos0.xyz/=light_view_pos0.w; #ifdef SHADOWS_SINGLE_CASCADE vec2 abs_bounds=abs(light_view_pos0.xy);if (abs_bounds.x >=1.0 || abs_bounds.y >=1.0) {return 0.0;}return shadow_sample(u_shadowmap_0,light_view_pos0.xyz,bias); #else light_view_pos1.xyz/=light_view_pos1.w;vec4 abs_bounds=abs(vec4(light_view_pos0.xy,light_view_pos1.xy));if (abs_bounds.x < 1.0 && abs_bounds.y < 1.0) {return shadow_sample(u_shadowmap_0,light_view_pos0.xyz,bias);}if (abs_bounds.z >=1.0 || abs_bounds.w >=1.0) {return 0.0;}float occlusion1=shadow_sample(u_shadowmap_1,light_view_pos1.xyz,bias);return clamp(mix(occlusion1,0.0,smoothstep(u_fade_range.x,u_fade_range.y,view_depth)),0.0,1.0); #endif }highp float calculate_shadow_bias(float NDotL) { #ifdef NORMAL_OFFSET return 0.5*u_shadow_bias.x; #else return 0.5*(u_shadow_bias.x+clamp(u_shadow_bias.y*tan(acos(NDotL)),0.0,u_shadow_bias.z)); #endif }float shadowed_light_factor_normal(vec3 N,highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth) {float NDotL=dot(N,u_shadow_direction);float bias=calculate_shadow_bias(NDotL);float occlusion=shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias);return mix(0.0,(1.0-(u_shadow_intensity*occlusion))*NDotL,step(0.0,NDotL));}float shadowed_light_factor_normal_opacity(vec3 N,highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth,float shadow_opacity) {float NDotL=dot(N,u_shadow_direction);float bias=calculate_shadow_bias(NDotL);float occlusion=shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias)*shadow_opacity;return mix(0.0,(1.0-(u_shadow_intensity*occlusion))*NDotL,step(0.0,NDotL));}float shadowed_light_factor_normal_unbiased(vec3 N,highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth) {float NDotL=dot(N,u_shadow_direction);float bias=0.0;float occlusion=shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias);return mix(0.0,(1.0-(u_shadow_intensity*occlusion))*NDotL,step(0.0,NDotL));}highp vec2 compute_receiver_plane_depth_bias(highp vec3 pos_dx,highp vec3 pos_dy) {highp vec2 biasUV=vec2( pos_dy.y*pos_dx.z-pos_dx.y*pos_dy.z,pos_dx.x*pos_dy.z-pos_dy.x*pos_dx.z);biasUV*=1.0/((pos_dx.x*pos_dy.y)-(pos_dx.y*pos_dy.x));return biasUV;}float shadowed_light_factor_plane_bias(highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth) {highp vec3 light_view_pos0_xyz=light_view_pos0.xyz/light_view_pos0.w*0.5+0.5;highp vec3 light_view_pos0_ddx=dFdx(light_view_pos0_xyz);highp vec3 light_view_pos0_ddy=dFdy(light_view_pos0_xyz);highp vec2 plane_depth_bias=compute_receiver_plane_depth_bias(light_view_pos0_ddx,light_view_pos0_ddy);highp float bias=dot(vec2(u_shadow_texel_size,u_shadow_texel_size),plane_depth_bias)+0.0001;float occlusion=shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias);return 1.0-(u_shadow_intensity*occlusion);}float shadowed_light_factor(highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth) {float bias=0.0;float occlusion=shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias);return 1.0-(u_shadow_intensity*occlusion);}float shadow_occlusion(float ndotl,highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth) {float bias=calculate_shadow_bias(ndotl);return shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias);} #endif`;const Gx=/#include\s+"([^"]+)"/g,Rd=/#pragma mapbox: ([\w\-]+) ([\w]+) ([\w]+) ([\w]+)/g,bS=/\b[A-Za-z_][A-Za-z0-9_]*\b/g,Wp=new Set(["ifdef","ifndef","elif","if","defined"]),Gp=new Set;$f(yg,Gp),$f(xS,Gp),$f(xg,Gp);const Bf={"_prelude_fog.vertex.glsl":M0,"_prelude_terrain.vertex.glsl":$c,"_prelude_shadow.vertex.glsl":R0,"_prelude_material_table.vertex.glsl":`#ifdef HAS_SHADER_STORAGE_BLOCK_material_buffer #define MATERIAL_TABLE_DEBUG 0 uniform int u_material_offset;uniform int u_vertex_offset;layout(std140,binding=0)readonly buffer material_buffer{uvec4 material_data[];};struct MaterialInfo{uint dataOffset; #if MATERIAL_TABLE_DEBUG vec4 colorDebug; #endif };uint read_buf_no_offset(uint iDword) {return material_data[iDword/4u][iDword % 4u];}uint read_buf(uint iDword) {iDword+=uint(u_material_offset/4);return read_buf_no_offset(iDword);}float read_buf_float(uint iDword){return uintBitsToFloat(read_buf(iDword));}uint read_buf_uint8(uint iDword,uint iUint8){uint dwordOffset=iDword+(iUint8/4u);uint byteOffset=iUint8 & 3u;uint bitOffset=8u*byteOffset;uint mask=0xffu << bitOffset;uint dwordVal=read_buf(dwordOffset);return (dwordVal & mask) >> bitOffset;}uint read_buf_uint16(uint iDword,uint iUint16){uint dwordOffset=iDword+(iUint16 >> 1u);uint bitOffset=(iUint16 & 1u)*16u;uint mask=0xffffu << bitOffset;uint dwordVal=read_buf(dwordOffset);return (dwordVal & mask) >> bitOffset;}uint nrDwordsForVertexIdEntries(uint nrMaterialLookupEntries) {return nrMaterialLookupEntries;}uint nrDwordsForMaterialIdEntries(uint nrMaterialLookupEntries) {return (nrMaterialLookupEntries*2u+3u)/4u;}uint findRangeBinarySearch(uint vertexId,uint numRanges,uint dwordOffset) {uint left=0u;uint right=numRanges-1u;for (uint i=0u; i < 16u; i++) { if (left > right) {break;}uint mid=(left+right)/2u;uint start=read_buf(dwordOffset+mid);uint nextStart=(mid+1u < numRanges) ? read_buf(dwordOffset+mid+1u) : 0xffffffffu;if (vertexId >=start && vertexId < nextStart) {return mid;} else if (vertexId < start) {if (mid==0u) {break;}right=mid-1u;} else {left=mid+1u;}}return 0u; }uint readVertexId(uint dwordOffset,uint iMaterialLookupEntry) {return read_buf(dwordOffset+iMaterialLookupEntry);}uint findRange(uint vertexId,uint numRanges,uint dwordOffset) {uint iRange;if(numRanges <=64u){uint vertexBegin;for(iRange=0u; iRange < numRanges;++iRange) {vertexBegin=readVertexId(dwordOffset,iRange);if(vertexBegin > vertexId) {break;}}iRange=iRange==0u? 0u : iRange-1u;} else { iRange=findRangeBinarySearch(vertexId,numRanges,dwordOffset);}return iRange;}MaterialInfo read_material_info(uint vertex_id) {MaterialInfo info; #if MATERIAL_TABLE_DEBUG const vec4 red=vec4(1.0,0.0,0.0,1.0);const vec4 orange=vec4(1.0,0.5,0.0,1.0);const vec4 yellow=vec4(1.0,1.0,0.0,1.0);const vec4 green=vec4(0.0,1.0,0.0,1.0);const vec4 indigo=vec4(0.294,0.0,0.510,1.0);const vec4 blue=vec4(0.0,0.0,1.0,1.0);const vec4 purple=vec4(0.5,0.0,0.5,1.0);const vec4 pink=vec4(1.0,0.0,1.0,1.0);info.colorDebug=green; #endif uint offset=0u; #if MATERIAL_TABLE_DEBUG bool keepFinding=true;uint magic=read_buf(offset);if(magic !=0xCAFEBABEu) {info.colorDebug=red;keepFinding=false;return info;} #endif offset++; #if MATERIAL_TABLE_DEBUG uint nrMaterials=read_buf(offset);uint nrVertices=read_buf(offset+1u);if(keepFinding && vertex_id >=nrVertices) {info.colorDebug=red;keepFinding=false;} #endif offset+=2u;uint nrMaterialLookupEntries=read_buf(offset++);uint perMaterialEntrySizeDwords=read_buf(offset++); #if MATERIAL_TABLE_DEBUG if(keepFinding && perMaterialEntrySizeDwords !=1u) {info.colorDebug=red;keepFinding=false;} #endif uint iMaterialLookup=findRange(vertex_id,nrMaterialLookupEntries,offset); #if MATERIAL_TABLE_DEBUG if(keepFinding) {uint vertexBeginCheck=readVertexId(offset,iMaterialLookup);if(vertexBeginCheck > vertex_id) {info.colorDebug=red;keepFinding=false;}if(iMaterialLookup < nrMaterialLookupEntries-1u) {uint vertexEndCheck=readVertexId(offset,iMaterialLookup+1u);if(vertexEndCheck <=vertex_id) {info.colorDebug=red;keepFinding=false;}}} #endif offset+=nrDwordsForVertexIdEntries(nrMaterialLookupEntries);uint materialId=iMaterialLookup; #if MATERIAL_TABLE_DEBUG if(keepFinding) {if(materialId >=nrMaterialLookupEntries) {info.colorDebug=red;}} #endif info.dataOffset=offset+materialId*perMaterialEntrySizeDwords;return info;}uint get_data_location(const MaterialInfo matInfo,uint attribOffsetBytes) {uint attribFieldOffsetDwords=attribOffsetBytes/4u;return matInfo.dataOffset+attribFieldOffsetDwords;}vec4 read_material_vec4(const MaterialInfo matInfo,uint attribOffsetBytes){uint loc=get_data_location(matInfo,attribOffsetBytes);return vec4(read_buf_float(loc),read_buf_float(loc+1u),read_buf_float(loc+2u),read_buf_float(loc+3u));}vec2 read_material_vec2(const MaterialInfo matInfo,uint attribOffsetBytes){uint loc=get_data_location(matInfo,attribOffsetBytes);return vec2(read_buf_float(loc),read_buf_float(loc+1u));}float read_material_float(const MaterialInfo matInfo,uint attribOffsetBytes){uint loc=get_data_location(matInfo,attribOffsetBytes);return read_buf_float(loc);} #define GET_ATTRIBUTE_float(attrib,matInfo,attrib_offset) read_material_float(matInfo,attrib_offset) #define GET_ATTRIBUTE_vec4(attrib,matInfo,attrib_offset) read_material_vec4(matInfo,attrib_offset) #define GET_ATTRIBUTE_vec2(attrib,matInfo,attrib_offset) read_material_vec2(matInfo,attrib_offset) #define DECLARE_MATERIAL_TABLE_INFO MaterialInfo materialInfo=read_material_info(uint(gl_VertexID)); #define DECLARE_MATERIAL_TABLE_INFO_DEBUG(dbgColor) MaterialInfo materialInfo=read_material_info(uint(gl_VertexID)); dbgColor=materialInfo.colorDebug; #endif`,"_prelude_fog.fragment.glsl":mr,"_prelude_shadow.fragment.glsl":_S,"_prelude_lighting.glsl":` #ifdef LIGHTING_3D_MODE uniform mediump vec3 u_lighting_ambient_color;uniform mediump vec3 u_lighting_directional_dir;uniform mediump vec3 u_lighting_directional_color;uniform mediump vec3 u_ground_radiance;float calculate_ambient_directional_factor(vec3 normal) {float NdotL=dot(normal,u_lighting_directional_dir);const float factor_reduction_max=0.3;float dir_luminance=dot(u_lighting_directional_color,vec3(0.2126,0.7152,0.0722));float directional_factor_min=1.0-factor_reduction_max*min(dir_luminance,1.0);float ambient_directional_factor=mix(directional_factor_min,1.0,min((NdotL+1.0),1.0));const float vertical_factor_min=0.92;float vertical_factor=mix(vertical_factor_min,1.0,normal.z*0.5+0.5);return vertical_factor*ambient_directional_factor;}vec3 linearProduct(vec3 srgbIn,vec3 k) {return srgbIn*pow(k,vec3(1./2.2));}vec3 apply_lighting(vec3 color,vec3 normal,float dir_factor) {float ambient_directional_factor=calculate_ambient_directional_factor(normal);vec3 ambient_contrib=ambient_directional_factor*u_lighting_ambient_color;vec3 directional_contrib=u_lighting_directional_color*dir_factor;return linearProduct(color,ambient_contrib+directional_contrib);}vec4 apply_lighting(vec4 color,vec3 normal,float dir_factor) {return vec4(apply_lighting(color.rgb,normal,dir_factor),color.a);}vec3 apply_lighting(vec3 color,vec3 normal) {float dir_factor=max(dot(normal,u_lighting_directional_dir),0.0);return apply_lighting(color.rgb,normal,dir_factor);}vec4 apply_lighting(vec4 color,vec3 normal) {float dir_factor=max(dot(normal,u_lighting_directional_dir),0.0);return vec4(apply_lighting(color.rgb,normal,dir_factor),color.a);}vec3 apply_lighting_ground(vec3 color) {return color*u_ground_radiance;}vec4 apply_lighting_ground(vec4 color) {return vec4(apply_lighting_ground(color.rgb),color.a);}float calculate_NdotL(vec3 normal) {const float ext=0.70710678118;return (clamp(dot(normal,u_lighting_directional_dir),-ext,1.0)+ext)/(1.0+ext);}vec4 apply_lighting_with_emission_ground(vec4 color,float emissive_strength) {return mix(apply_lighting_ground(color),color,emissive_strength);}vec3 compute_flood_lighting(vec3 flood_light_color,float fully_occluded_factor,float occlusion,vec3 ground_shadow_factor) {vec3 fully_occluded_color=flood_light_color*mix(ground_shadow_factor,vec3(1.0),fully_occluded_factor);float occlusion_ramp=smoothstep(0.0,0.2,1.0-occlusion);return mix(fully_occluded_color,flood_light_color,occlusion_ramp);}vec3 compute_emissive_draped(vec3 unlit_color,float fully_occluded_factor,float occlusion,vec3 ground_shadow_factor) {vec3 fully_occluded_color=unlit_color*mix(ground_shadow_factor,vec3(1.0),fully_occluded_factor);return mix(fully_occluded_color,unlit_color,1.0-occlusion);} #endif`,"_prelude_raster_array.glsl":vS,"_prelude_raster_particle.glsl":O0},D0={};ps("",$c),ps(mr,M0),ps(_S,R0),ps(vS,""),ps(O0,"");const cE=ps(xg,xS),L0=yg,u4=[` #if defined(GL_EXT_blend_func_extended) && defined(DUAL_SOURCE_BLENDING) #extension GL_EXT_blend_func_extended : require #endif`,"precision mediump float;",L0,cE.fragmentSource].join(` `),uE=["precision highp float;",L0,cE.vertexSource].join(` `);var wS={background:ps(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" uniform vec4 u_color;uniform float u_opacity;uniform mediump float u_emissive_strength; #ifdef LIGHTING_3D_MODE in vec4 v_color; #endif void main() {vec4 out_color; #ifdef LIGHTING_3D_MODE out_color=v_color; #else out_color=u_color; #endif #ifdef FOG out_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos)); #endif glFragColor=out_color*u_opacity; #ifdef USE_MRT1 out_Target1=vec4(u_emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a); #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_lighting.glsl" in vec2 a_pos;uniform mat4 u_matrix;uniform mediump float u_emissive_strength; #ifdef LIGHTING_3D_MODE uniform mediump vec4 u_color;out vec4 v_color; #endif void main() {gl_Position=u_matrix*vec4(a_pos,0,1); #ifdef LIGHTING_3D_MODE v_color=apply_lighting_with_emission_ground(u_color,u_emissive_strength); #endif #ifdef FOG v_fog_pos=fog_position(a_pos); #endif }`),backgroundPattern:ps(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" uniform vec2 u_pattern_tl;uniform vec2 u_pattern_br;uniform vec2 u_texsize;uniform float u_opacity;uniform float u_emissive_strength;uniform sampler2D u_image;in highp vec2 v_pos;void main() {highp vec2 imagecoord=mod(v_pos,1.0);highp vec2 pos=mix(u_pattern_tl/u_texsize,u_pattern_br/u_texsize,imagecoord);vec4 out_color=textureLodCustom(u_image,pos,v_pos); #ifdef LIGHTING_3D_MODE out_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength); #endif #ifdef FOG out_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos)); #endif glFragColor=out_color*u_opacity; #ifdef USE_MRT1 out_Target1=vec4(u_emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a); #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" uniform mat4 u_matrix;uniform vec2 u_pattern_size;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec2 u_pattern_units_to_pixels;in vec2 a_pos;out highp vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_pattern_size,u_pattern_units_to_pixels,a_pos); #ifdef FOG v_fog_pos=fog_position(a_pos); #endif }`),building:ps(`#include "_prelude_fog.fragment.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_lighting.glsl" const float window_depth=0.5;const float ao_radius=0.2;in vec4 v_color;in highp vec3 v_normal;in highp vec3 v_pos; #ifdef BUILDING_FAUX_FACADE in lowp float v_faux_facade;in highp float v_faux_facade_ed;in highp vec2 v_faux_facade_window;in highp vec2 v_faux_facade_floor;in highp vec2 v_faux_facade_range;in highp float v_aspect;in highp vec3 v_tbn_0;in highp vec3 v_tbn_1;in highp vec3 v_tbn_2;in highp vec4 v_faux_color_emissive;uniform float u_faux_facade_ao_intensity; #endif #ifdef RENDER_SHADOWS in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1; #endif #ifdef FLOOD_LIGHT in highp float v_flood_radius;in float v_has_flood_light; #endif uniform lowp float u_opacity;uniform vec3 u_camera_pos;uniform highp float u_tile_to_meter;uniform float u_facade_emissive_chance;uniform vec3 u_flood_light_color;uniform float u_flood_light_intensity;vec3 linearTosRGB(in vec3 color) {return pow(color,vec3(1./2.2));} #ifdef BUILDING_FAUX_FACADE float hash12(in vec2 p) {vec3 p3 =fract(vec3(p.xyx)*0.1031);p3+=dot(p3,p3.yzx+33.33);return fract((p3.x+p3.y)*p3.z);}float min3(in vec3 v) {return min(min(v.x,v.y),v.z);}vec2 get_uv_mask_id(in vec2 q,out float mask,out vec2 id) {vec2 p=q;mask=step(v_faux_facade_range.x,p.y)*step(p.y,v_faux_facade_range.y);p.y=p.y-v_faux_facade_range.x;vec2 uv=modf(p/v_faux_facade_floor,id);vec4 d=(v_faux_facade_floor.xyxy+vec4(-v_faux_facade_window,v_faux_facade_window))*0.5;vec4 edge=d/v_faux_facade_floor.xyxy;vec2 m=step(edge.xy,uv)*step(uv,edge.zw);mask*=m.x*m.y;uv-=vec2(0.5);uv*=vec2(0.5)/(vec2(0.5)-edge.xy);uv+=vec2(0.5);return uv;}float ray_unit_box(in vec3 ray_o,in vec3 ray_d,in vec3 bmin,in vec3 bmax) {vec3 planes=mix(bmin,bmax,step(0.0,ray_d));vec3 t=(planes-ray_o)/ray_d;return min3(t);}float get_emissive(in vec2 id) {if (u_facade_emissive_chance > 0.0) {return (step(hash12(id),u_facade_emissive_chance)+0.05)*v_faux_color_emissive.a;}return 0.0;}vec3 get_shade_info(in vec3 v,in vec3 v_normalized,in vec3 color,in vec2 id,in mat3 tbn,inout vec3 out_normal,inout float out_emissive) {vec3 out_color=color;vec3 abs_v=abs(v_normalized);bool x_major=abs_v.x >=abs_v.y && abs_v.x >=abs_v.z;bool y_major=abs_v.y >=abs_v.x && abs_v.y >=abs_v.z;bool z_major=abs_v.z >=abs_v.x && abs_v.z >=abs_v.y; #if 0 if (x_major) {out_color=v.x > 0.0 ? vec3(1.0,0.0,0.0) : vec3(0.0,1.0,1.0);} else if (y_major) {out_color=v.y > 0.0 ? vec3(0.0,1.0,0.0) : vec3(1.0,0.0,1.0);} else if (z_major) {out_color=v.z > 0.0 ? vec3(0.0,0.0,1.0) : vec3(1.0,1.0,0.0);}out_emissive=1.0; #else if (x_major) {out_normal=sign(v.x)*tbn[0];} else if (y_major) {out_normal=vec3(0.0,0.0,-sign(v.y));} else if (z_major) {out_color=v_faux_color_emissive.rgb;out_emissive=v.z <=0.0 ? get_emissive(id) : out_emissive;}float ao=1.0;if (u_faux_facade_ao_intensity > 0.0) {vec4 ao_range=v_faux_facade_window.xxyy*0.5-vec4(0,ao_radius,0,ao_radius);vec2 ao_range_z=vec2(window_depth*0.5)-vec2(0.0,ao_radius);if (x_major || y_major) {ao*=smoothstep(-ao_range_z.x,-ao_range_z.y,v.z);} else if (z_major) {ao*=smoothstep(-ao_range.x,-ao_range.y,v.x)*(1.0-smoothstep(ao_range.y,ao_range.x,v.x));ao*=smoothstep(-ao_range.z,-ao_range.w,v.y)*(1.0-smoothstep(ao_range.w,ao_range.z,v.y));}ao=mix(1.0,min(1.0,ao+0.25),u_faux_facade_ao_intensity);}out_color*=ao; #endif return out_color;} #endif vec3 apply_lighting_linear(in vec3 color,in vec3 normal,in float dir_factor) {float ambient_directional_factor=calculate_ambient_directional_factor(normal);vec3 ambient_contrib=ambient_directional_factor*u_lighting_ambient_color;vec3 directional_contrib=u_lighting_directional_color*dir_factor;return color*(ambient_contrib+directional_contrib);}void main() {vec3 normal=normalize(v_normal);vec3 base_color=v_color.rgb;float emissive=v_color.a; #ifdef BUILDING_FAUX_FACADE if (v_faux_facade > 0.0) {mat3 tbn=mat3(v_tbn_0,v_tbn_1,v_tbn_2);vec3 v=vec3(v_pos.xy,v_pos.z/u_tile_to_meter)-u_camera_pos;vec3 view_tangent=transpose(tbn)*v;vec2 q=vec2(v_faux_facade_ed,v_pos.z);float mask=0.0;vec2 id=vec2(0.0);vec2 uv=get_uv_mask_id(q,mask,id);uv*=v_faux_facade_window;vec3 bmin=vec3(0.0,0.0,-window_depth);vec3 bmax=bmin+vec3(v_faux_facade_window,window_depth);vec3 ray_o=vec3(uv,0.0);vec3 ray_d=normalize(view_tangent);float t_min=ray_unit_box(ray_o,ray_d,bmin,bmax);vec3 hit=ray_o+t_min*ray_d;vec3 r=vec3(v_faux_facade_window,-window_depth);hit-=r*0.5;vec3 normalized=hit/r;vec3 out_normal=normal;float out_emissive=emissive;vec3 room_color=get_shade_info(hit,normalized,base_color,id,tbn,out_normal,out_emissive);base_color=mix(base_color,room_color,mask);normal=mix(normal,out_normal,mask);emissive=mix(emissive,out_emissive,mask);} #endif vec4 color=vec4(base_color,1.0);vec3 xy_flipped_normal=vec3(-normal.xy,normal.z);float shadowed_lighting_factor=0.0; #ifdef RENDER_SHADOWS #ifdef RENDER_CUTOFF shadowed_lighting_factor=shadowed_light_factor_normal_opacity(xy_flipped_normal,v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w,v_cutoff_opacity);if (v_cutoff_opacity==0.0) {discard;} #else shadowed_lighting_factor=shadowed_light_factor_normal(xy_flipped_normal,v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w); #endif #else shadowed_lighting_factor=dot(xy_flipped_normal,u_lighting_directional_dir); #endif color.rgb=apply_lighting_linear(color.rgb,xy_flipped_normal,shadowed_lighting_factor);color.rgb=linearTosRGB(color.rgb); #ifdef FLOOD_LIGHT float flood_radiance=(1.0-min(v_pos.z/v_flood_radius,1.0))*u_flood_light_intensity*v_has_flood_light;color.rgb=mix(color.rgb,u_flood_light_color,flood_radiance); #endif color.rgb=mix(color.rgb,linearTosRGB(base_color.rgb),emissive); #ifdef FOG color=fog_dither(fog_apply_premultiplied(color,v_fog_pos,v_pos.z)); #endif color*=u_opacity; #ifdef INDICATOR_CUTOUT color=applyCutout(color,v_pos.z); #endif #ifdef FEATURE_CUTOUT color=apply_feature_cutout(color,gl_FragCoord); #endif glFragColor=color; #ifdef DEBUG_SHOW_NORMALS color.rgb=xy_flipped_normal*0.5+vec3(0.5,0.5,0.5);color.a=1.0;glFragColor=color; #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_shadow.vertex.glsl" in vec3 a_pos_3f;in vec3 a_normal_3;in vec3 a_centroid_3;in float a_flood_light_wall_radius_1i16;in vec4 a_faux_facade_data;in vec2 a_faux_facade_vertical_range;uniform mat4 u_matrix;uniform mat4 u_normal_matrix;uniform highp float u_tile_to_meter;out vec4 v_color;out vec3 v_normal;out highp vec3 v_pos; #ifdef BUILDING_FAUX_FACADE out lowp float v_faux_facade;out highp float v_faux_facade_ed;out highp vec2 v_faux_facade_window;out highp vec2 v_faux_facade_floor;out highp vec2 v_faux_facade_range;out highp float v_aspect;out highp vec3 v_tbn_0;out highp vec3 v_tbn_1;out highp vec3 v_tbn_2;out highp vec4 v_faux_color_emissive; #endif #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1; #endif #ifdef FLOOD_LIGHT out highp float v_flood_radius;out float v_has_flood_light; #endif const float MAX_UINT_16=65535.0;const float MAX_INT_16=32767.0;const float MAX_UINT_8=255.0;const float TWO_POW_8=256.0;const float FLOOD_LIGHT_MAX_RADIUS_METER=2048.0;vec3 sRGBToLinear(vec3 srgbIn) {return pow(srgbIn,vec3(2.2));} #ifdef BUILDING_FAUX_FACADE mat3 get_tbn(in vec3 normal) {const vec3 bitangent=vec3(0.0,0.0,1.0);vec3 tangent=normalize(vec3(normal.y,-normal.x,0.0));return mat3(tangent,bitangent,normal);} #endif #pragma mapbox: define-attribute-vertex-shader-only highp vec2 part_color_emissive #pragma mapbox: define-attribute-vertex-shader-only highp vec2 faux_facade_color_emissive void main() { #pragma mapbox: initialize-attribute-custom highp vec2 part_color_emissive #pragma mapbox: initialize-attribute-custom highp vec2 faux_facade_color_emissive #ifdef FLOOD_LIGHT v_flood_radius=(a_flood_light_wall_radius_1i16/MAX_INT_16*FLOOD_LIGHT_MAX_RADIUS_METER);v_has_flood_light=step(0.0,v_flood_radius); #endif vec4 color_emissive=decode_color(part_color_emissive);v_color=vec4(sRGBToLinear(color_emissive.rgb),color_emissive.a);vec3 a_normal_3f=a_normal_3/MAX_INT_16;v_normal=vec3(u_normal_matrix*vec4(a_normal_3f,0.0));float hidden=0.0;float depth_offset=0.0; #ifdef BUILDING_FAUX_FACADE v_faux_facade=a_faux_facade_data.x;if (v_faux_facade > 0.0) {v_faux_facade_ed=a_faux_facade_data.x *u_tile_to_meter;float window_x_perc=floor(a_faux_facade_data.y/TWO_POW_8);float window_y_perc=a_faux_facade_data.y-TWO_POW_8*window_x_perc;vec2 window_perc=vec2(window_x_perc,window_y_perc)/MAX_UINT_8;v_faux_facade_floor=(a_faux_facade_data.zw/MAX_UINT_16*EXTENT)*u_tile_to_meter;v_faux_facade_window=window_perc*v_faux_facade_floor;v_faux_facade_range=(a_faux_facade_vertical_range/MAX_UINT_16*EXTENT)*u_tile_to_meter;v_aspect=v_faux_facade_window.x/v_faux_facade_window.y;mat3 tbn=get_tbn(normalize(v_normal));v_tbn_0=tbn[0];v_tbn_1=tbn[1];v_tbn_2=tbn[2];v_faux_color_emissive=decode_color(faux_facade_color_emissive);v_faux_color_emissive.rgb=sRGBToLinear(v_faux_color_emissive.rgb);float height=a_centroid_3.z;depth_offset=min(1000.0,height)*0.0000002;} #endif v_pos=a_pos_3f; #ifdef RENDER_CUTOFF vec4 ground=u_matrix*vec4(a_centroid_3,1.0);v_cutoff_opacity=cutoff_opacity(u_cutoff_params,ground.z);hidden=float(v_cutoff_opacity==0.0);v_pos.z*=v_cutoff_opacity; #endif #ifdef RENDER_SHADOWS vec3 shadow_pos=v_pos; #ifdef NORMAL_OFFSET vec3 offset=shadow_normal_offset_model(v_normal);shadow_pos+=offset*shadow_normal_offset_multiplier0(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shadow_pos,1.0);v_pos_light_view_1=u_light_matrix_1*vec4(shadow_pos,1.0); #endif #ifdef FOG v_fog_pos=fog_position(v_pos); #endif gl_Position=mix(u_matrix*vec4(v_pos,1),AWAY,hidden);gl_Position.z-=depth_offset*gl_Position.w;}`),buildingBloom:ps(`in vec4 v_color_emissive; #pragma mapbox: define-attribute highp vec4 bloom_attenuation #pragma mapbox: initialize-attribute highp vec4 bloom_attenuation float saturate(float val) {return clamp(val,0.0,1.0);}void main() {float emission=v_color_emissive.a;float opacity=1.0; #ifdef HAS_ATTRIBUTE_a_bloom_attenuation float distance=length(vec2(1.3*max(0.0,abs(bloom_attenuation.x)-bloom_attenuation.z),bloom_attenuation.y));distance+= mix(0.5,0.0,clamp(emission-1.0,0.0,1.0));opacity*=saturate(1.0-distance*distance); #endif #ifdef RENDER_CUTOFF opacity*=v_cutoff_opacity; #endif glFragColor=vec4(v_color_emissive.rgb,1.0)*opacity;}`,`in vec3 a_pos_3f; #pragma mapbox: define-attribute-vertex-shader-only highp vec2 part_color_emissive #pragma mapbox: define-attribute highp vec4 bloom_attenuation out vec4 v_color_emissive;uniform mat4 u_matrix;vec3 sRGBToLinear(vec3 srgbIn) {return pow(srgbIn,vec3(2.2));}void main() { #pragma mapbox: initialize-attribute-custom highp vec2 part_color_emissive #pragma mapbox: initialize-attribute highp vec4 bloom_attenuation #ifdef HAS_ATTRIBUTE_a_part_color_emissive vec4 color_emissive=decode_color(part_color_emissive);float part_emissive=color_emissive.a*5.0;v_color_emissive=vec4(sRGBToLinear(color_emissive.rgb),part_emissive); #else v_color_emissive=vec4(1.0); #endif gl_Position=u_matrix*vec4(a_pos_3f,1.0); #ifdef RENDER_CUTOFF v_cutoff_opacity=cutoff_opacity(u_cutoff_params,gl_Position.z); #endif }`),buildingDepth:ps(`in highp float v_depth;void main() { #ifndef DEPTH_TEXTURE glFragColor=pack_depth(v_depth); #endif }`,"in vec3 a_pos_3f;uniform mat4 u_matrix;out highp float v_depth;void main() {gl_Position=u_matrix*vec4(a_pos_3f,1.0);v_depth=gl_Position.z/gl_Position.w;}"),circle:ps(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" in vec3 v_data;in float v_visibility; #pragma mapbox: define highp vec4 color #pragma mapbox: define mediump float radius #pragma mapbox: define lowp float blur #pragma mapbox: define lowp float opacity #pragma mapbox: define highp vec4 stroke_color #pragma mapbox: define mediump float stroke_width #pragma mapbox: define lowp float stroke_opacity uniform float u_emissive_strength;void main() { #pragma mapbox: initialize highp vec4 color #pragma mapbox: initialize mediump float radius #pragma mapbox: initialize lowp float blur #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize highp vec4 stroke_color #pragma mapbox: initialize mediump float stroke_width #pragma mapbox: initialize lowp float stroke_opacity vec2 extrude=v_data.xy;float blur_positive=blur < 0.0 ? 0.0 : 1.0;lowp float antialiasblur=v_data.z;float extrude_length=length(extrude)+antialiasblur*(1.0-blur_positive);float antialiased_blur=-max(abs(blur),antialiasblur);float antialiase_blur_opacity=smoothstep(0.0,antialiasblur,extrude_length-1.0);float opacity_t=blur_positive==1.0 ? smoothstep(0.0,-antialiased_blur,1.0-extrude_length) : smoothstep(antialiased_blur,0.0,extrude_length-1.0)-antialiase_blur_opacity;float color_t=stroke_width < 0.01 ? 0.0 : smoothstep( antialiased_blur,0.0,extrude_length-radius/(radius+stroke_width) );vec4 out_color=mix(color*opacity,stroke_color*stroke_opacity,color_t); #ifdef LIGHTING_3D_MODE out_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength); #endif #ifdef FOG out_color=fog_apply_premultiplied(out_color,v_fog_pos); #endif glFragColor=out_color*(v_visibility*opacity_t); #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif }`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_terrain.vertex.glsl" #define NUM_VISIBILITY_RINGS 2 #define INV_SQRT2 0.70710678 #define ELEVATION_BIAS 0.0001 #define NUM_SAMPLES_PER_RING 16 uniform mat4 u_matrix;uniform mat2 u_extrude_scale;uniform lowp float u_device_pixel_ratio;uniform highp float u_camera_to_center_distance;in vec2 a_pos; #ifdef PROJECTION_GLOBE_VIEW in vec3 a_pos_3;in vec3 a_pos_normal_3;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform vec3 u_tile_id;uniform float u_zoom_transition;uniform vec3 u_up_dir; #endif #ifdef ELEVATED_ROADS in float a_circle_z_offset; #endif out vec3 v_data;out float v_visibility; #pragma mapbox: define highp vec4 color #pragma mapbox: define mediump float radius #pragma mapbox: define lowp float blur #pragma mapbox: define lowp float opacity #pragma mapbox: define highp vec4 stroke_color #pragma mapbox: define mediump float stroke_width #pragma mapbox: define lowp float stroke_opacity vec2 calc_offset(vec2 extrusion,float radius,float stroke_width, float view_scale) {return extrusion*(radius+stroke_width)*u_extrude_scale*view_scale;}float cantilevered_elevation(vec2 pos,float radius,float stroke_width,float view_scale) {vec2 c1=pos+calc_offset(vec2(-1,-1),radius,stroke_width,view_scale);vec2 c2=pos+calc_offset(vec2(1,-1),radius,stroke_width,view_scale);vec2 c3=pos+calc_offset(vec2(1,1),radius,stroke_width,view_scale);vec2 c4=pos+calc_offset(vec2(-1,1),radius,stroke_width,view_scale);float h1=elevation(c1)+ELEVATION_BIAS;float h2=elevation(c2)+ELEVATION_BIAS;float h3=elevation(c3)+ELEVATION_BIAS;float h4=elevation(c4)+ELEVATION_BIAS;return max(h4,max(h3,max(h1,h2)));}float circle_elevation(vec2 pos) { #if defined(TERRAIN) return elevation(pos)+ELEVATION_BIAS; #else return 0.0; #endif }vec4 project_vertex(vec2 extrusion,vec4 world_center,vec4 projected_center,float radius,float stroke_width, float view_scale,mat3 surface_vectors) {vec2 sample_offset=calc_offset(extrusion,radius,stroke_width,view_scale); #ifdef PITCH_WITH_MAP #ifdef PROJECTION_GLOBE_VIEW return u_matrix*( world_center+vec4(sample_offset.x*surface_vectors[0]+sample_offset.y*surface_vectors[1],0) ); #else return u_matrix*( world_center+vec4(sample_offset,0,0) ); #endif #else return projected_center+vec4(sample_offset,0,0); #endif }float get_sample_step() { #ifdef PITCH_WITH_MAP return 2.0*PI/float(NUM_SAMPLES_PER_RING); #else return PI/float(NUM_SAMPLES_PER_RING); #endif }void main() { #pragma mapbox: initialize highp vec4 color #pragma mapbox: initialize mediump float radius #pragma mapbox: initialize lowp float blur #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize highp vec4 stroke_color #pragma mapbox: initialize mediump float stroke_width #pragma mapbox: initialize lowp float stroke_opacity vec2 extrude=vec2(mod(a_pos,2.0)*2.0-1.0);vec2 circle_center=floor(a_pos*0.5);vec4 world_center;mat3 surface_vectors; #ifdef PROJECTION_GLOBE_VIEW vec3 pos_normal_3=a_pos_normal_3/16384.0;surface_vectors=globe_mercator_surface_vectors(pos_normal_3,u_up_dir,u_zoom_transition);vec3 surface_extrusion=extrude.x*surface_vectors[0]+extrude.y*surface_vectors[1];vec3 globe_elevation=elevationVector(circle_center)*circle_elevation(circle_center);vec3 globe_pos=a_pos_3+surface_extrusion+globe_elevation;vec3 mercator_elevation=u_up_dir*u_tile_up_scale*circle_elevation(circle_center);vec3 merc_pos=mercator_tile_position(u_inv_rot_matrix,circle_center,u_tile_id,u_merc_center)+surface_extrusion+mercator_elevation;vec3 pos=mix_globe_mercator(globe_pos,merc_pos,u_zoom_transition);world_center=vec4(pos,1); #else surface_vectors=mat3(1.0);float height=circle_elevation(circle_center);world_center=vec4(circle_center,height,1); #endif #ifdef ELEVATED_ROADS world_center.z+=a_circle_z_offset+ELEVATION_BIAS; #endif vec4 projected_center=u_matrix*world_center;float view_scale=0.0; #ifdef PITCH_WITH_MAP #ifdef SCALE_WITH_MAP view_scale=1.0; #else view_scale=projected_center.w/u_camera_to_center_distance; #endif #else #ifdef SCALE_WITH_MAP view_scale=u_camera_to_center_distance; #else view_scale=projected_center.w; #endif #endif gl_Position=project_vertex(extrude,world_center,projected_center,radius,stroke_width,view_scale,surface_vectors);float visibility=0.0; #ifdef TERRAIN float step=get_sample_step();vec4 occlusion_world_center;vec4 occlusion_projected_center; #ifdef PITCH_WITH_MAP float cantilevered_height=cantilevered_elevation(circle_center,radius,stroke_width,view_scale);occlusion_world_center=vec4(circle_center,cantilevered_height,1);occlusion_projected_center=u_matrix*occlusion_world_center; #else occlusion_world_center=world_center;occlusion_projected_center=projected_center; #endif for(int ring=0; ring < NUM_VISIBILITY_RINGS; ring++) {float scale=(float(ring)+1.0)/float(NUM_VISIBILITY_RINGS);for(int i=0; i < NUM_SAMPLES_PER_RING; i++) {vec2 extrusion=vec2(cos(step*float(i)),-sin(step*float(i)))*scale;vec4 frag_pos=project_vertex(extrusion,occlusion_world_center,occlusion_projected_center,radius,stroke_width,view_scale,surface_vectors);visibility+=float(!isOccluded(frag_pos));}}visibility/=float(NUM_VISIBILITY_RINGS)*float(NUM_SAMPLES_PER_RING); #else visibility=1.0; #endif #ifdef PROJECTION_GLOBE_VIEW visibility=1.0; #endif v_visibility=visibility;lowp float antialiasblur=1.0/u_device_pixel_ratio/(radius+stroke_width);v_data=vec3(extrude.x,extrude.y,antialiasblur); #ifdef FOG v_fog_pos=fog_position(world_center.xyz); #endif }`),clippingMask:ps("void main() {glFragColor=vec4(1.0);}","in vec2 a_pos;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);}"),heatmap:ps(`#include "_prelude_fog.fragment.glsl" uniform highp float u_intensity;in vec2 v_extrude; #pragma mapbox: define highp float weight #define GAUSS_COEF 0.3989422804014327 void main() { #pragma mapbox: initialize highp float weight float d=-0.5*3.0*3.0*dot(v_extrude,v_extrude);float val=weight*u_intensity*GAUSS_COEF*exp(d);glFragColor=vec4(val,1.0,1.0,1.0); #ifdef FOG if (u_is_globe==0) {glFragColor.r*=pow(1.0-fog_opacity(v_fog_pos),2.0);} #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_terrain.vertex.glsl" #include "_prelude_fog.vertex.glsl" uniform mat4 u_matrix;uniform float u_extrude_scale;uniform float u_opacity;uniform float u_intensity;in vec2 a_pos; #ifdef PROJECTION_GLOBE_VIEW in vec3 a_pos_3;in vec3 a_pos_normal_3;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform vec3 u_tile_id;uniform float u_zoom_transition;uniform vec3 u_up_dir; #endif out vec2 v_extrude; #pragma mapbox: define highp float weight #pragma mapbox: define mediump float radius const highp float ZERO=1.0/255.0/16.0; #define GAUSS_COEF 0.3989422804014327 void main() { #pragma mapbox: initialize highp float weight #pragma mapbox: initialize mediump float radius vec2 unscaled_extrude=vec2(mod(a_pos,2.0)*2.0-1.0);float S=sqrt(-2.0*log(ZERO/weight/u_intensity/GAUSS_COEF))/3.0;v_extrude=S*unscaled_extrude;vec2 extrude=v_extrude*radius*u_extrude_scale;vec2 tilePos=floor(a_pos*0.5);vec3 pos; #ifdef PROJECTION_GLOBE_VIEW vec3 pos_normal_3=a_pos_normal_3/16384.0;mat3 surface_vectors=globe_mercator_surface_vectors(pos_normal_3,u_up_dir,u_zoom_transition);vec3 surface_extrusion=extrude.x*surface_vectors[0]+extrude.y*surface_vectors[1];vec3 globe_elevation=elevationVector(tilePos)*elevation(tilePos);vec3 globe_pos=a_pos_3+surface_extrusion+globe_elevation;vec3 mercator_elevation=u_up_dir*u_tile_up_scale*elevation(tilePos);vec3 merc_pos=mercator_tile_position(u_inv_rot_matrix,tilePos,u_tile_id,u_merc_center)+surface_extrusion+mercator_elevation;pos=mix_globe_mercator(globe_pos,merc_pos,u_zoom_transition); #else pos=vec3(tilePos+extrude,elevation(tilePos)); #endif gl_Position=u_matrix*vec4(pos,1); #ifdef FOG v_fog_pos=fog_position(pos); #endif }`),heatmapTexture:ps(`uniform sampler2D u_image;uniform sampler2D u_color_ramp;uniform float u_opacity;in vec2 v_pos;void main() {float t=texture(u_image,v_pos).r;vec4 color=texture(u_color_ramp,vec2(t,0.5));glFragColor=color*u_opacity; #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(0.0); #endif HANDLE_WIREFRAME_DEBUG;}`,"in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=vec4(a_pos,0,1);v_pos=a_pos*0.5+0.5;}"),collisionBox:ps("in float v_placed;in float v_notUsed;void main() {vec4 red =vec4(1.0,0.0,0.0,1.0);vec4 blue=vec4(0.0,0.0,1.0,0.5);glFragColor =mix(red,blue,step(0.5,v_placed))*0.5;glFragColor*=mix(1.0,0.1,step(0.5,v_notUsed));}",`#include "_prelude_terrain.vertex.glsl" in vec3 a_pos;in vec2 a_anchor_pos;in vec2 a_extrude;in vec2 a_placed;in vec2 a_shift;in vec2 a_elevation_from_sea;in float a_size_scale;in vec2 a_padding;in float a_auto_z_offset;uniform mat4 u_matrix;uniform vec2 u_extrude_scale;uniform float u_camera_to_center_distance; #ifdef PROJECTION_GLOBE_VIEW uniform vec3 u_tile_id;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform float u_zoom_transition; #endif out float v_placed;out float v_notUsed;void main() {float feature_elevation=a_elevation_from_sea.x+a_auto_z_offset;float terrain_elevation=(a_elevation_from_sea.y==1.0 ? 0.0 : elevation(a_anchor_pos));vec3 proj_pos=a_pos+elevationVector(a_anchor_pos)*(feature_elevation+terrain_elevation); #ifdef PROJECTION_GLOBE_VIEW #ifndef PROJECTED_POS_ON_VIEWPORT vec3 globe_pos=proj_pos;vec3 mercator_pos=mercator_tile_position(u_inv_rot_matrix,a_anchor_pos,u_tile_id,u_merc_center);proj_pos=mix_globe_mercator(globe_pos,mercator_pos,u_zoom_transition); #endif #endif vec4 projectedPoint=u_matrix*vec4(proj_pos,1);highp float camera_to_anchor_distance=projectedPoint.w;highp float collision_perspective_ratio=clamp( 0.5+0.5*(u_camera_to_center_distance/camera_to_anchor_distance),0.0,1.5);gl_Position=projectedPoint;gl_Position.xy+=(a_extrude*a_size_scale+a_shift+a_padding)*u_extrude_scale*gl_Position.w*collision_perspective_ratio;v_placed=a_placed.x;v_notUsed=a_placed.y;}`),collisionCircle:ps("in float v_radius;in vec2 v_extrude;in float v_perspective_ratio;in float v_collision;void main() {float alpha=0.5*min(v_perspective_ratio,1.0);float stroke_radius=0.9*max(v_perspective_ratio,1.0);float distance_to_center=length(v_extrude);float distance_to_edge=abs(distance_to_center-v_radius);float opacity_t=smoothstep(-stroke_radius,0.0,-distance_to_edge);vec4 color=mix(vec4(0.0,0.0,1.0,0.5),vec4(1.0,0.0,0.0,1.0),v_collision);glFragColor=color*alpha*opacity_t;}",`in vec2 a_pos_2f;in float a_radius;in vec2 a_flags;uniform mat4 u_matrix;uniform mat4 u_inv_matrix;uniform vec2 u_viewport_size;uniform float u_camera_to_center_distance;out float v_radius;out vec2 v_extrude;out float v_perspective_ratio;out float v_collision;vec3 toTilePosition(vec2 screenPos) {vec4 rayStart=u_inv_matrix*vec4(screenPos,-1.0,1.0);vec4 rayEnd =u_inv_matrix*vec4(screenPos, 1.0,1.0);rayStart.xyz/=rayStart.w;rayEnd.xyz /=rayEnd.w;highp float t=(0.0-rayStart.z)/(rayEnd.z-rayStart.z);return mix(rayStart.xyz,rayEnd.xyz,t);}void main() {vec2 quadCenterPos=a_pos_2f;float radius=a_radius;float collision=a_flags.x;float vertexIdx=a_flags.y;vec2 quadVertexOffset=vec2( mix(-1.0,1.0,float(vertexIdx >=2.0)),mix(-1.0,1.0,float(vertexIdx >=1.0 && vertexIdx <=2.0)));vec2 quadVertexExtent=quadVertexOffset*radius;vec3 tilePos=toTilePosition(quadCenterPos);vec4 clipPos=u_matrix*vec4(tilePos,1.0);highp float camera_to_anchor_distance=clipPos.w;highp float collision_perspective_ratio=clamp( 0.5+0.5*(u_camera_to_center_distance/camera_to_anchor_distance),0.0,4.0);float padding_factor=1.2;v_radius=radius;v_extrude=quadVertexExtent*padding_factor;v_perspective_ratio=collision_perspective_ratio;v_collision=collision;gl_Position=vec4(clipPos.xyz/clipPos.w,1.0)+vec4(quadVertexExtent*padding_factor/u_viewport_size*2.0,0.0,0.0);}`),debug:ps("uniform highp vec4 u_color;uniform sampler2D u_overlay;in vec2 v_uv;void main() {vec4 overlay_color=texture(u_overlay,v_uv);glFragColor=mix(u_color,overlay_color,overlay_color.a);}",`#include "_prelude_terrain.vertex.glsl" in vec2 a_pos; #ifdef PROJECTION_GLOBE_VIEW in vec3 a_pos_3; #endif out vec2 v_uv;uniform mat4 u_matrix;uniform float u_overlay_scale;void main() {float h=elevation(a_pos);v_uv=a_pos/8192.0; #ifdef PROJECTION_GLOBE_VIEW gl_Position=u_matrix*vec4(a_pos_3+elevationVector(a_pos)*h,1); #else gl_Position=u_matrix*vec4(a_pos*u_overlay_scale,h,1); #endif }`),elevatedStructuresDepth:ps(`void main() { #ifndef DEPTH_TEXTURE glFragColor=vec4(0.); #endif }`,"in vec2 a_pos;in float a_height;uniform mat4 u_matrix;uniform float u_depth_bias;void main() {gl_Position=u_matrix*vec4(a_pos,a_height,1);gl_Position.z=gl_Position.z+u_depth_bias;}"),elevatedStructuresDepthReconstruct:ps(`#ifdef DEPTH_RECONSTRUCTION in float v_height; #endif void main() { #ifdef DEPTH_RECONSTRUCTION if (v_height >=0.0) discard; #else #ifdef FEATURE_CUTOUT apply_feature_cutout(vec4(0.0,0.0,0.0,1.0),gl_FragCoord); #endif #endif glFragColor=vec4(1.0,0.0,0.0,1.0);}`,`in vec2 a_pos;in float a_height;uniform mat4 u_matrix;uniform vec3 u_camera_pos;uniform highp float u_depth_bias;uniform lowp float u_height_scale;uniform lowp float u_reset_depth; #ifdef DEPTH_RECONSTRUCTION out float v_height; #endif void main() {vec3 vpos=vec3(a_pos,a_height*u_height_scale); #ifdef DEPTH_RECONSTRUCTION if (u_camera_pos.z > vpos.z) {vpos-=(u_camera_pos-vpos)*(vpos.z/(u_camera_pos.z-vpos.z));}v_height=a_height; #endif gl_Position=u_matrix*vec4(vpos,1);gl_Position.z=u_reset_depth==1.0 ? gl_Position.w : gl_Position.z+u_depth_bias;}`),elevatedStructures:ps(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" in vec3 v_normal;in float v_height; #ifdef RENDER_SHADOWS in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in float v_depth; #endif vec3 linearTosRGB(vec3 color) {return pow(color,vec3(1./2.2));}vec3 sRGBToLinear(vec3 srgbIn) {return pow(srgbIn,vec3(2.2));}vec3 compute_view_dependent_emissive_color(float ndotl,float emissive_strength,vec3 color) {color=sRGBToLinear(color);color=color*(ndotl+(1.0-min(ndotl*57.29,1.0))*emissive_strength);color=linearTosRGB(color.rgb);return color;}uniform float u_emissive_strength; #pragma mapbox: define highp vec4 structure_color void main() { #pragma mapbox: initialize highp vec4 structure_color vec3 color=structure_color.xyz; #ifdef LIGHTING_3D_MODE vec3 normal=normalize(v_normal);vec3 transformed_normal=vec3(-normal.xy,normal.z);float ndotl=calculate_NdotL(transformed_normal);float emissive_strength=u_emissive_strength;emissive_strength=0.0;vec3 emissive_color=compute_view_dependent_emissive_color(ndotl,emissive_strength,color.xyz); #ifdef RENDER_SHADOWS float shadowed_lighting_factor=shadowed_light_factor_normal(transformed_normal,v_pos_light_view_0,v_pos_light_view_1,v_depth);color.rgb=apply_lighting(color.rgb,transformed_normal,shadowed_lighting_factor); #else color=apply_lighting(color,transformed_normal); #endif color=mix(color,emissive_color,emissive_strength);if (v_height < 0.0) {float penetration=max(v_height+7.5,0.0);float occlusion=1.0-1.0/PI*acos(1.0-penetration/4.0);color=color*(1.0-pow(occlusion,2.0)*0.3);} #endif #ifdef FOG color=fog_apply(color,v_fog_pos); #endif vec4 out_color=vec4(color,1.0); #ifdef INDICATOR_CUTOUT out_color=applyCutout(out_color,v_height); #endif #ifdef FEATURE_CUTOUT out_color=apply_feature_cutout(out_color,gl_FragCoord); #endif glFragColor=out_color;HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_shadow.vertex.glsl" in vec2 a_pos;in float a_height;in vec3 a_pos_normal_3;uniform mat4 u_matrix;out vec3 v_normal;out float v_height; #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out float v_depth; #endif #pragma mapbox: define highp vec4 structure_color void main() { #pragma mapbox: initialize highp vec4 structure_color v_normal=a_pos_normal_3/16384.0;v_height=a_height;vec3 pos=vec3(a_pos,a_height);gl_Position=u_matrix*vec4(pos,1); #ifdef RENDER_SHADOWS vec3 shd_pos0=pos;vec3 shd_pos1=pos; #ifdef NORMAL_OFFSET vec3 offset=shadow_normal_offset(vec3(-v_normal.xy,v_normal.z));shd_pos0+=offset*shadow_normal_offset_multiplier0();shd_pos1+=offset*shadow_normal_offset_multiplier1(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w; #endif #ifdef FOG v_fog_pos=fog_position(a_pos); #endif }`),fill:ps(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" #pragma mapbox: define highp vec4 color #pragma mapbox: define lowp float opacity uniform float u_emissive_strength; #ifdef RENDER_SHADOWS uniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth; #endif #ifdef ELEVATED_ROADS in highp float v_road_z_offset; #endif #ifdef INDICATOR_CUTOUT in highp float v_z_offset; #endif void main() { #pragma mapbox: initialize highp vec4 color #pragma mapbox: initialize lowp float opacity vec4 out_color=color; #ifdef LIGHTING_3D_MODE out_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength); #ifdef RENDER_SHADOWS float light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth);out_color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light); #endif #endif #ifdef FOG out_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos)); #endif out_color*=opacity; #ifdef INDICATOR_CUTOUT if (v_z_offset >=0.0) {out_color=applyCutout(out_color,v_z_offset);} #endif #ifdef FEATURE_CUTOUT out_color=apply_feature_cutout(out_color,gl_FragCoord); #endif glFragColor=out_color; #ifdef USE_MRT1 out_Target1=vec4(u_emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a); #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_shadow.vertex.glsl" in vec2 a_pos; #ifdef ELEVATED_ROADS in float a_road_z_offset;out highp float v_road_z_offset; #endif #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth; #endif #ifdef INDICATOR_CUTOUT out highp float v_z_offset; #endif uniform mat4 u_matrix; #pragma mapbox: define highp vec4 color #pragma mapbox: define lowp float opacity #pragma mapbox: define highp float z_offset void main() { #pragma mapbox: initialize highp vec4 color #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize highp float z_offset #ifdef ELEVATED_ROADS z_offset+=a_road_z_offset;v_road_z_offset=z_offset; #endif float hidden=float(opacity==0.0);gl_Position=mix(u_matrix*vec4(a_pos,z_offset,1),AWAY,hidden); #ifdef RENDER_SHADOWS vec3 shd_pos0=vec3(a_pos,z_offset);vec3 shd_pos1=vec3(a_pos,z_offset); #ifdef NORMAL_OFFSET vec3 offset=shadow_normal_offset(vec3(0.0,0.0,1.0));shd_pos0+=offset*shadow_normal_offset_multiplier0();shd_pos1+=offset*shadow_normal_offset_multiplier1(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w; #endif #ifdef FOG v_fog_pos=fog_position(a_pos); #endif #ifdef INDICATOR_CUTOUT v_z_offset=z_offset; #endif }`),fillOutline:ps(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" in highp vec2 v_pos;uniform float u_emissive_strength; #ifdef RENDER_SHADOWS uniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth; #endif #pragma mapbox: define highp vec4 outline_color #pragma mapbox: define lowp float opacity void main() { #pragma mapbox: initialize highp vec4 outline_color #pragma mapbox: initialize lowp float opacity float dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);vec4 out_color=outline_color; #ifdef LIGHTING_3D_MODE out_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength); #ifdef RENDER_SHADOWS float light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth);out_color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light); #endif #endif #ifdef FOG out_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos)); #endif #ifdef FEATURE_CUTOUT out_color=apply_feature_cutout(out_color,gl_FragCoord); #endif glFragColor=out_color*(alpha*opacity); #ifdef USE_MRT1 out_Target1=vec4(u_emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a); #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_shadow.vertex.glsl" in vec2 a_pos; #ifdef ELEVATED_ROADS in float a_road_z_offset; #endif #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth; #endif uniform mat4 u_matrix;uniform vec2 u_world;out highp vec2 v_pos; #pragma mapbox: define highp vec4 outline_color #pragma mapbox: define lowp float opacity #pragma mapbox: define highp float z_offset void main() { #pragma mapbox: initialize highp vec4 outline_color #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize highp float z_offset #ifdef ELEVATED_ROADS z_offset+=a_road_z_offset; #endif float hidden=float(opacity==0.0);gl_Position=mix(u_matrix*vec4(a_pos,z_offset,1),AWAY,hidden); #ifdef FLIP_Y v_pos=(vec2(gl_Position.x,-gl_Position.y)/gl_Position.w+1.0)/2.0*u_world; #else v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world; #endif #ifdef RENDER_SHADOWS vec3 shd_pos0=vec3(a_pos,z_offset);vec3 shd_pos1=vec3(a_pos,z_offset); #ifdef NORMAL_OFFSET vec3 offset=shadow_normal_offset(vec3(0.0,0.0,1.0));shd_pos0+=offset*shadow_normal_offset_multiplier0();shd_pos1+=offset*shadow_normal_offset_multiplier1(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w; #endif #ifdef FOG v_fog_pos=fog_position(a_pos); #endif }`),fillOutlinePattern:ps(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" uniform vec2 u_texsize;uniform sampler2D u_image; #ifdef FILL_PATTERN_TRANSITION uniform float u_pattern_transition; #endif uniform float u_emissive_strength; #ifdef APPLY_LUT_ON_GPU uniform highp sampler3D u_lutTexture; #endif #ifdef RENDER_SHADOWS uniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth; #endif in highp vec2 v_pos;in highp vec2 v_pos_world; #pragma mapbox: define lowp float opacity #pragma mapbox: define lowp vec4 pattern #ifdef FILL_PATTERN_TRANSITION #pragma mapbox: define mediump vec4 pattern_b #endif void main() { #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize mediump vec4 pattern #ifdef FILL_PATTERN_TRANSITION #pragma mapbox: initialize mediump vec4 pattern_b #endif vec2 pattern_tl=pattern.xy;vec2 pattern_br=pattern.zw;highp vec2 imagecoord=mod(v_pos,1.0);highp vec2 pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,imagecoord);highp vec2 lod_pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,v_pos);float dist=length(v_pos_world-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);vec4 out_color=textureLodCustom(u_image,pos,lod_pos); #ifdef APPLY_LUT_ON_GPU out_color=applyLUT(u_lutTexture,out_color); #endif #ifdef FILL_PATTERN_TRANSITION vec2 pattern_b_tl=pattern_b.xy;vec2 pattern_b_br=pattern_b.zw;highp vec2 pos_b=mix(pattern_b_tl/u_texsize,pattern_b_br/u_texsize,imagecoord);vec4 color_b=textureLodCustom(u_image,pos_b,lod_pos);out_color=out_color*(1.0-u_pattern_transition)+color_b*u_pattern_transition; #endif #ifdef LIGHTING_3D_MODE out_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength); #ifdef RENDER_SHADOWS float light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth);out_color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light); #endif #endif #ifdef FEATURE_CUTOUT out_color=apply_feature_cutout(out_color,gl_FragCoord); #endif #ifdef FOG out_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos)); #endif glFragColor=out_color*(alpha*opacity); #ifdef USE_MRT1 out_Target1=vec4(u_emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a); #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_shadow.vertex.glsl" uniform mat4 u_matrix;uniform vec2 u_world;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_tile_units_to_pixels;in vec2 a_pos; #ifdef ELEVATED_ROADS in float a_road_z_offset; #endif #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth; #endif out highp vec2 v_pos;out highp vec2 v_pos_world; #pragma mapbox: define lowp float opacity #pragma mapbox: define lowp vec4 pattern #ifdef FILL_PATTERN_TRANSITION #pragma mapbox: define mediump vec4 pattern_b #endif #pragma mapbox: define lowp float pixel_ratio #pragma mapbox: define highp float z_offset void main() { #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize mediump vec4 pattern #ifdef FILL_PATTERN_TRANSITION #pragma mapbox: initialize mediump vec4 pattern_b #endif #pragma mapbox: initialize lowp float pixel_ratio #pragma mapbox: initialize highp float z_offset vec2 pattern_tl=pattern.xy;vec2 pattern_br=pattern.zw; #ifdef ELEVATED_ROADS z_offset+=a_road_z_offset; #endif float hidden=float(opacity==0.0);gl_Position=mix(u_matrix*vec4(a_pos,z_offset,1),AWAY,hidden);vec2 display_size=(pattern_br-pattern_tl)/pixel_ratio;v_pos=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,display_size,u_tile_units_to_pixels,a_pos); #ifdef FLIP_Y v_pos_world=(vec2(gl_Position.x,-gl_Position.y)/gl_Position.w+1.0)/2.0*u_world; #else v_pos_world=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world; #endif #ifdef RENDER_SHADOWS vec3 shd_pos0=vec3(a_pos,z_offset);vec3 shd_pos1=vec3(a_pos,z_offset); #ifdef NORMAL_OFFSET vec3 offset=shadow_normal_offset(vec3(0.0,0.0,1.0));shd_pos0+=offset*shadow_normal_offset_multiplier0();shd_pos1+=offset*shadow_normal_offset_multiplier1(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w; #endif #ifdef FOG v_fog_pos=fog_position(a_pos); #endif }`),fillPattern:ps(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" uniform vec2 u_texsize;uniform sampler2D u_image; #ifdef FILL_PATTERN_TRANSITION uniform float u_pattern_transition; #endif in highp vec2 v_pos;uniform float u_emissive_strength; #ifdef RENDER_SHADOWS uniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth; #endif #ifdef ELEVATED_ROADS in highp float v_road_z_offset; #endif #ifdef APPLY_LUT_ON_GPU uniform highp sampler3D u_lutTexture; #endif #pragma mapbox: define lowp float opacity #pragma mapbox: define lowp vec4 pattern #ifdef FILL_PATTERN_TRANSITION #pragma mapbox: define mediump vec4 pattern_b #endif void main() { #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize mediump vec4 pattern #ifdef FILL_PATTERN_TRANSITION #pragma mapbox: initialize mediump vec4 pattern_b #endif vec2 pattern_tl=pattern.xy;vec2 pattern_br=pattern.zw;highp vec2 imagecoord=mod(v_pos,1.0);highp vec2 pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,imagecoord);highp vec2 lod_pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,v_pos);vec4 out_color=textureLodCustom(u_image,pos,lod_pos); #ifdef APPLY_LUT_ON_GPU out_color=applyLUT(u_lutTexture,out_color); #endif #ifdef FILL_PATTERN_TRANSITION vec2 pattern_b_tl=pattern_b.xy;vec2 pattern_b_br=pattern_b.zw;highp vec2 pos_b=mix(pattern_b_tl/u_texsize,pattern_b_br/u_texsize,imagecoord);vec4 color_b=textureLodCustom(u_image,pos_b,lod_pos);out_color=out_color*(1.0-u_pattern_transition)+color_b*u_pattern_transition; #endif #ifdef LIGHTING_3D_MODE out_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength); #ifdef RENDER_SHADOWS float light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth); #ifdef ELEVATED_ROADS out_color.rgb*=mix(v_road_z_offset !=0.0 ? u_ground_shadow_factor : vec3(1.0),vec3(1.0),light); #else out_color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light); #endif #endif #endif #ifdef FEATURE_CUTOUT out_color=apply_feature_cutout(out_color,gl_FragCoord); #endif #ifdef FOG out_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos)); #endif glFragColor=out_color*opacity; #ifdef USE_MRT1 out_Target1=vec4(u_emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a); #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_shadow.vertex.glsl" uniform mat4 u_matrix;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_tile_units_to_pixels;in vec2 a_pos; #ifdef ELEVATED_ROADS in float a_road_z_offset;out highp float v_road_z_offset; #endif #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth; #endif out highp vec2 v_pos; #pragma mapbox: define lowp float opacity #pragma mapbox: define lowp vec4 pattern #ifdef FILL_PATTERN_TRANSITION #pragma mapbox: define mediump vec4 pattern_b #endif #pragma mapbox: define lowp float pixel_ratio #pragma mapbox: define highp float z_offset void main() { #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize mediump vec4 pattern #pragma mapbox: initialize lowp float pixel_ratio #pragma mapbox: initialize highp float z_offset #ifdef FILL_PATTERN_TRANSITION #pragma mapbox: initialize mediump vec4 pattern_b #endif vec2 pattern_tl=pattern.xy;vec2 pattern_br=pattern.zw;vec2 display_size=(pattern_br-pattern_tl)/pixel_ratio; #ifdef ELEVATED_ROADS z_offset+=a_road_z_offset;v_road_z_offset=z_offset; #endif float hidden=float(opacity==0.0);gl_Position=mix(u_matrix*vec4(a_pos,z_offset,1),AWAY,hidden);v_pos=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,display_size,u_tile_units_to_pixels,a_pos); #ifdef RENDER_SHADOWS vec3 shd_pos0=vec3(a_pos,z_offset);vec3 shd_pos1=vec3(a_pos,z_offset); #ifdef NORMAL_OFFSET vec3 offset=shadow_normal_offset(vec3(0.0,0.0,1.0));shd_pos0+=offset*shadow_normal_offset_multiplier0();shd_pos1+=offset*shadow_normal_offset_multiplier1(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w; #endif #ifdef FOG v_fog_pos=fog_position(a_pos); #endif }`),fillExtrusion:ps(`#include "_prelude_fog.fragment.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_lighting.glsl" in vec4 v_color;in vec4 v_flat; #ifdef RENDER_SHADOWS in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1; #endif uniform lowp float u_opacity; #ifdef FAUX_AO uniform lowp vec2 u_ao;in vec2 v_ao; #endif #if defined(ZERO_ROOF_RADIUS) && !defined(LIGHTING_3D_MODE) in vec4 v_roof_color; #endif #if defined(ZERO_ROOF_RADIUS) || defined(RENDER_SHADOWS) || defined(LIGHTING_3D_MODE) in highp vec3 v_normal; #endif uniform vec3 u_flood_light_color;uniform highp float u_vertical_scale;uniform float u_flood_light_intensity;uniform vec3 u_ground_shadow_factor; #if defined(LIGHTING_3D_MODE) && defined(FLOOD_LIGHT) in float v_flood_radius;in float v_has_floodlight; #endif in float v_height; #pragma mapbox: define highp float emissive_strength void main() { #pragma mapbox: initialize highp float emissive_strength #if defined(ZERO_ROOF_RADIUS) || defined(RENDER_SHADOWS) || defined(LIGHTING_3D_MODE) vec3 normal=normalize(v_normal); #endif float z;vec4 color=v_color; #ifdef ZERO_ROOF_RADIUS z=float(normal.z > 0.00001); #ifdef LIGHTING_3D_MODE normal=mix(normal,vec3(0.0,0.0,1.0),z); #else color=mix(v_color,v_roof_color,z); #endif #endif float h=max(0.0,v_height);float ao_shade=1.0; #ifdef FAUX_AO float intensity=u_ao[0];float h_floors=h/(u_ao[1]*u_vertical_scale);float y_shade=1.0-0.9*intensity*min(v_ao.y,1.0);ao_shade=(1.0-0.08*intensity)*(y_shade+(1.0-y_shade)*(1.0-pow(1.0-min(h_floors/16.0,1.0),16.0)))+0.08*intensity*min(h_floors/160.0,1.0);float concave=v_ao.x*v_ao.x; #ifdef ZERO_ROOF_RADIUS concave*=(1.0-z); #endif float x_shade=mix(1.0,mix(0.6,0.75,min(h_floors/30.0,1.0)),intensity)+0.1*intensity*min(h,1.0);ao_shade*=mix(1.0,x_shade*x_shade*x_shade,concave); #ifdef LIGHTING_3D_MODE #ifdef FLOOD_LIGHT color.rgb*=mix(ao_shade,1.0,v_has_floodlight); #else color.rgb*=ao_shade; #endif #else color.rgb*=ao_shade; #endif #endif #ifdef LIGHTING_3D_MODE float flood_radiance=0.0; #ifdef FLOOD_LIGHT flood_radiance=(1.0-min(h/v_flood_radius,1.0))*u_flood_light_intensity*v_has_floodlight; #endif #ifdef RENDER_SHADOWS #ifdef FLOOD_LIGHT float ndotl_unclamped=dot(normal,u_shadow_direction);float ndotl=max(0.0,ndotl_unclamped);float occlusion=ndotl_unclamped < 0.0 ? 1.0 : shadow_occlusion(ndotl,v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w);vec3 litColor=apply_lighting(color.rgb,normal,(1.0-u_shadow_intensity*occlusion)*ndotl);vec3 floodLitColor=compute_flood_lighting(u_flood_light_color*u_opacity,1.0-u_shadow_intensity,occlusion,u_ground_shadow_factor);color.rgb=mix(litColor,floodLitColor,flood_radiance); #else float shadowed_lighting_factor; #ifdef RENDER_CUTOFF shadowed_lighting_factor=shadowed_light_factor_normal_opacity(normal,v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w,v_cutoff_opacity);if (v_cutoff_opacity==0.0) {discard;} #else shadowed_lighting_factor=shadowed_light_factor_normal(normal,v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w); #endif color.rgb=apply_lighting(color.rgb,normal,shadowed_lighting_factor); #endif #else color.rgb=apply_lighting(color.rgb,normal); #ifdef FLOOD_LIGHT color.rgb=mix(color.rgb,u_flood_light_color*u_opacity,flood_radiance); #endif #endif color.rgb=mix(color.rgb,v_flat.rgb,emissive_strength);color*=u_opacity; #endif #ifdef FOG color=fog_dither(fog_apply_premultiplied(color,v_fog_pos,h)); #endif #ifdef INDICATOR_CUTOUT color=applyCutout(color,h); #endif #ifdef FEATURE_CUTOUT color=apply_feature_cutout(color,gl_FragCoord); #endif glFragColor=color; #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_terrain.vertex.glsl" #include "_prelude_shadow.vertex.glsl" #include "_prelude_lighting.glsl" #include "_prelude_material_table.vertex.glsl" uniform mat4 u_matrix;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform float u_edge_radius;uniform float u_width_scale;in vec4 a_pos_normal_ed;in vec2 a_centroid_pos; #ifdef RENDER_WALL_MODE in vec3 a_join_normal_inside; #endif #ifdef PROJECTION_GLOBE_VIEW in vec3 a_pos_3;in vec3 a_pos_normal_3;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform vec3 u_tile_id;uniform float u_zoom_transition;uniform vec3 u_up_dir;uniform float u_height_lift; #endif #ifdef TERRAIN uniform int u_height_type;uniform int u_base_type; #endif uniform highp float u_vertical_scale;out vec4 v_color;out vec4 v_flat; #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1; #endif #if defined(ZERO_ROOF_RADIUS) && !defined(LIGHTING_3D_MODE) out vec4 v_roof_color; #endif #if defined(ZERO_ROOF_RADIUS) || defined(RENDER_SHADOWS) || defined(LIGHTING_3D_MODE) out highp vec3 v_normal; #endif #ifdef FAUX_AO uniform lowp vec2 u_ao;out vec2 v_ao; #endif #if defined(LIGHTING_3D_MODE) && defined(FLOOD_LIGHT) out float v_flood_radius;out float v_has_floodlight; #endif out float v_height;vec3 linearTosRGB(vec3 color) {return pow(color,vec3(1./2.2));}vec3 sRGBToLinear(vec3 srgbIn) {return pow(srgbIn,vec3(2.2));} #pragma mapbox: define highp float base #pragma mapbox: define highp float height #pragma mapbox: define highp vec4 color #pragma mapbox: define highp float flood_light_wall_radius #pragma mapbox: define highp float line_width #pragma mapbox: define highp float emissive_strength void main() {DECLARE_MATERIAL_TABLE_INFO #pragma mapbox: initialize highp float base #pragma mapbox: initialize highp float height #pragma mapbox: initialize highp vec4 color #pragma mapbox: initialize highp float flood_light_wall_radius #pragma mapbox: initialize highp float line_width #pragma mapbox: initialize highp float emissive_strength base*=u_vertical_scale;height*=u_vertical_scale;vec4 pos_nx=floor(a_pos_normal_ed*0.5);vec4 top_up_ny_start=a_pos_normal_ed-2.0*pos_nx;vec3 top_up_ny=top_up_ny_start.xyz;float x_normal=pos_nx.z/8192.0;vec3 normal=top_up_ny.y==1.0 ? vec3(0.0,0.0,1.0) : normalize(vec3(x_normal,(2.0*top_up_ny.z-1.0)*(1.0-abs(x_normal)),0.0)); #if defined(ZERO_ROOF_RADIUS) || defined(RENDER_SHADOWS) || defined(LIGHTING_3D_MODE) v_normal=normal; #endif base=max(0.0,base);float attr_height=height;height=max(0.0,top_up_ny.y==0.0 && top_up_ny.x==1.0 ? height-u_edge_radius : height);float t=top_up_ny.x;vec2 centroid_pos=vec2(0.0); #if defined(HAS_CENTROID) || defined(TERRAIN) centroid_pos=a_centroid_pos; #endif float ele=0.0;float h=0.0;float c_ele=0.0;vec3 pos; #ifdef TERRAIN bool is_flat_height=centroid_pos.x !=0.0 && u_height_type==1;bool is_flat_base=centroid_pos.x !=0.0 && u_base_type==1;ele=elevation(pos_nx.xy);c_ele=is_flat_height || is_flat_base ? (centroid_pos.y==0.0 ? elevationFromUint16(centroid_pos.x) : flatElevation(centroid_pos)) : ele;float h_height=is_flat_height ? max(c_ele+height,ele+base+2.0) : ele+height;float h_base=is_flat_base ? max(c_ele+base,ele+base) : ele+(base==0.0 ?-5.0 : base);h=t > 0.0 ? max(h_base,h_height) : h_base;pos=vec3(pos_nx.xy,h); #else h=t > 0.0 ? height : base;pos=vec3(pos_nx.xy,h); #endif #ifdef PROJECTION_GLOBE_VIEW float lift=float((t+base) > 0.0)*u_height_lift;h+=lift;vec3 globe_normal=normalize(mix(a_pos_normal_3/16384.0,u_up_dir,u_zoom_transition));vec3 globe_pos=a_pos_3+globe_normal*(u_tile_up_scale*h);vec3 merc_pos=mercator_tile_position(u_inv_rot_matrix,pos.xy,u_tile_id,u_merc_center)+u_up_dir*u_tile_up_scale*pos.z;pos=mix_globe_mercator(globe_pos,merc_pos,u_zoom_transition); #endif float cutoff=1.0;vec3 scaled_pos=pos; #ifdef RENDER_CUTOFF vec3 centroid_random=vec3(centroid_pos.xy,centroid_pos.x+centroid_pos.y+1.0);vec3 ground_pos=centroid_pos.x==0.0 ? pos.xyz : (centroid_random/8.0);vec4 ground=u_matrix*vec4(ground_pos.xy,ele,1.0); #ifdef CLIP_ZERO_TO_ONE cutoff=cutoff_opacity(u_cutoff_params,ground.z*2.0-ground.w); #else cutoff=cutoff_opacity(u_cutoff_params,ground.z); #endif if (centroid_pos.y !=0.0 && centroid_pos.x !=0.0) {vec3 g=floor(ground_pos);vec3 mod_=centroid_random-g*8.0;float seed=min(1.0,0.1*(min(3.5,max(mod_.x+mod_.y,0.2*attr_height))*0.35+mod_.z));if (cutoff < 0.8-seed) {cutoff=0.0;}}float cutoff_scale=cutoff;v_cutoff_opacity=cutoff;scaled_pos.z=mix(c_ele,h,cutoff_scale); #endif float hidden=float((centroid_pos.x==0.0 && centroid_pos.y==1.0) || (cutoff==0.0 && centroid_pos.x !=0.0) || (color.a==0.0)); #ifdef RENDER_WALL_MODE vec2 wall_offset=u_width_scale*line_width*(a_join_normal_inside.xy/EXTENT);scaled_pos.xy+=(1.0-a_join_normal_inside.z)*wall_offset*0.5;scaled_pos.xy-=a_join_normal_inside.z*wall_offset*0.5; #endif gl_Position=mix(u_matrix*vec4(scaled_pos,1),AWAY,hidden);h=h-ele;v_height=h; #ifdef RENDER_SHADOWS vec3 shd_pos0=pos;vec3 shd_pos1=pos; #ifdef NORMAL_OFFSET vec3 offset=shadow_normal_offset(normal);shd_pos0+=offset*shadow_normal_offset_multiplier0();shd_pos1+=offset*shadow_normal_offset_multiplier1(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1); #endif float NdotL=0.0;float colorvalue=0.0; #ifndef LIGHTING_3D_MODE colorvalue=color.r*0.2126+color.g*0.7152+color.b*0.0722;vec4 ambientlight=vec4(0.03,0.03,0.03,1.0);color+=ambientlight;NdotL=clamp(dot(normal,u_lightpos),0.0,1.0);NdotL=mix((1.0-u_lightintensity),max((1.0-colorvalue+u_lightintensity),1.0),NdotL);if (normal.y !=0.0) {float r=0.84;r=mix(0.7,0.98,1.0-u_lightintensity);NdotL*=( (1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),r,1.0)));} #endif #ifdef FAUX_AO float concave=pos_nx.w-floor(pos_nx.w*0.5)*2.0;float start=top_up_ny_start.w;float y_ground=1.0-clamp(t+base,0.0,1.0);float top_height=height; #ifdef TERRAIN top_height=mix(max(c_ele+height,ele+base+2.0),ele+height,float(centroid_pos.x==0.0))-ele;y_ground+=y_ground*5.0/max(3.0,top_height); #endif v_ao=vec2(mix(concave,-concave,start),y_ground);NdotL*=(1.0+0.05*(1.0-top_up_ny.y)*u_ao[0]); #ifdef PROJECTION_GLOBE_VIEW top_height+=u_height_lift; #endif gl_Position.z-=(0.0000006*(min(top_height,500.)+2.0*min(base,500.0)+60.0*concave+3.0*start))*gl_Position.w; #endif #ifdef LIGHTING_3D_MODE #ifdef FLOOD_LIGHT float is_wall=1.0-float(t > 0.0 && top_up_ny.y > 0.0);v_has_floodlight=float(flood_light_wall_radius > 0.0 && is_wall > 0.0);v_flood_radius=flood_light_wall_radius*u_vertical_scale; #endif v_color=vec4(color.rgb,1.0);float ndotl=calculate_NdotL(normal);v_flat.rgb=sRGBToLinear(color.rgb);v_flat.rgb=v_flat.rgb*(ndotl+(1.0-min(ndotl*57.29,1.0))*emissive_strength);v_flat=vec4(linearTosRGB(v_flat.rgb),1.0); #else v_color=vec4(0.0,0.0,0.0,1.0);v_color.rgb+=clamp(color.rgb*NdotL*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_color*=u_opacity; #endif #if defined(ZERO_ROOF_RADIUS) && !defined(LIGHTING_3D_MODE) float roofNdotL=clamp(u_lightpos.z,0.0,1.0);roofNdotL=mix((1.0-u_lightintensity),max((1.0-colorvalue+u_lightintensity),1.0),roofNdotL);v_roof_color=vec4(0.0,0.0,0.0,1.0);v_roof_color.rgb+=clamp(color.rgb*roofNdotL*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_roof_color*=u_opacity; #endif #ifdef FOG v_fog_pos=fog_position(pos); #endif }`),fillExtrusionDepth:ps(`in highp float v_depth;void main() { #ifndef DEPTH_TEXTURE glFragColor=pack_depth(v_depth); #endif }`,`#include "_prelude_terrain.vertex.glsl" #include "_prelude_material_table.vertex.glsl" uniform mat4 u_matrix;uniform float u_edge_radius;uniform float u_width_scale;uniform float u_vertical_scale; #ifdef TERRAIN uniform int u_height_type;uniform int u_base_type; #endif in vec4 a_pos_normal_ed;in vec2 a_centroid_pos; #ifdef RENDER_WALL_MODE in vec3 a_join_normal_inside; #endif #pragma mapbox: define highp float base #pragma mapbox: define highp float height #pragma mapbox: define highp float line_width #pragma mapbox: define highp vec4 color out highp float v_depth;void main() {DECLARE_MATERIAL_TABLE_INFO #pragma mapbox: initialize highp float base #pragma mapbox: initialize highp float height #pragma mapbox: initialize highp float line_width #pragma mapbox: initialize highp vec4 color base*=u_vertical_scale;height*=u_vertical_scale;vec3 pos_nx=floor(a_pos_normal_ed.xyz*0.5);mediump vec3 top_up_ny=a_pos_normal_ed.xyz-2.0*pos_nx;base=max(0.0,base);height=max(0.0,top_up_ny.y==0.0 && top_up_ny.x==1.0 ? height-u_edge_radius : height);float t=top_up_ny.x;vec2 centroid_pos=vec2(0.0); #if defined(HAS_CENTROID) || defined(TERRAIN) centroid_pos=a_centroid_pos; #endif vec3 pos; #ifdef TERRAIN bool is_flat_height=centroid_pos.x !=0.0 && u_height_type==1;bool is_flat_base=centroid_pos.x !=0.0 && u_base_type==1;float ele=elevation(pos_nx.xy);float c_ele=is_flat_height || is_flat_base ? (centroid_pos.y==0.0 ? elevationFromUint16(centroid_pos.x) : flatElevation(centroid_pos)) : ele;float h_height=is_flat_height ? max(c_ele+height,ele+base+2.0) : ele+height;float h_base=is_flat_base ? max(c_ele+base,ele+base) : ele+(base==0.0 ?-5.0 : base);float h=t > 0.0 ? max(h_base,h_height) : h_base;pos=vec3(pos_nx.xy,h); #else pos=vec3(pos_nx.xy,t > 0.0 ? height : base); #endif #ifdef RENDER_WALL_MODE vec2 wall_offset=u_width_scale*line_width*(a_join_normal_inside.xy/EXTENT);pos.xy+=(1.0-a_join_normal_inside.z)*wall_offset*0.5;pos.xy-=a_join_normal_inside.z*wall_offset*0.5; #endif float hidden=float((centroid_pos.x==0.0 && centroid_pos.y==1.0) || (color.a==0.0));gl_Position=mix(u_matrix*vec4(pos,1),AWAY,hidden);v_depth=gl_Position.z/gl_Position.w;}`),fillExtrusionPattern:ps(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" uniform vec2 u_texsize;uniform sampler2D u_image; #ifdef FILL_EXTRUSION_PATTERN_TRANSITION uniform float u_pattern_transition; #endif #ifdef FAUX_AO uniform lowp vec2 u_ao;in vec3 v_ao; #endif #ifdef LIGHTING_3D_MODE in vec3 v_normal; #endif #ifdef APPLY_LUT_ON_GPU uniform highp sampler3D u_lutTexture; #endif in highp vec2 v_pos;in vec4 v_lighting;uniform lowp float u_opacity; #pragma mapbox: define highp float base #pragma mapbox: define highp float height #pragma mapbox: define mediump vec4 pattern #ifdef FILL_EXTRUSION_PATTERN_TRANSITION #pragma mapbox: define mediump vec4 pattern_b #endif #pragma mapbox: define highp float pixel_ratio void main() { #pragma mapbox: initialize highp float base #pragma mapbox: initialize highp float height #pragma mapbox: initialize mediump vec4 pattern #ifdef FILL_EXTRUSION_PATTERN_TRANSITION #pragma mapbox: initialize mediump vec4 pattern_b #endif #pragma mapbox: initialize highp float pixel_ratio vec2 pattern_tl=pattern.xy;vec2 pattern_br=pattern.zw;highp vec2 imagecoord=mod(v_pos,1.0);highp vec2 pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,imagecoord);highp vec2 lod_pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,v_pos);vec4 out_color=textureLodCustom(u_image,pos,lod_pos); #ifdef APPLY_LUT_ON_GPU out_color=applyLUT(u_lutTexture,out_color); #endif #ifdef FILL_EXTRUSION_PATTERN_TRANSITION vec2 pattern_b_tl=pattern_b.xy;vec2 pattern_b_br=pattern_b.zw;highp vec2 pos_b=mix(pattern_b_tl/u_texsize,pattern_b_br/u_texsize,imagecoord);vec4 color_b=textureLodCustom(u_image,pos_b,lod_pos);out_color=out_color*(1.0-u_pattern_transition)+color_b*u_pattern_transition; #endif #ifdef LIGHTING_3D_MODE out_color=apply_lighting(out_color,normalize(v_normal))*u_opacity; #else out_color=out_color*v_lighting; #endif #ifdef FAUX_AO float intensity=u_ao[0];float h=max(0.0,v_ao.z);float h_floors=h/u_ao[1];float y_shade=1.0-0.9*intensity*min(v_ao.y,1.0);float shade=(1.0-0.08*intensity)*(y_shade+(1.0-y_shade)*(1.0-pow(1.0-min(h_floors/16.0,1.0),16.0)))+0.08*intensity*min(h_floors/160.0,1.0);float concave=v_ao.x*v_ao.x;float x_shade=mix(1.0,mix(0.6,0.75,min(h_floors/30.0,1.0)),intensity)+0.1*intensity*min(h,1.0);shade*=mix(1.0,x_shade*x_shade*x_shade,concave);out_color.rgb=out_color.rgb*shade; #endif #ifdef FOG out_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos)); #endif #ifdef INDICATOR_CUTOUT out_color=applyCutout(out_color,height); #endif glFragColor=out_color; #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_terrain.vertex.glsl" #include "_prelude_lighting.glsl" #include "_prelude_material_table.vertex.glsl" uniform mat4 u_matrix;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_height_factor;uniform float u_tile_units_to_pixels;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform float u_width_scale;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity;in vec4 a_pos_normal_ed;in vec2 a_centroid_pos; #ifdef RENDER_WALL_MODE in vec3 a_join_normal_inside; #endif #ifdef PROJECTION_GLOBE_VIEW in vec3 a_pos_3;in vec3 a_pos_normal_3;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform vec3 u_tile_id;uniform float u_zoom_transition;uniform vec3 u_up_dir;uniform float u_height_lift; #endif #ifdef TERRAIN uniform int u_height_type;uniform int u_base_type; #endif out highp vec2 v_pos;out vec4 v_lighting; #ifdef FAUX_AO uniform lowp vec2 u_ao;out vec3 v_ao; #endif #ifdef LIGHTING_3D_MODE out vec3 v_normal; #endif #pragma mapbox: define highp float base #pragma mapbox: define highp float height #pragma mapbox: define highp vec4 color #pragma mapbox: define mediump vec4 pattern #ifdef FILL_EXTRUSION_PATTERN_TRANSITION #pragma mapbox: define mediump vec4 pattern_b #endif #pragma mapbox: define highp float pixel_ratio #pragma mapbox: define highp float line_width void main() {DECLARE_MATERIAL_TABLE_INFO #pragma mapbox: initialize highp float base #pragma mapbox: initialize highp float height #pragma mapbox: initialize highp vec4 color #pragma mapbox: initialize mediump vec4 pattern #ifdef FILL_EXTRUSION_PATTERN_TRANSITION #pragma mapbox: initialize mediump vec4 pattern_b #endif #pragma mapbox: initialize highp float pixel_ratio #pragma mapbox: initialize highp float line_width vec2 pattern_tl=pattern.xy;vec2 pattern_br=pattern.zw;vec4 pos_nx=floor(a_pos_normal_ed*0.5);mediump vec4 top_up_ny_start=a_pos_normal_ed-2.0*pos_nx;mediump vec3 top_up_ny=top_up_ny_start.xyz;float x_normal=pos_nx.z/8192.0;vec3 normal=top_up_ny.y==1.0 ? vec3(0.0,0.0,1.0) : normalize(vec3(x_normal,(2.0*top_up_ny.z-1.0)*(1.0-abs(x_normal)),0.0));float edgedistance=a_pos_normal_ed.w;vec2 display_size=(pattern_br-pattern_tl)/pixel_ratio;base=max(0.0,base);height=max(0.0,height);float t=top_up_ny.x;float z=t > 0.0 ? height : base;vec2 centroid_pos=vec2(0.0); #if defined(HAS_CENTROID) || defined(TERRAIN) centroid_pos=a_centroid_pos; #endif float ele=0.0;float h=z;vec3 p;float c_ele; #ifdef TERRAIN bool is_flat_height=centroid_pos.x !=0.0 && u_height_type==1;bool is_flat_base=centroid_pos.x !=0.0 && u_base_type==1;ele=elevation(pos_nx.xy);c_ele=is_flat_height || is_flat_base ? (centroid_pos.y==0.0 ? elevationFromUint16(centroid_pos.x) : flatElevation(centroid_pos)) : ele;float h_height=is_flat_height ? max(c_ele+height,ele+base+2.0) : ele+height;float h_base=is_flat_base ? max(c_ele+base,ele+base) : ele+(base==0.0 ?-5.0 : base);h=t > 0.0 ? max(h_base,h_height) : h_base;p=vec3(pos_nx.xy,h); #else p=vec3(pos_nx.xy,z); #endif #ifdef PROJECTION_GLOBE_VIEW float lift=float((t+base) > 0.0)*u_height_lift;h+=lift;vec3 globe_normal=normalize(mix(a_pos_normal_3/16384.0,u_up_dir,u_zoom_transition));vec3 globe_pos=a_pos_3+globe_normal*(u_tile_up_scale*(p.z+lift));vec3 merc_pos=mercator_tile_position(u_inv_rot_matrix,p.xy,u_tile_id,u_merc_center)+u_up_dir*u_tile_up_scale*p.z;p=mix_globe_mercator(globe_pos,merc_pos,u_zoom_transition); #endif #ifdef RENDER_WALL_MODE vec2 wall_offset=u_width_scale*line_width*(a_join_normal_inside.xy/EXTENT);p.xy+=(1.0-a_join_normal_inside.z)*wall_offset*0.5;p.xy-=a_join_normal_inside.z*wall_offset*0.5; #endif float hidden=float((centroid_pos.x==0.0 && centroid_pos.y==1.0) || (color.a==0.0));gl_Position=mix(u_matrix*vec4(p,1),AWAY,hidden);vec2 pos=normal.z==1.0 ? pos_nx.xy : vec2(edgedistance,z*u_height_factor);v_pos=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,display_size,u_tile_units_to_pixels,pos);v_lighting=vec4(0.0,0.0,0.0,1.0);float NdotL=0.0; #ifdef LIGHTING_3D_MODE NdotL=calculate_NdotL(normal); #else NdotL=clamp(dot(normal,u_lightpos),0.0,1.0);NdotL=mix((1.0-u_lightintensity),max((0.5+u_lightintensity),1.0),NdotL); #endif if (normal.y !=0.0) {float r=0.84; #ifndef LIGHTING_3D_MODE r=mix(0.7,0.98,1.0-u_lightintensity); #endif NdotL*=( (1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),r,1.0)));} #ifdef FAUX_AO float concave=pos_nx.w-floor(pos_nx.w*0.5)*2.0;float start=top_up_ny_start.w;float y_ground=1.0-clamp(t+base,0.0,1.0);float top_height=height; #ifdef TERRAIN top_height=mix(max(c_ele+height,ele+base+2.0),ele+height,float(centroid_pos.x==0.0))-ele;y_ground+=y_ground*5.0/max(3.0,top_height); #endif v_ao=vec3(mix(concave,-concave,start),y_ground,h-ele);NdotL*=(1.0+0.05*(1.0-top_up_ny.y)*u_ao[0]); #ifdef PROJECTION_GLOBE_VIEW top_height+=u_height_lift; #endif gl_Position.z-=(0.0000006*(min(top_height,500.)+2.0*min(base,500.0)+60.0*concave+3.0*start))*gl_Position.w; #endif #ifdef LIGHTING_3D_MODE v_normal=normal; #else v_lighting.rgb+=clamp(NdotL*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_lighting*=u_opacity; #endif #ifdef FOG v_fog_pos=fog_position(p); #endif }`),groundShadow:ps(`#include "_prelude_shadow.fragment.glsl" precision highp float;uniform vec3 u_ground_shadow_factor;in vec4 v_pos_light_view_0;in vec4 v_pos_light_view_1; #ifdef FOG in float v_fog_opacity; #endif void main() {float light=shadowed_light_factor_plane_bias(v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w);vec3 shadow=mix(u_ground_shadow_factor,vec3(1.0),light); #ifdef RENDER_CUTOFF shadow=mix(vec3(1.0),shadow,cutoff_opacity(u_cutoff_params,1.0/gl_FragCoord.w)); #endif #ifdef FOG shadow=mix(shadow,vec3(1.0),v_fog_opacity); #endif #ifdef INDICATOR_CUTOUT shadow=mix(shadow,vec3(1.0),1.0-applyCutout(vec4(1.0),0.0).r); #endif glFragColor=vec4(shadow,1.0);}`,`#include "_prelude_fog.vertex.glsl" uniform mat4 u_matrix;uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;in vec2 a_pos;out vec4 v_pos_light_view_0;out vec4 v_pos_light_view_1; #ifdef FOG out float v_fog_opacity; #endif void main() {gl_Position=u_matrix*vec4(a_pos,0.0,1.0);v_pos_light_view_0=u_light_matrix_0*vec4(a_pos,0.0,1.0);v_pos_light_view_1=u_light_matrix_1*vec4(a_pos,0.0,1.0); #ifdef FOG v_fog_pos=fog_position(a_pos);v_fog_opacity=fog(v_fog_pos); #endif }`),fillExtrusionGroundEffect:ps(`uniform highp float u_ao_pass;uniform highp float u_opacity;uniform highp float u_flood_light_intensity;uniform highp vec3 u_flood_light_color;uniform highp float u_attenuation;uniform sampler2D u_fb;uniform float u_fb_size; #ifdef SDF_SUBPASS in highp vec2 v_pos;in highp vec4 v_line_segment;in highp float v_flood_light_radius_tile;in highp vec2 v_ao;float line_df(highp vec2 a,highp vec2 b,highp vec2 p) {highp vec2 ba=b-a;highp vec2 pa=p-a;highp float r=clamp(dot(pa,ba)/dot(ba,ba),0.0,1.0);return length(pa-r*ba);} #ifdef FOG in highp float v_fog; #endif #endif void main() { #ifdef CLEAR_SUBPASS vec4 color=vec4(1.0); #ifdef CLEAR_FROM_TEXTURE color=texture(u_fb,gl_FragCoord.xy/vec2(u_fb_size)); #endif glFragColor=color; #else #ifdef SDF_SUBPASS highp float d=line_df(v_line_segment.xy,v_line_segment.zw,v_pos);highp float effect_radius=mix(v_flood_light_radius_tile,v_ao.y,u_ao_pass);d/=effect_radius;d=min(d,1.0);d=1.0-pow(1.0-d,u_attenuation);highp float effect_intensity=mix(u_flood_light_intensity,v_ao.x,u_ao_pass);highp float fog=1.0; #ifdef FOG fog=v_fog; #endif #ifdef RENDER_CUTOFF fog*=v_cutoff_opacity; #endif glFragColor=vec4(vec3(0.0),mix(1.0,d,effect_intensity*u_opacity*fog)); #else #ifdef USE_MRT1 out_Target1=vec4(1.0-texture(u_fb,gl_FragCoord.xy/vec2(u_fb_size)).a,0.0,0.0,0.0); #else vec4 color=mix(vec4(u_flood_light_color,1.0),vec4(vec3(0.0),1.0),u_ao_pass); #ifdef OVERDRAW_INSPECTOR color=vec4(1.0); #endif glFragColor=color; #endif #endif HANDLE_WIREFRAME_DEBUG; #endif }`,`#include "_prelude_fog.vertex.glsl" in highp vec4 a_pos_end;in highp float a_angular_offset_factor;in highp float a_hidden_by_landmark; #ifdef SDF_SUBPASS out highp vec2 v_pos;out highp vec4 v_line_segment;out highp float v_flood_light_radius_tile;out highp vec2 v_ao; #ifdef FOG out highp float v_fog; #endif #endif uniform highp float u_flood_light_intensity;uniform highp mat4 u_matrix;uniform highp float u_ao_pass;uniform highp float u_meter_to_tile;uniform highp float u_edge_radius;uniform highp float u_dynamic_offset;uniform highp vec2 u_ao; #pragma mapbox: define highp float flood_light_ground_radius const float TANGENT_CUTOFF=4.0;const float NORM=32767.0;void main() { #pragma mapbox: initialize highp float flood_light_ground_radius vec2 p=a_pos_end.xy;vec2 q=floor(a_pos_end.zw*0.5);vec2 start_bottom=a_pos_end.zw-q*2.0;float fl_ground_radius=flood_light_ground_radius;fl_ground_radius=abs(flood_light_ground_radius);float direction=flood_light_ground_radius < 0.0 ?-1.0 : 1.0;float flood_radius_tile=fl_ground_radius*u_meter_to_tile;vec2 v=normalize(q-p);float ao_radius=u_ao.y/3.5;float effect_radius=mix(flood_radius_tile,ao_radius,u_ao_pass)+u_edge_radius;float angular_offset_factor=a_angular_offset_factor/NORM*TANGENT_CUTOFF;float angular_offset=direction*angular_offset_factor*effect_radius;float top=1.0-start_bottom.y;float side=(0.5-start_bottom.x)*2.0;vec2 extrusion_parallel=v*side*mix(u_dynamic_offset,angular_offset,top);vec2 perp=vec2(v.y,-v.x);vec2 extrusion_perp=direction*perp*effect_radius*top;vec3 pos=vec3(mix(q,p,start_bottom.x),0.0);pos.xy+=extrusion_parallel+extrusion_perp; #ifdef SDF_SUBPASS v_pos=pos.xy;v_line_segment=vec4(p,q)+perp.xyxy*u_edge_radius;v_flood_light_radius_tile=flood_radius_tile;v_ao=vec2(u_ao.x,ao_radius); #ifdef FOG v_fog_pos=fog_position(pos);v_fog=1.0-fog(v_fog_pos); #endif #endif float hidden_by_landmark=0.0; #ifdef HAS_CENTROID hidden_by_landmark=a_hidden_by_landmark; #endif float isFloodlit=float(fl_ground_radius > 0.0 && u_flood_light_intensity > 0.0);float hidden=mix(1.0-isFloodlit,isFloodlit,u_ao_pass);hidden+=hidden_by_landmark;gl_Position=mix(u_matrix*vec4(pos,1.0),AWAY,float(hidden > 0.0)); #ifdef RENDER_CUTOFF v_cutoff_opacity=cutoff_opacity(u_cutoff_params,gl_Position.z); #endif }`),hillshadePrepare:ps(`precision highp float;uniform highp sampler2D u_image;in vec2 v_pos;uniform vec2 u_dimension;uniform float u_zoom;float getElevation(vec2 coord) {return texture(u_image,coord).r/4.0;}void main() {vec2 epsilon=1.0/u_dimension;float a=getElevation(v_pos+vec2(-epsilon.x,-epsilon.y));float b=getElevation(v_pos+vec2(0,-epsilon.y));float c=getElevation(v_pos+vec2(epsilon.x,-epsilon.y));float d=getElevation(v_pos+vec2(-epsilon.x,0));float e=getElevation(v_pos+vec2(epsilon.x,0));float f=getElevation(v_pos+vec2(-epsilon.x,epsilon.y));float g=getElevation(v_pos+vec2(0,epsilon.y));float h=getElevation(v_pos+vec2(epsilon.x,epsilon.y));float exaggerationFactor=u_zoom < 2.0 ? 0.4 : u_zoom < 4.5 ? 0.35 : 0.3;float exaggeration=u_zoom < 15.0 ? (u_zoom-15.0)*exaggerationFactor : 0.0;vec2 deriv=vec2( (c+e+e+h)-(a+d+d+f),(f+g+g+h)-(a+b+b+c) )/pow(2.0,exaggeration+(19.2562-u_zoom));glFragColor=clamp(vec4( deriv.x/2.0+0.5,deriv.y/2.0+0.5,1.0,1.0),0.0,1.0);}`,"uniform mat4 u_matrix;uniform vec2 u_dimension;in vec2 a_pos;in vec2 a_texture_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);highp vec2 epsilon=1.0/u_dimension;float scale=(u_dimension.x-2.0)/u_dimension.x;v_pos=(a_texture_pos/8192.0)*scale+epsilon;}"),hillshade:ps(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" uniform sampler2D u_image;in vec2 v_pos;uniform vec2 u_latrange;uniform vec2 u_light;uniform vec4 u_shadow;uniform vec4 u_highlight;uniform vec4 u_accent;uniform float u_emissive_strength;void main() {vec4 pixel=texture(u_image,v_pos);vec2 deriv=((pixel.rg*2.0)-1.0);float scaleFactor=cos(radians((u_latrange[0]-u_latrange[1])*(1.0-v_pos.y)+u_latrange[1]));float slope=atan(1.25*length(deriv)/scaleFactor);float aspect=deriv.x !=0.0 ? atan(deriv.y,-deriv.x) : PI/2.0*(deriv.y > 0.0 ? 1.0 :-1.0);float intensity=u_light.x;float azimuth=u_light.y+PI;float base=1.875-intensity*1.75;float maxValue=0.5*PI;float scaledSlope=intensity !=0.5 ? ((pow(base,slope)-1.0)/(pow(base,maxValue)-1.0))*maxValue : slope;float accent=cos(scaledSlope);vec4 accent_color=(1.0-accent)*u_accent*clamp(intensity*2.0,0.0,1.0);float shade=abs(mod((aspect+azimuth)/PI+0.5,2.0)-1.0);vec4 shade_color=mix(u_shadow,u_highlight,shade)*sin(scaledSlope)*clamp(intensity*2.0,0.0,1.0);glFragColor=accent_color*(1.0-shade_color.a)+shade_color; #ifdef LIGHTING_3D_MODE glFragColor=apply_lighting_with_emission_ground(glFragColor,u_emissive_strength); #endif #ifdef FOG glFragColor=fog_dither(fog_apply_premultiplied(glFragColor,v_fog_pos)); #endif #ifdef USE_MRT1 out_Target1=vec4(u_emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a); #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" uniform mat4 u_matrix;in vec2 a_pos;in vec2 a_texture_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos=a_texture_pos/8192.0; #ifdef FOG v_fog_pos=fog_position(a_pos); #endif }`),line:ps(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" uniform lowp float u_device_pixel_ratio;uniform highp float u_width_scale;uniform highp float u_floor_width_scale;uniform float u_alpha_discard_threshold;uniform highp vec2 u_trim_offset;uniform highp vec2 u_trim_fade_range;uniform lowp vec4 u_trim_color;in vec2 v_width2;in vec2 v_normal;in float v_gamma_scale;in highp vec3 v_uv; #ifdef ELEVATED_ROADS in highp float v_road_z_offset; #endif #ifdef RENDER_LINE_DASH uniform sampler2D u_dash_image;in vec2 v_tex; #endif #ifdef RENDER_LINE_GRADIENT uniform sampler2D u_gradient_image; #endif #ifdef INDICATOR_CUTOUT in highp float v_z_offset; #endif #ifdef RENDER_SHADOWS uniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth; #endif float luminance(vec3 c) {return (c.r+c.r+c.b+c.g+c.g+c.g)*0.1667;} #pragma mapbox: define highp vec4 color #pragma mapbox: define lowp float floorwidth #pragma mapbox: define lowp vec4 dash #pragma mapbox: define lowp float blur #pragma mapbox: define lowp float opacity #pragma mapbox: define mediump float side_z_offset #pragma mapbox: define lowp float border_width #pragma mapbox: define lowp vec4 border_color #pragma mapbox: define lowp float emissive_strength float linearstep(float edge0,float edge1,float x) {return clamp((x-edge0)/(edge1-edge0),0.0,1.0);}void main() { #pragma mapbox: initialize highp vec4 color #pragma mapbox: initialize lowp float floorwidth #pragma mapbox: initialize lowp vec4 dash #pragma mapbox: initialize lowp float blur #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize mediump float side_z_offset #pragma mapbox: initialize lowp float border_width #pragma mapbox: initialize lowp vec4 border_color #pragma mapbox: initialize lowp float emissive_strength float dist=length(v_normal)*v_width2.s;float blur2=(u_width_scale*blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);alpha=side_z_offset > 0.0 ? 1.0-alpha : alpha; #ifdef RENDER_LINE_DASH float sdfdist=texture(u_dash_image,v_tex).r;float sdfgamma=1.0/(2.0*u_device_pixel_ratio)/dash.z;float scaled_floorwidth=(floorwidth*u_floor_width_scale);alpha*=linearstep(0.5-sdfgamma/scaled_floorwidth,0.5+sdfgamma/scaled_floorwidth,sdfdist); #endif highp vec4 out_color; #ifdef RENDER_LINE_GRADIENT out_color=texture(u_gradient_image,v_uv.xy); #ifdef MULTIPLY_LINE_GRADIENT_COLOR out_color*=color; #endif #else out_color=color; #endif float trim_alpha=1.0; #ifdef RENDER_LINE_TRIM_OFFSET highp float trim_start=u_trim_offset[0];highp float trim_end=u_trim_offset[1];highp float line_progress=v_uv[2];if (trim_end > trim_start) {highp float start_transition=max(0.0,min(1.0,(line_progress-trim_start)/max(u_trim_fade_range[0],1.0e-9)));highp float end_transition=max(0.0,min(1.0,(trim_end-line_progress)/max(u_trim_fade_range[1],1.0e-9)));highp float transition_factor=min(start_transition,end_transition);out_color=mix(out_color,u_trim_color,transition_factor);trim_alpha=1.0-transition_factor;} #endif if (u_alpha_discard_threshold !=0.0) {if (alpha < u_alpha_discard_threshold) {discard;}} #ifdef RENDER_LINE_BORDER float edgeBlur=((border_width*u_width_scale)+1.0/u_device_pixel_ratio);float alpha2=clamp(min(dist-(v_width2.t-edgeBlur),v_width2.s-dist)/edgeBlur,0.0,1.0);if (alpha2 < 1.) {float smoothAlpha=smoothstep(0.6,1.0,alpha2);if (border_color.a==0.0) {float Y=(out_color.a > 0.01) ? luminance(out_color.rgb/out_color.a) : 1.;float adjustment=(Y > 0.) ? 0.5/Y : 0.45;if (out_color.a > 0.25 && Y < 0.25) {vec3 borderColor=(Y > 0.) ? out_color.rgb : vec3(1,1,1)*out_color.a;out_color.rgb=out_color.rgb+borderColor*(adjustment*(1.0-smoothAlpha));} else {out_color.rgb*=(0.6 +0.4*smoothAlpha);}} else {out_color=mix(border_color*trim_alpha,out_color,smoothAlpha);}} #endif #ifdef LIGHTING_3D_MODE out_color=apply_lighting_with_emission_ground(out_color,emissive_strength); #ifdef RENDER_SHADOWS float light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth); #ifdef ELEVATED_ROADS out_color.rgb*=mix(v_road_z_offset !=0.0 ? u_ground_shadow_factor : vec3(1.0),vec3(1.0),light); #else out_color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light); #endif #endif #endif #ifdef FOG out_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos)); #endif out_color*=(alpha*opacity); #ifdef INDICATOR_CUTOUT out_color=applyCutout(out_color,v_z_offset); #endif #ifdef FEATURE_CUTOUT out_color=apply_feature_cutout(out_color,gl_FragCoord); #endif glFragColor=out_color; #ifdef DUAL_SOURCE_BLENDING glFragColorSrc1=vec4(vec3(0.0),emissive_strength); #else #ifdef USE_MRT1 out_Target1=vec4(emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a); #endif #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_shadow.vertex.glsl" #include "_prelude_terrain.vertex.glsl" #define EXTRUDE_SCALE 0.015873016 in vec2 a_pos_normal;in vec4 a_data; #if defined(ELEVATED) || defined(ELEVATED_ROADS) || defined(VARIABLE_LINE_WIDTH) in vec3 a_z_offset_width; #endif #if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_TRIM_OFFSET) in highp vec3 a_packed; #endif #ifdef RENDER_LINE_DASH in float a_linesofar; #endif uniform mat4 u_matrix;uniform mat2 u_pixels_to_tile_units;uniform vec2 u_units_to_pixels;uniform lowp float u_device_pixel_ratio;uniform float u_width_scale;uniform highp float u_floor_width_scale; #ifdef ELEVATED uniform lowp float u_zbias_factor;uniform lowp float u_tile_to_meter;float sample_elevation(vec2 apos) { #ifdef ELEVATION_REFERENCE_SEA return 0.0; #else return elevation(apos); #endif } #endif out vec2 v_normal;out vec2 v_width2;out float v_gamma_scale;out highp vec3 v_uv; #ifdef ELEVATED_ROADS out highp float v_road_z_offset; #endif #ifdef RENDER_LINE_DASH uniform vec2 u_texsize;uniform float u_tile_units_to_pixels;out vec2 v_tex; #endif #ifdef RENDER_LINE_GRADIENT uniform float u_image_height; #endif #ifdef INDICATOR_CUTOUT out highp float v_z_offset; #endif #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth; #endif #pragma mapbox: define highp vec4 color #pragma mapbox: define lowp float floorwidth #pragma mapbox: define lowp vec4 dash #pragma mapbox: define lowp float blur #pragma mapbox: define lowp float opacity #pragma mapbox: define mediump float gapwidth #pragma mapbox: define lowp float offset #pragma mapbox: define mediump float width #pragma mapbox: define mediump float side_z_offset #pragma mapbox: define lowp float border_width #pragma mapbox: define lowp vec4 border_color #pragma mapbox: define lowp float emissive_strength void main() { #pragma mapbox: initialize highp vec4 color #pragma mapbox: initialize lowp float floorwidth #pragma mapbox: initialize lowp vec4 dash #pragma mapbox: initialize lowp float blur #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize mediump float gapwidth #pragma mapbox: initialize lowp float offset #pragma mapbox: initialize mediump float width #pragma mapbox: initialize mediump float side_z_offset #pragma mapbox: initialize lowp float border_width #pragma mapbox: initialize lowp vec4 border_color #pragma mapbox: initialize lowp float emissive_strength float a_z_offset; #if defined(ELEVATED) || defined(ELEVATED_ROADS) a_z_offset=a_z_offset_width.x; #endif float ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth; #ifdef VARIABLE_LINE_WIDTH bool left=normal.y==1.0;halfwidth=(u_width_scale*(left ? a_z_offset_width.y : a_z_offset_width.z))/2.0;a_z_offset+=left ? side_z_offset : 0.0;v_normal=side_z_offset > 0.0 && left ? vec2(0.0) : v_normal; #else halfwidth=(u_width_scale*width)/2.0; #endif offset=-1.0*offset*u_width_scale;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*EXTRUDE_SCALE;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*EXTRUDE_SCALE*normal.y*mat2(t,-u,u,t);float hidden=float(opacity==0.0);vec2 extrude=dist*u_pixels_to_tile_units;vec4 projected_extrude=u_matrix*vec4(extrude,0.0,0.0);vec2 projected_extrude_xy=projected_extrude.xy; #ifdef ELEVATED_ROADS v_road_z_offset=a_z_offset;gl_Position=u_matrix*vec4(pos+offset2*u_pixels_to_tile_units,a_z_offset,1.0)+projected_extrude; #else #ifdef ELEVATED vec2 offsetTile=offset2*u_pixels_to_tile_units;vec2 offset_pos=pos+offsetTile;float ele=0.0; #ifdef CROSS_SLOPE_VERTICAL float top=a_pos_normal.y-2.0*floor(a_pos_normal.y*0.5);float line_height=2.0*u_tile_to_meter*outset*top*u_pixels_to_tile_units[1][1]+a_z_offset;ele=sample_elevation(offset_pos)+line_height;projected_extrude=vec4(0); #else #ifdef CROSS_SLOPE_HORIZONTAL float ele0=sample_elevation(offset_pos);float ele1=max(sample_elevation(offset_pos+extrude),sample_elevation(offset_pos+extrude/2.0));float ele2=max(sample_elevation(offset_pos-extrude),sample_elevation(offset_pos-extrude/2.0));float ele_max=max(ele0,max(ele1,ele2));ele=ele_max+a_z_offset; #else float ele0=sample_elevation(offset_pos);float ele1=max(sample_elevation(offset_pos+extrude),sample_elevation(offset_pos+extrude/2.0));float ele2=max(sample_elevation(offset_pos-extrude),sample_elevation(offset_pos-extrude/2.0));float ele_max=max(ele0,0.5*(ele1+ele2));ele=ele_max-ele0+ele1+a_z_offset; #endif #endif gl_Position=u_matrix*vec4(offset_pos,ele,1.0)+projected_extrude;float z=clamp(gl_Position.z/gl_Position.w,0.5,1.0);float zbias=max(0.00005,(pow(z,0.8)-z)*u_zbias_factor*u_exaggeration);gl_Position.z-=(gl_Position.w*zbias);gl_Position=mix(gl_Position,AWAY,hidden); #else gl_Position=mix(u_matrix*vec4(pos+offset2*u_pixels_to_tile_units,0.0,1.0)+projected_extrude,AWAY,hidden); #endif #endif #ifdef ELEVATED_ROADS #ifdef RENDER_SHADOWS vec3 shd_pos=vec3(pos+(offset2+dist)*u_pixels_to_tile_units,a_z_offset);vec3 shd_pos0=shd_pos;vec3 shd_pos1=shd_pos; #ifdef NORMAL_OFFSET vec3 shd_pos_offset=shadow_normal_offset(vec3(0.0,0.0,1.0));shd_pos0+=shd_pos_offset*shadow_normal_offset_multiplier0();shd_pos1+=shd_pos_offset*shadow_normal_offset_multiplier1(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w; #endif #endif #ifndef RENDER_TO_TEXTURE float epsilon=0.0001;float extrude_length_without_perspective=max(length(dist),epsilon);float extrude_length_with_perspective=max(length(projected_extrude_xy/gl_Position.w*u_units_to_pixels),epsilon);v_gamma_scale=mix(extrude_length_without_perspective/extrude_length_with_perspective,1.0,step(0.01,blur)); #else v_gamma_scale=1.0; #endif #if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_TRIM_OFFSET) highp float a_uv_x=a_packed[0];float a_split_index=a_packed[1];highp float line_progress=a_packed[2]; #ifdef RENDER_LINE_GRADIENT highp float texel_height=1.0/u_image_height;highp float half_texel_height=0.5*texel_height;v_uv=vec3(a_uv_x,a_split_index*texel_height-half_texel_height,line_progress); #else v_uv=vec3(a_uv_x,0.0,line_progress); #endif #endif #ifdef RENDER_LINE_DASH float scale=dash.z==0.0 ? 0.0 : u_tile_units_to_pixels/dash.z;float height=dash.y;v_tex=vec2(a_linesofar*scale/(floorwidth*u_floor_width_scale),(-normal.y*height+dash.x+0.5)/u_texsize.y); #endif v_width2=vec2(outset,inset); #ifdef FOG v_fog_pos=fog_position(pos); #endif #ifdef INDICATOR_CUTOUT v_z_offset=a_z_offset; #endif }`),linePattern:ps(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" uniform highp float u_device_pixel_ratio;uniform highp float u_width_scale;uniform highp float u_alpha_discard_threshold;uniform highp vec2 u_texsize;uniform highp float u_tile_units_to_pixels;uniform highp vec2 u_trim_offset;uniform highp vec2 u_trim_fade_range;uniform lowp vec4 u_trim_color;uniform sampler2D u_image; #ifdef APPLY_LUT_ON_GPU uniform highp sampler3D u_lutTexture; #endif #ifdef LINE_PATTERN_TRANSITION uniform float u_pattern_transition; #endif in vec2 v_normal;in vec2 v_width2;in highp float v_linesofar;in float v_gamma_scale;in float v_width; #ifdef RENDER_LINE_TRIM_OFFSET in highp vec3 v_uv; #endif #ifdef ELEVATED_ROADS in highp float v_road_z_offset; #endif #ifdef LINE_JOIN_NONE in vec2 v_pattern_data; #endif #ifdef INDICATOR_CUTOUT in highp float v_z_offset; #endif #ifdef RENDER_SHADOWS uniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth; #endif #pragma mapbox: define mediump vec4 pattern #ifdef LINE_PATTERN_TRANSITION #pragma mapbox: define mediump vec4 pattern_b #endif #pragma mapbox: define mediump float pixel_ratio #pragma mapbox: define mediump float blur #pragma mapbox: define mediump float opacity #pragma mapbox: define lowp float emissive_strength void main() { #pragma mapbox: initialize mediump vec4 pattern #ifdef LINE_PATTERN_TRANSITION #pragma mapbox: initialize mediump vec4 pattern_b #endif #pragma mapbox: initialize mediump float pixel_ratio #pragma mapbox: initialize mediump float blur #pragma mapbox: initialize mediump float opacity #pragma mapbox: initialize lowp float emissive_strength vec2 pattern_tl=pattern.xy;vec2 pattern_br=pattern.zw;vec2 display_size=(pattern_br-pattern_tl)/pixel_ratio;highp float pattern_size=display_size.x/u_tile_units_to_pixels;float aspect=display_size.y/v_width;float dist=length(v_normal)*v_width2.s;float blur2=(u_width_scale*blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);highp float pattern_x=v_linesofar/pattern_size*aspect;highp float x=mod(pattern_x,1.0);highp float y=0.5*v_normal.y+0.5;vec2 texel_size=1.0/u_texsize;highp vec2 pos=mix(pattern_tl*texel_size-texel_size,pattern_br*texel_size+texel_size,vec2(x,y));highp vec2 lod_pos=mix(pattern_tl*texel_size-texel_size,pattern_br*texel_size+texel_size,vec2(pattern_x,y));vec4 color=textureLodCustom(u_image,pos,lod_pos); #ifdef APPLY_LUT_ON_GPU color=applyLUT(u_lutTexture,color); #endif #ifdef LINE_PATTERN_TRANSITION vec2 pattern_b_tl=pattern_b.xy;vec2 pattern_b_br=pattern_b.zw;highp vec2 pos_b=mix(pattern_b_tl*texel_size-texel_size,pattern_b_br*texel_size+texel_size,vec2(x,y));vec4 color_b=textureLodCustom(u_image,pos_b,lod_pos);color=color*(1.0-u_pattern_transition)+color_b*u_pattern_transition; #endif #ifdef RENDER_LINE_TRIM_OFFSET highp float trim_start=u_trim_offset[0];highp float trim_end=u_trim_offset[1];highp float line_progress=v_uv[2];if (trim_end > trim_start) {highp float start_transition=max(0.0,min(1.0,(line_progress-trim_start)/max(u_trim_fade_range[0],1.0e-9)));highp float end_transition=max(0.0,min(1.0,(trim_end-line_progress)/max(u_trim_fade_range[1],1.0e-9)));highp float transition_factor=min(start_transition,end_transition);color=mix(color,color.a*u_trim_color,transition_factor);} #endif #ifdef LINE_JOIN_NONE highp float pattern_len=pattern_size/aspect;highp float segment_phase=pattern_len-mod(v_linesofar-v_pattern_data.x+pattern_len,pattern_len);highp float visible_start=segment_phase-step(pattern_len*0.5,segment_phase)*pattern_len;highp float visible_end=floor((v_pattern_data.y-segment_phase)/pattern_len)*pattern_len+segment_phase;visible_end+=step(pattern_len*0.5,v_pattern_data.y-visible_end)*pattern_len;if (v_pattern_data.x < visible_start || v_pattern_data.x >=visible_end) {color=vec4(0.0);} #endif #ifdef LIGHTING_3D_MODE color=apply_lighting_with_emission_ground(color,emissive_strength); #ifdef RENDER_SHADOWS float light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth); #ifdef ELEVATED_ROADS color.rgb*=mix(v_road_z_offset !=0.0 ? u_ground_shadow_factor : vec3(1.0),vec3(1.0),light); #else color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light); #endif #endif #endif #ifdef FOG color=fog_dither(fog_apply_premultiplied(color,v_fog_pos)); #endif color*=(alpha*opacity);if (u_alpha_discard_threshold !=0.0) {if (color.a < u_alpha_discard_threshold) {discard;}} #ifdef INDICATOR_CUTOUT color=applyCutout(color,v_z_offset); #endif glFragColor=color; #ifdef DUAL_SOURCE_BLENDING glFragColorSrc1=vec4(vec3(0.0),emissive_strength); #else #ifdef USE_MRT1 out_Target1=vec4(emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a); #endif #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_shadow.vertex.glsl" #include "_prelude_terrain.vertex.glsl" #define scale 0.015873016 in vec2 a_pos_normal;in vec4 a_data; #if defined(ELEVATED) || defined(ELEVATED_ROADS) in vec3 a_z_offset_width; #endif #ifdef RENDER_LINE_TRIM_OFFSET in highp vec3 a_packed; #endif in highp float a_linesofar; #ifdef LINE_JOIN_NONE in highp vec3 a_pattern_data;out vec2 v_pattern_data; #endif #ifdef INDICATOR_CUTOUT out highp float v_z_offset; #endif uniform mat4 u_matrix;uniform float u_tile_units_to_pixels;uniform vec2 u_units_to_pixels;uniform mat2 u_pixels_to_tile_units;uniform float u_device_pixel_ratio;uniform float u_width_scale;uniform float u_floor_width_scale; #ifdef ELEVATED uniform lowp float u_zbias_factor;uniform lowp float u_tile_to_meter;float sample_elevation(vec2 apos) { #ifdef ELEVATION_REFERENCE_SEA return 0.0; #else return elevation(apos); #endif } #endif out vec2 v_normal;out vec2 v_width2;out highp float v_linesofar;out float v_gamma_scale;out float v_width; #ifdef RENDER_LINE_TRIM_OFFSET out highp vec3 v_uv; #endif #ifdef ELEVATED_ROADS out highp float v_road_z_offset; #endif #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth; #endif #pragma mapbox: define mediump float blur #pragma mapbox: define mediump float opacity #pragma mapbox: define mediump float offset #pragma mapbox: define mediump float gapwidth #pragma mapbox: define mediump float width #pragma mapbox: define mediump float floorwidth #pragma mapbox: define mediump vec4 pattern #ifdef LINE_PATTERN_TRANSITION #pragma mapbox: define mediump vec4 pattern_b #endif #pragma mapbox: define mediump float pixel_ratio #pragma mapbox: define lowp float emissive_strength void main() { #pragma mapbox: initialize mediump float blur #pragma mapbox: initialize mediump float opacity #pragma mapbox: initialize mediump float offset #pragma mapbox: initialize mediump float gapwidth #pragma mapbox: initialize mediump float width #pragma mapbox: initialize mediump float floorwidth #pragma mapbox: initialize mediump vec4 pattern #ifdef LINE_PATTERN_TRANSITION #pragma mapbox: initialize mediump vec4 pattern_b #endif #pragma mapbox: initialize mediump float pixel_ratio #pragma mapbox: initialize lowp float emissive_strength float a_z_offset; #if defined(ELEVATED) || defined(ELEVATED_ROADS) a_z_offset=a_z_offset_width.x; #endif float ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;vec2 pos=floor(a_pos_normal*0.5);vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=(u_width_scale*width)/2.0;offset=-1.0*offset*u_width_scale;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);vec2 dist=outset*a_extrude*scale;float u=0.5*a_direction;float t=1.0-abs(u);vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float hidden=float(opacity==0.0);vec2 extrude=dist*u_pixels_to_tile_units;vec4 projected_extrude=u_matrix*vec4(extrude,0.0,0.0);vec2 projected_extrude_xy=projected_extrude.xy; #ifdef ELEVATED_ROADS v_road_z_offset=a_z_offset;gl_Position=u_matrix*vec4(pos+offset2*u_pixels_to_tile_units,a_z_offset,1.0)+projected_extrude; #else #ifdef ELEVATED vec2 offsetTile=offset2*u_pixels_to_tile_units;vec2 offset_pos=pos+offsetTile;float ele=0.0; #ifdef CROSS_SLOPE_VERTICAL float top=a_pos_normal.y-2.0*floor(a_pos_normal.y*0.5);float line_height=2.0*u_tile_to_meter*outset*top*u_pixels_to_tile_units[1][1]+a_z_offset;ele=sample_elevation(offset_pos)+line_height;projected_extrude=vec4(0); #else #ifdef CROSS_SLOPE_HORIZONTAL float ele0=sample_elevation(offset_pos);float ele1=max(sample_elevation(offset_pos+extrude),sample_elevation(offset_pos+extrude/2.0));float ele2=max(sample_elevation(offset_pos-extrude),sample_elevation(offset_pos-extrude/2.0));float ele_max=max(ele0,max(ele1,ele2));ele=ele_max+a_z_offset; #else float ele0=sample_elevation(offset_pos);float ele1=max(sample_elevation(offset_pos+extrude),sample_elevation(offset_pos+extrude/2.0));float ele2=max(sample_elevation(offset_pos-extrude),sample_elevation(offset_pos-extrude/2.0));float ele_max=max(ele0,0.5*(ele1+ele2));ele=ele_max-ele0+ele1+a_z_offset; #endif #endif gl_Position=u_matrix*vec4(offset_pos,ele,1.0)+projected_extrude;float z=clamp(gl_Position.z/gl_Position.w,0.5,1.0);float zbias=max(0.00005,(pow(z,0.8)-z)*u_zbias_factor*u_exaggeration);gl_Position.z-=(gl_Position.w*zbias);gl_Position=mix(gl_Position,AWAY,hidden); #else gl_Position=mix(u_matrix*vec4(pos+offset2*u_pixels_to_tile_units,0.0,1.0)+projected_extrude,AWAY,hidden); #endif #endif #ifdef ELEVATED_ROADS #ifdef RENDER_SHADOWS vec3 shd_pos=vec3(pos+(offset2+dist)*u_pixels_to_tile_units,a_z_offset);vec3 shd_pos0=shd_pos;vec3 shd_pos1=shd_pos; #ifdef NORMAL_OFFSET vec3 shd_pos_offset=shadow_normal_offset(vec3(0.0,0.0,1.0));shd_pos0+=shd_pos_offset*shadow_normal_offset_multiplier0();shd_pos1+=shd_pos_offset*shadow_normal_offset_multiplier1(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w; #endif #endif #ifndef RENDER_TO_TEXTURE float extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude_xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=mix(extrude_length_without_perspective/extrude_length_with_perspective,1.0,step(0.01,blur)); #else v_gamma_scale=1.0; #endif #ifdef RENDER_LINE_TRIM_OFFSET highp float a_uv_x=a_packed[0];highp float line_progress=a_packed[2];v_uv=vec3(a_uv_x,0.0,line_progress); #endif v_linesofar=a_linesofar;v_width2=vec2(outset,inset);v_width=(floorwidth*u_floor_width_scale); #ifdef LINE_JOIN_NONE v_width=(floorwidth*u_floor_width_scale)+ANTIALIASING;mediump float pixels_to_tile_units=1.0/u_tile_units_to_pixels;mediump float pixel_ratio_inverse=1.0/pixel_ratio;mediump float aspect=v_width/((pattern.w-pattern.y)*pixel_ratio_inverse);highp float subt_multiple=(pattern.z-pattern.x)*pixel_ratio_inverse*pixels_to_tile_units*aspect*32.0;highp float subt=floor(a_pattern_data.z/subt_multiple)*subt_multiple;float offset_sign=(fract(a_pattern_data.x)-0.5)*4.0;float line_progress_offset=offset_sign*v_width*0.5*pixels_to_tile_units;v_linesofar=(a_pattern_data.z-subt)+a_linesofar+line_progress_offset;v_pattern_data=vec2(a_pattern_data.x+line_progress_offset,a_pattern_data.y); #endif #ifdef FOG v_fog_pos=fog_position(pos); #endif #ifdef INDICATOR_CUTOUT v_z_offset=a_z_offset; #endif }`),raster:ps(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_raster_array.glsl" uniform float u_fade_t;uniform float u_opacity;uniform highp float u_raster_elevation;uniform highp float u_zoom_transition;in vec2 v_pos0;in vec2 v_pos1;in float v_depth; #ifdef PROJECTION_GLOBE_VIEW in float v_split_fade; #endif uniform float u_brightness_low;uniform float u_brightness_high;uniform float u_saturation_factor;uniform float u_contrast_factor;uniform vec3 u_spin_weights;uniform float u_emissive_strength; #ifndef RASTER_ARRAY uniform highp sampler2D u_image0;uniform sampler2D u_image1; #endif #ifdef RASTER_COLOR uniform sampler2D u_color_ramp;uniform highp vec4 u_colorization_mix;uniform highp float u_colorization_offset;uniform vec2 u_texture_res; #endif void main() {vec4 color0,color1,color;vec2 value; #ifdef RASTER_COLOR #ifdef RASTER_ARRAY #ifdef RASTER_ARRAY_LINEAR value=mix( raTexture2D_image0_linear(v_pos0,u_texture_res,u_colorization_mix,u_colorization_offset),raTexture2D_image1_linear(v_pos1,u_texture_res,u_colorization_mix,u_colorization_offset),u_fade_t ); #else value=mix( raTexture2D_image0_nearest(v_pos0,u_texture_res,u_colorization_mix,u_colorization_offset),raTexture2D_image1_nearest(v_pos1,u_texture_res,u_colorization_mix,u_colorization_offset),u_fade_t ); #endif if (value.y > 0.0) value.x/=value.y; #else color=mix(texture(u_image0,v_pos0),texture(u_image1,v_pos1),u_fade_t);value=vec2(u_colorization_offset+dot(color.rgb,u_colorization_mix.rgb),color.a); #endif color=texture(u_color_ramp,vec2(value.x,0.5));if (color.a > 0.0) color.rgb/=color.a;color.a*=value.y; #else color0=texture(u_image0,v_pos0);color1=texture(u_image1,v_pos1);if (color0.a > 0.0) color0.rgb/=color0.a;if (color1.a > 0.0) color1.rgb/=color1.a;color=mix(color0,color1,u_fade_t); #endif color.a*=u_opacity; #ifdef GLOBE_POLES color.a*=1.0-smoothstep(0.0,0.05,u_zoom_transition); #endif vec3 rgb=color.rgb;rgb=vec3( dot(rgb,u_spin_weights.xyz),dot(rgb,u_spin_weights.zxy),dot(rgb,u_spin_weights.yzx));float average=(color.r+color.g+color.b)/3.0;rgb+=(average-rgb)*u_saturation_factor;rgb=(rgb-0.5)*u_contrast_factor+0.5;vec3 u_high_vec=vec3(u_brightness_low,u_brightness_low,u_brightness_low);vec3 u_low_vec=vec3(u_brightness_high,u_brightness_high,u_brightness_high);vec3 out_color=mix(u_high_vec,u_low_vec,rgb); #ifdef LIGHTING_3D_MODE out_color=apply_lighting_with_emission_ground(vec4(out_color,1.0),u_emissive_strength).rgb; #endif #ifdef FOG highp float fog_limit_high_meters=1000000.0;highp float fog_limit_low_meters=600000.0;float fog_limit=1.0-smoothstep(fog_limit_low_meters,fog_limit_high_meters,u_raster_elevation);out_color=fog_dither(fog_apply(out_color,v_fog_pos,fog_limit)); #endif glFragColor=vec4(out_color*color.a,color.a); #ifdef PROJECTION_GLOBE_VIEW glFragColor*=mix(1.0,1.0-smoothstep(0.0,0.05,u_zoom_transition),smoothstep(0.8,0.9,v_split_fade)); #endif #ifdef RENDER_CUTOFF glFragColor=glFragColor*cutoff_opacity(u_cutoff_params,v_depth); #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif #ifdef USE_MRT1 out_Target1=vec4(u_emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" uniform mat4 u_matrix;uniform mat4 u_normalize_matrix;uniform mat4 u_globe_matrix;uniform mat4 u_merc_matrix;uniform mat3 u_grid_matrix;uniform vec2 u_tl_parent;uniform float u_scale_parent;uniform vec2 u_perspective_transform;uniform vec2 u_texture_offset;uniform float u_raster_elevation;uniform float u_zoom_transition;uniform vec2 u_merc_center; #define GLOBE_UPSCALE GLOBE_RADIUS/6371008.8 #ifdef GLOBE_POLES in vec3 a_globe_pos;in vec2 a_uv; #else in vec2 a_pos;in vec2 a_texture_pos; #endif out vec2 v_pos0;out vec2 v_pos1;out float v_depth; #ifdef PROJECTION_GLOBE_VIEW out float v_split_fade; #endif void main() {vec2 uv; #ifdef GLOBE_POLES vec3 globe_pos=a_globe_pos;globe_pos+=normalize(globe_pos)*u_raster_elevation*GLOBE_UPSCALE;gl_Position=u_matrix*u_globe_matrix*vec4(globe_pos ,1.0);uv=a_uv; #ifdef FOG v_fog_pos=fog_position((u_normalize_matrix*vec4(a_globe_pos,1.0)).xyz); #endif #else float w=1.0+dot(a_texture_pos,u_perspective_transform);uv=a_texture_pos/8192.0; #ifdef PROJECTION_GLOBE_VIEW vec3 decomposed_pos_and_skirt=decomposeToPosAndSkirt(a_pos);vec3 latLng=u_grid_matrix*vec3(decomposed_pos_and_skirt.xy,1.0);vec3 globe_pos=latLngToECEF(latLng.xy);globe_pos+=normalize(globe_pos)*u_raster_elevation*GLOBE_UPSCALE;vec4 globe_world_pos=u_globe_matrix*vec4(globe_pos,1.0);vec4 merc_world_pos=vec4(0.0);float mercatorY=mercatorYfromLat(latLng[0]);float mercatorX=mercatorXfromLng(latLng[1]); v_split_fade=0.0;if (u_zoom_transition > 0.0) {vec2 merc_pos=vec2(mercatorX,mercatorY);merc_world_pos=vec4(merc_pos,u_raster_elevation,1.0);merc_world_pos.xy-=u_merc_center;merc_world_pos.x=wrap(merc_world_pos.x,-0.5,0.5);merc_world_pos=u_merc_matrix*merc_world_pos;float opposite_merc_center=mod(u_merc_center.x+0.5,1.0);float dist_from_poles=(abs(mercatorY-0.5)*2.0);float range=0.1;v_split_fade=abs(opposite_merc_center-mercatorX);v_split_fade=clamp(1.0-v_split_fade,0.0,1.0);v_split_fade=max(smoothstep(1.0-range,1.0,dist_from_poles),max(smoothstep(1.0-range,1.0,v_split_fade),smoothstep(1.0-range,1.0,1.0-v_split_fade)));}float tiles=u_grid_matrix[0][2];if (tiles > 0.0) {float idx=u_grid_matrix[1][2];float idy=u_grid_matrix[2][2];float uvY=mercatorY*tiles-idy;float uvX=mercatorX*tiles-idx;uv=vec2(uvX,uvY);}vec4 interpolated_pos=vec4(mix(globe_world_pos.xyz,merc_world_pos.xyz,u_zoom_transition)*w,w);gl_Position=u_matrix*interpolated_pos; #ifdef FOG v_fog_pos=fog_position((u_normalize_matrix*vec4(globe_pos,1.0)).xyz); #endif #else gl_Position=u_matrix*vec4(a_pos*w,u_raster_elevation*w,w); #ifdef FOG v_fog_pos=fog_position(a_pos); #endif #endif #endif v_pos0=uv;v_pos1=(v_pos0*u_scale_parent)+u_tl_parent;v_pos0=u_texture_offset.x+u_texture_offset.y*v_pos0;v_pos1=u_texture_offset.x+u_texture_offset.y*v_pos1; #ifdef RENDER_CUTOFF v_depth=gl_Position.z; #endif }`),rasterParticle:ps(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" uniform float u_fade_t;uniform float u_opacity;uniform highp float u_raster_elevation;in vec2 v_pos0;in vec2 v_pos1;uniform sampler2D u_image0;uniform sampler2D u_image1;void main() {vec4 color0,color1,color;color0=texture(u_image0,v_pos0);color1=texture(u_image1,v_pos1);if (color0.a > 0.0) color0.rgb/=color0.a;if (color1.a > 0.0) color1.rgb/=color1.a;color=mix(color0,color1,u_fade_t);color.a*=u_opacity;vec3 out_color=color.rgb; #ifdef LIGHTING_3D_MODE out_color=apply_lighting_with_emission_ground(vec4(out_color,1.0),1.0).rgb; #endif #ifdef FOG highp float fog_limit_high_meters=1000000.0;highp float fog_limit_low_meters=600000.0;float fog_limit=1.0-smoothstep(fog_limit_low_meters,fog_limit_high_meters,u_raster_elevation);out_color=fog_dither(fog_apply(out_color,v_fog_pos,fog_limit)); #endif glFragColor=vec4(out_color*color.a,color.a); #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" uniform mat4 u_matrix;uniform mat4 u_normalize_matrix;uniform mat4 u_globe_matrix;uniform mat4 u_merc_matrix;uniform mat3 u_grid_matrix;uniform vec2 u_tl_parent;uniform float u_scale_parent;uniform float u_raster_elevation;uniform float u_zoom_transition;uniform vec2 u_merc_center; #define GLOBE_UPSCALE GLOBE_RADIUS/6371008.8 in vec2 a_pos;in vec2 a_texture_pos;out vec2 v_pos0;out vec2 v_pos1;void main() {float w=1.0;vec2 uv; #ifdef PROJECTION_GLOBE_VIEW vec3 decomposed_pos_and_skirt=decomposeToPosAndSkirt(a_pos);vec3 latLng=u_grid_matrix*vec3(decomposed_pos_and_skirt.xy,1.0);float mercatorY=mercatorYfromLat(latLng[0]);float mercatorX=mercatorXfromLng(latLng[1]);float tiles=u_grid_matrix[0][2];float idx=u_grid_matrix[1][2];float idy=u_grid_matrix[2][2];float uvX=mercatorX*tiles-idx;float uvY=mercatorY*tiles-idy;uv=vec2(uvX,uvY);vec3 globe_pos=latLngToECEF(latLng.xy);globe_pos+=normalize(globe_pos)*u_raster_elevation*GLOBE_UPSCALE;vec4 globe_world_pos=u_globe_matrix*vec4(globe_pos,1.0);vec4 merc_world_pos=vec4(0.0);if (u_zoom_transition > 0.0) {vec2 merc_pos=vec2(mercatorX,mercatorY);merc_world_pos=vec4(merc_pos,u_raster_elevation,1.0);merc_world_pos.xy-=u_merc_center;merc_world_pos.x=wrap(merc_world_pos.x,-0.5,0.5);merc_world_pos=u_merc_matrix*merc_world_pos;}vec4 interpolated_pos=vec4(mix(globe_world_pos.xyz,merc_world_pos.xyz,u_zoom_transition)*w,w);gl_Position=u_matrix*interpolated_pos; #ifdef FOG v_fog_pos=fog_position((u_normalize_matrix*vec4(globe_pos,1.0)).xyz); #endif #else uv=a_texture_pos/8192.0;gl_Position=u_matrix*vec4(a_pos*w,u_raster_elevation*w,w); #ifdef FOG v_fog_pos=fog_position(a_pos); #endif #endif v_pos0=uv;v_pos1=(v_pos0*u_scale_parent)+u_tl_parent;}`),rasterParticleDraw:ps("uniform sampler2D u_color_ramp;in float v_particle_speed;void main() {glFragColor=texture(u_color_ramp,vec2(v_particle_speed,0.5));}",`#include "_prelude_raster_particle.glsl" in float a_index;uniform sampler2D u_particle_texture;uniform float u_particle_texture_side_len;uniform vec2 u_tile_offset;out float v_particle_speed;void main() {ivec2 pixel_coord=ivec2( mod(a_index,u_particle_texture_side_len),a_index/u_particle_texture_side_len);vec4 pixel=texelFetch(u_particle_texture,pixel_coord,0);vec2 pos=unpack_pos_from_rgba(pixel)+u_tile_offset;vec2 tex_coord=fract(pos);vec2 velocity=lookup_velocity(tex_coord);if (velocity==INVALID_VELOCITY) {gl_Position=AWAY;v_particle_speed=0.0;} else {gl_Position=vec4(2.0*pos-1.0,0,1);v_particle_speed=length(velocity);}gl_PointSize=1.0;}`),rasterParticleTexture:ps("uniform sampler2D u_texture;uniform float u_opacity;in vec2 v_tex_pos;void main() {vec4 color=texture(u_texture,v_tex_pos);glFragColor=vec4(floor(255.0*color*u_opacity)/255.0);}","in vec2 a_pos;out vec2 v_tex_pos;void main() {vec2 uv=0.5*a_pos+vec2(0.5);v_tex_pos=uv;gl_Position=vec4(a_pos,0.0,1.0);}"),rasterParticleUpdate:ps(`#include "_prelude_raster_particle.glsl" uniform sampler2D u_particle_texture;uniform mediump float u_particle_texture_side_len;uniform mediump float u_speed_factor;uniform highp float u_reset_rate;uniform highp float u_rand_seed;in highp vec2 v_tex_coord;vec2 linearstep(vec2 edge0,vec2 edge1,vec2 x) {return clamp((x-edge0)/(edge1-edge0),vec2(0),vec2(1));}const highp vec3 rand_constants=vec3(12.9898,78.233,4375.85453);highp float rand(const highp vec2 co) {highp float t=dot(rand_constants.xy,co);return fract(sin(t)*(rand_constants.z+t));}void main() {ivec2 pixel_coord=ivec2(v_tex_coord*u_particle_texture_side_len);highp vec4 pixel=texelFetch(u_particle_texture,pixel_coord,0);highp vec2 pos=unpack_pos_from_rgba(pixel);highp vec2 velocity=lookup_velocity(clamp(pos,0.0,1.0));highp vec2 dp=velocity==INVALID_VELOCITY ? vec2(0) : velocity*u_speed_factor;pos=pos+dp;highp vec2 seed=(pos+v_tex_coord)*u_rand_seed;highp vec2 random_pos=vec2(rand(seed+1.3),rand(seed+2.1));highp vec2 persist_rate=pow( linearstep(vec2(-u_particle_pos_offset),vec2(0),pos)*linearstep(vec2(1.0+u_particle_pos_offset),vec2(1),pos),vec2(4) );highp vec2 per_frame_persist=pow(persist_rate,abs(dp)/u_particle_pos_offset);highp float drop_rate=1.0-per_frame_persist.x*per_frame_persist.y;drop_rate=any(greaterThanEqual(abs(pos-0.5),vec2(0.5+u_particle_pos_offset))) ? 1.0 : drop_rate;highp float drop=step(1.0-drop_rate-u_reset_rate,rand(seed));highp vec2 next_pos=mix(pos,random_pos,drop);glFragColor=pack_pos_to_rgba(next_pos);}`,"in vec2 a_pos;out vec2 v_tex_coord;void main() {v_tex_coord=0.5*(a_pos+vec2(1.0));gl_Position=vec4(a_pos,0.0,1.0);}"),symbol:ps(`#include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" #define SDF_PX 8.0 #define SDF 1.0 #define ICON 0.0 uniform sampler2D u_texture;uniform sampler2D u_texture_icon;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;uniform bool u_is_text;uniform bool u_is_halo;uniform lowp float u_scale_factor; #ifdef ICON_TRANSITION uniform float u_icon_transition; #endif #ifdef COLOR_ADJUSTMENT uniform mat4 u_color_adj_mat; #endif #ifdef INDICATOR_CUTOUT in highp float v_z_offset; #else #ifdef RENDER_SHADOWS in highp float v_z_offset; #endif #endif in vec2 v_tex_a; #ifdef ICON_TRANSITION in vec2 v_tex_b; #endif in float v_draw_halo;in vec3 v_gamma_scale_size_fade_opacity; #ifdef RENDER_TEXT_AND_SYMBOL in float is_sdf;in vec2 v_tex_a_icon; #endif #ifdef RENDER_SHADOWS uniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth; #endif #ifdef APPLY_LUT_ON_GPU uniform highp sampler3D u_lutTexture; #endif #pragma mapbox: define highp vec4 fill_color #pragma mapbox: define highp vec4 halo_color #pragma mapbox: define lowp float opacity #pragma mapbox: define lowp float halo_width #pragma mapbox: define lowp float halo_blur #pragma mapbox: define lowp float emissive_strength void main() { #pragma mapbox: initialize highp vec4 fill_color #pragma mapbox: initialize highp vec4 halo_color #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize lowp float halo_width #pragma mapbox: initialize lowp float halo_blur #pragma mapbox: initialize lowp float emissive_strength vec4 out_color;float fade_opacity=v_gamma_scale_size_fade_opacity[2]; #ifdef RENDER_TEXT_AND_SYMBOL if (is_sdf==ICON) {vec2 tex_icon=v_tex_a_icon;lowp float alpha=opacity*fade_opacity;glFragColor=texture(u_texture_icon,tex_icon)*alpha; #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif return;} #endif #ifdef RENDER_SDF float EDGE_GAMMA=0.105/u_device_pixel_ratio;float gamma_scale=v_gamma_scale_size_fade_opacity.x;float size=v_gamma_scale_size_fade_opacity.y;float fontScale=u_is_text ? size/24.0 : size;out_color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float buff=(256.0-64.0)/256.0;bool draw_halo=v_draw_halo > 0.0;if (draw_halo) {out_color=halo_color;gamma=(halo_blur*u_scale_factor*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);buff=(6.0-halo_width*u_scale_factor/fontScale)/SDF_PX;}lowp float dist=texture(u_texture,v_tex_a).r;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(buff-gamma_scaled,buff+gamma_scaled,dist);out_color*=alpha; #else #ifdef ICON_TRANSITION vec4 a=texture(u_texture,v_tex_a)*(1.0-u_icon_transition);vec4 b=texture(u_texture,v_tex_b)*u_icon_transition;out_color=(a+b); #else out_color=texture(u_texture,v_tex_a); #endif #ifdef APPLY_LUT_ON_GPU out_color=applyLUT(u_lutTexture,out_color); #endif #ifdef COLOR_ADJUSTMENT out_color=u_color_adj_mat*out_color; #endif #endif out_color*=opacity*fade_opacity; #ifdef LIGHTING_3D_MODE out_color=apply_lighting_with_emission_ground(out_color,emissive_strength); #ifdef RENDER_SHADOWS float light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth); #ifdef TERRAIN out_color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light); #else out_color.rgb*=mix(v_z_offset !=0.0 ? u_ground_shadow_factor : vec3(1.0),vec3(1.0),light); #endif #endif #endif #ifdef INDICATOR_CUTOUT out_color=applyCutout(out_color,v_z_offset); #endif #ifdef FEATURE_CUTOUT out_color=apply_feature_cutout(out_color,gl_FragCoord); #endif glFragColor=out_color; #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_terrain.vertex.glsl" #include "_prelude_shadow.vertex.glsl" #define APPEARANCE_ICON 1.0 in vec4 a_pos_offset;in vec4 a_tex_size;in vec4 a_pixeloffset;in vec4 a_projected_pos;in float a_fade_opacity; #ifdef Z_OFFSET in float a_auto_z_offset; #endif #ifdef PROJECTION_GLOBE_VIEW in vec3 a_globe_anchor;in vec3 a_globe_normal; #endif #ifdef ICON_TRANSITION in vec2 a_texb; #endif #ifdef OCCLUSION_QUERIES in float a_occlusion_query_opacity; #endif #ifdef ELEVATED_ROADS in vec3 a_x_axis;in vec3 a_y_axis;uniform float u_normal_scale; #endif #ifdef INDICATOR_CUTOUT out highp float v_z_offset; #else #ifdef RENDER_SHADOWS out highp float v_z_offset; #endif #endif uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_matrix;uniform mat4 u_inv_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_elevation_from_sea;uniform bool u_pitch_with_map;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec3 u_up_vector;uniform vec2 u_texsize_icon;uniform bool u_is_halo; #ifdef PROJECTION_GLOBE_VIEW uniform vec3 u_tile_id;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform vec3 u_camera_forward;uniform float u_zoom_transition;uniform vec3 u_ecef_origin;uniform mat4 u_tile_matrix; #endif out vec2 v_tex_a; #ifdef ICON_TRANSITION out vec2 v_tex_b; #endif out float v_draw_halo;out vec3 v_gamma_scale_size_fade_opacity; #ifdef RENDER_TEXT_AND_SYMBOL out float is_sdf;out vec2 v_tex_a_icon; #endif #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth; #endif #pragma mapbox: define highp vec4 fill_color #pragma mapbox: define highp vec4 halo_color #pragma mapbox: define lowp float opacity #pragma mapbox: define lowp float halo_width #pragma mapbox: define lowp float halo_blur #pragma mapbox: define lowp float emissive_strength #pragma mapbox: define lowp float occlusion_opacity #pragma mapbox: define lowp float z_offset void main() { #pragma mapbox: initialize highp vec4 fill_color #pragma mapbox: initialize highp vec4 halo_color #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize lowp float halo_width #pragma mapbox: initialize lowp float halo_blur #pragma mapbox: initialize lowp float emissive_strength #pragma mapbox: initialize lowp float occlusion_opacity #pragma mapbox: initialize lowp float z_offset vec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_tex_size.xy;vec2 a_size=a_tex_size.zw;float a_size_min=floor(a_size[0]*0.5);float a_size_max= floor(a_size[1]*0.5);float a_apperance_icon=a_size[1]-2.0*a_size_max;vec2 a_pxoffset=a_pixeloffset.xy;vec2 a_min_font_scale=a_pixeloffset.zw/256.0;highp float segment_angle=-a_projected_pos[3];float size;if (a_apperance_icon==APPEARANCE_ICON) {size=a_size_max/128.0;} else if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size_max,u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 tile_anchor=a_pos;float e=u_elevation_from_sea ? z_offset : z_offset+elevation(tile_anchor); #ifdef Z_OFFSET e+=a_auto_z_offset; #endif vec3 h=elevationVector(tile_anchor)*e;float globe_occlusion_fade;vec3 world_pos;vec3 mercator_pos;vec3 world_pos_globe; #ifdef PROJECTION_GLOBE_VIEW mercator_pos=mercator_tile_position(u_inv_rot_matrix,tile_anchor,u_tile_id,u_merc_center);world_pos_globe=a_globe_anchor+h;world_pos=mix_globe_mercator(world_pos_globe,mercator_pos,u_zoom_transition);vec4 ecef_point=u_tile_matrix*vec4(world_pos,1.0);vec3 origin_to_point=ecef_point.xyz-u_ecef_origin;globe_occlusion_fade=dot(origin_to_point,u_camera_forward) >=0.0 ? 0.0 : 1.0; #else world_pos=vec3(tile_anchor,0)+h;globe_occlusion_fade=1.0; #endif vec4 projected_point=u_matrix*vec4(world_pos,1);highp float camera_to_anchor_distance=projected_point.w;highp float distance_ratio=u_pitch_with_map ? camera_to_anchor_distance/u_camera_to_center_distance : u_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp( 0.5+0.5*distance_ratio,0.0,1.5);size*=perspective_ratio;float font_scale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetprojected_point;vec2 a; #ifdef PROJECTION_GLOBE_VIEW vec3 displacement=vec3(a_globe_normal.z,0,-a_globe_normal.x);offsetprojected_point=u_matrix*vec4(a_globe_anchor+displacement,1);vec4 projected_point_globe=u_matrix*vec4(world_pos_globe,1);a=projected_point_globe.xy/projected_point_globe.w; #else offsetprojected_point=u_matrix*vec4(tile_anchor+vec2(1,0),0,1);a=projected_point.xy/projected_point.w; #endif vec2 b=offsetprojected_point.xy/offsetprojected_point.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}vec4 projected_pos; #ifdef PROJECTION_GLOBE_VIEW #ifdef PROJECTED_POS_ON_VIEWPORT projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xyz+h,1.0); #else vec3 proj_pos=mix_globe_mercator(a_projected_pos.xyz,mercator_pos,u_zoom_transition)+h;projected_pos=u_label_plane_matrix*vec4(proj_pos,1.0); #endif #else projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy,h.z,1.0); #endif highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);float z=0.0;vec2 offset=rotation_matrix*(a_offset/32.0*max(a_min_font_scale,font_scale)+a_pxoffset/16.0); #ifdef TERRAIN #ifdef PITCH_WITH_MAP_TERRAIN vec4 tile_pos=u_label_plane_matrix_inv*vec4(a_projected_pos.xy+offset,0.0,1.0);z=elevation(tile_pos.xy); #endif #endif #ifdef Z_OFFSET z+=u_pitch_with_map ? a_auto_z_offset+z_offset : 0.0; #else z+=u_pitch_with_map ? z_offset : 0.0; #endif float occlusion_fade=globe_occlusion_fade;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float out_fade_opacity=max(0.0,min(occlusion_fade,fade_opacity[0]+fade_change)); #ifdef DEPTH_OCCLUSION float depth_occlusion=occlusionFadeMultiSample(projected_point);float depth_occlusion_multplier=mix(occlusion_opacity,1.0,depth_occlusion);out_fade_opacity*=depth_occlusion_multplier; #endif #ifdef OCCLUSION_QUERIES float occludedFadeMultiplier=mix(occlusion_opacity,1.0,a_occlusion_query_opacity);out_fade_opacity*=occludedFadeMultiplier; #endif #ifdef Z_TEST_OCCLUSION out_fade_opacity*=occlusion_opacity; #endif float alpha=opacity*out_fade_opacity;float hidden=float(alpha==0.0 || projected_point.w <=0.0 || occlusion_fade==0.0);vec3 pos; #ifdef PROJECTION_GLOBE_VIEW vec3 xAxis=u_pitch_with_map ? normalize(cross(a_globe_normal,u_up_vector)) : vec3(1,0,0);vec3 yAxis=u_pitch_with_map ? normalize(cross(a_globe_normal,xAxis)) : vec3(0,1,0);pos=projected_pos.xyz/projected_pos.w+xAxis*offset.x+yAxis*offset.y; #else #ifdef ELEVATED_ROADS vec3 xAxis=vec3(a_x_axis.xy,a_x_axis.z*u_normal_scale);vec3 yAxis=vec3(a_y_axis.xy,a_y_axis.z*u_normal_scale);pos=projected_pos.xyz/projected_pos.w+xAxis*offset.x+yAxis*offset.y; #else pos=vec3(projected_pos.xy/projected_pos.w+offset,z); #endif #endif gl_Position=mix(u_coord_matrix*vec4(pos,1.0),AWAY,hidden);float gamma_scale=gl_Position.w;v_draw_halo=(u_is_halo && float(gl_InstanceID)==0.0) ? 1.0 : 0.0;v_gamma_scale_size_fade_opacity=vec3(gamma_scale,size,out_fade_opacity);v_tex_a=a_tex/u_texsize; #ifdef RENDER_TEXT_AND_SYMBOL is_sdf=a_size[0]-2.0*a_size_min;v_tex_a_icon=a_tex/u_texsize_icon; #endif #ifdef ICON_TRANSITION v_tex_b=a_texb/u_texsize; #endif #ifdef RENDER_SHADOWS vec4 shd_pos=u_inv_matrix*vec4(pos,1.0);vec3 shd_pos0=shd_pos.xyz;vec3 shd_pos1=shd_pos.xyz; #ifdef NORMAL_OFFSET vec3 shd_pos_offset=shadow_normal_offset(vec3(0.0,0.0,1.0));shd_pos0+=shd_pos_offset*shadow_normal_offset_multiplier0();shd_pos1+=shd_pos_offset*shadow_normal_offset_multiplier1(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w; #endif #ifdef INDICATOR_CUTOUT v_z_offset=e; #else #ifdef RENDER_SHADOWS v_z_offset=e; #endif #endif }`),terrainRaster:ps(`#include "_prelude_fog.fragment.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_lighting.glsl" uniform sampler2D u_image0; #ifdef LIGHTING_3D_ALPHA_EMISSIVENESS uniform sampler2D u_image1;uniform float u_emissive_texture_available; #endif in vec2 v_pos0; #ifdef FOG in float v_fog_opacity; #endif #ifdef RENDER_SHADOWS in vec4 v_pos_light_view_0;in vec4 v_pos_light_view_1; #endif uniform vec3 u_ground_shadow_factor;void main() {vec4 image_color=texture(u_image0,v_pos0);vec4 color; #ifdef LIGHTING_3D_MODE const vec3 normal=vec3(0.0,0.0,1.0); #ifdef RENDER_SHADOWS float cutoffOpacity=1.0; #ifdef RENDER_CUTOFF cutoffOpacity=cutoff_opacity(u_cutoff_params,1.0/gl_FragCoord.w); #endif #ifdef LIGHTING_3D_ALPHA_EMISSIVENESS float emissive_strength=u_emissive_texture_available > 0.5 ? texture(u_image1,v_pos0).r : image_color.a;vec3 unlit_base=image_color.rgb*(1.0-emissive_strength);vec3 emissive_base=image_color.rgb*emissive_strength;float ndotl=u_shadow_direction.z;float occlusion=ndotl < 0.0 ? 1.0 : shadow_occlusion(v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w,0.0);ndotl=max(0.0,ndotl);vec3 lit=apply_lighting(unlit_base,normal,mix(1.0,(1.0-(u_shadow_intensity*occlusion))*ndotl,cutoffOpacity));vec3 emissive=compute_emissive_draped(emissive_base,1.0-u_shadow_intensity,occlusion,u_ground_shadow_factor);color.rgb=lit+emissive;color.a=1.0; #else float lighting_factor=shadowed_light_factor_normal_unbiased(normal,v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w);color=apply_lighting(image_color,normal,mix(1.0,lighting_factor,cutoffOpacity)); #endif #else float lighting_factor=u_lighting_directional_dir.z;color=apply_lighting(image_color,normal,lighting_factor); #ifdef LIGHTING_3D_ALPHA_EMISSIVENESS float emissive_strength=u_emissive_texture_available > 0.5 ? texture(u_image1,v_pos0).r : image_color.a;color.rgb=mix(color.rgb,image_color.rgb,emissive_strength);color.a=1.0; #endif #endif #else color=image_color; #endif #ifdef FOG #ifdef ZERO_EXAGGERATION color=fog_dither(fog_apply_premultiplied(color,v_fog_pos)); #else color=fog_dither(fog_apply_from_vert(color,v_fog_opacity)); #endif #endif glFragColor=color; #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_terrain.vertex.glsl" uniform mat4 u_matrix;uniform float u_skirt_height;in vec2 a_pos;out vec2 v_pos0; #ifdef FOG out float v_fog_opacity; #endif #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out vec4 v_pos_light_view_0;out vec4 v_pos_light_view_1; #endif void main() {vec3 decomposedPosAndSkirt=decomposeToPosAndSkirt(a_pos);float skirt=decomposedPosAndSkirt.z;vec2 decodedPos=decomposedPosAndSkirt.xy;float elevation=elevation(decodedPos)-skirt*u_skirt_height;v_pos0=decodedPos/8192.0;gl_Position=u_matrix*vec4(decodedPos,elevation,1.0); #ifdef FOG #ifdef ZERO_EXAGGERATION v_fog_pos=fog_position(decodedPos); #else v_fog_opacity=fog(fog_position(vec3(decodedPos,elevation))); #endif #endif #ifdef RENDER_SHADOWS vec3 pos=vec3(decodedPos,elevation);v_pos_light_view_0=u_light_matrix_0*vec4(pos,1.);v_pos_light_view_1=u_light_matrix_1*vec4(pos,1.); #endif }`),terrainDepth:ps("precision highp float;in float v_depth;void main() {glFragColor=pack_depth(v_depth);}",`#include "_prelude_terrain.vertex.glsl" uniform mat4 u_matrix;in vec2 a_pos;out float v_depth;void main() {float elevation=elevation(a_pos);gl_Position=u_matrix*vec4(a_pos,elevation,1.0);v_depth=gl_Position.z/gl_Position.w;}`),skybox:ps(`#include "_prelude_fog.fragment.glsl" in lowp vec3 v_uv;uniform lowp samplerCube u_cubemap;uniform lowp float u_opacity;uniform highp float u_temporal_offset;uniform highp vec3 u_sun_direction;float sun_disk(highp vec3 ray_direction,highp vec3 sun_direction) {highp float cos_angle=dot(normalize(ray_direction),sun_direction);const highp float cos_sun_angular_diameter=0.99996192306;const highp float smoothstep_delta=1e-5;return smoothstep( cos_sun_angular_diameter-smoothstep_delta,cos_sun_angular_diameter+smoothstep_delta,cos_angle);}float map(float value,float start,float end,float new_start,float new_end) {return ((value-start)*(new_end-new_start))/(end-start)+new_start;}void main() {vec3 uv=v_uv;const float y_bias=0.015;uv.y+=y_bias;uv.y=pow(abs(uv.y),1.0/5.0);uv.y=map(uv.y,0.0,1.0,-1.0,1.0);vec3 sky_color=texture(u_cubemap,uv).rgb; #ifdef FOG sky_color=fog_apply_sky_gradient(v_uv.xzy,sky_color); #endif sky_color+=0.1*sun_disk(v_uv,u_sun_direction);glFragColor=vec4(sky_color*u_opacity,u_opacity); #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif }`,I0),skyboxGradient:ps(`#include "_prelude_fog.fragment.glsl" in highp vec3 v_uv;uniform lowp sampler2D u_color_ramp;uniform highp vec3 u_center_direction;uniform lowp float u_radius;uniform lowp float u_opacity;uniform highp float u_temporal_offset;void main() {float progress=acos(dot(normalize(v_uv),u_center_direction))/u_radius;vec4 color=texture(u_color_ramp,vec2(progress,0.5)); #ifdef FOG color.rgb=fog_apply_sky_gradient(v_uv.xzy,color.rgb/color.a)*color.a; #endif color*=u_opacity;glFragColor=color; #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif }`,I0),skyboxCapture:ps(` in highp vec3 v_position;uniform highp float u_sun_intensity;uniform highp float u_luminance;uniform lowp vec3 u_sun_direction;uniform highp vec4 u_color_tint_r;uniform highp vec4 u_color_tint_m;precision highp float; #define BETA_R vec3(5.5e-6,13.0e-6,22.4e-6) #define BETA_M vec3(21e-6,21e-6,21e-6) #define MIE_G 0.76 #define DENSITY_HEIGHT_SCALE_R 8000.0 #define DENSITY_HEIGHT_SCALE_M 1200.0 #define PLANET_RADIUS 6360e3 #define ATMOSPHERE_RADIUS 6420e3 #define SAMPLE_STEPS 10 #define DENSITY_STEPS 4 float ray_sphere_exit(vec3 orig,vec3 dir,float radius) {float a=dot(dir,dir);float b=2.0*dot(dir,orig);float c=dot(orig,orig)-radius*radius;float d=sqrt(b*b-4.0*a*c);return (-b+d)/(2.0*a);}vec3 extinction(vec2 density) {return exp(-vec3(BETA_R*u_color_tint_r.a*density.x+BETA_M*u_color_tint_m.a*density.y));}vec2 local_density(vec3 point) {float height=max(length(point)-PLANET_RADIUS,0.0);float exp_r=exp(-height/DENSITY_HEIGHT_SCALE_R);float exp_m=exp(-height/DENSITY_HEIGHT_SCALE_M);return vec2(exp_r,exp_m);}float phase_ray(float cos_angle) {return (3.0/(16.0*PI))*(1.0+cos_angle*cos_angle);}float phase_mie(float cos_angle) {return (3.0/(8.0*PI))*((1.0-MIE_G*MIE_G)*(1.0+cos_angle*cos_angle))/((2.0+MIE_G*MIE_G)*pow(1.0+MIE_G*MIE_G-2.0*MIE_G*cos_angle,1.5));}vec2 density_to_atmosphere(vec3 point,vec3 light_dir) {float ray_len=ray_sphere_exit(point,light_dir,ATMOSPHERE_RADIUS);float step_len=ray_len/float(DENSITY_STEPS);vec2 density_point_to_atmosphere=vec2(0.0);for (int i=0; i < DENSITY_STEPS;++i) {vec3 point_on_ray=point+light_dir*((float(i)+0.5)*step_len);density_point_to_atmosphere+=local_density(point_on_ray)*step_len;;}return density_point_to_atmosphere;}vec3 atmosphere(vec3 ray_dir,vec3 sun_direction,float sun_intensity) {vec2 density_orig_to_point=vec2(0.0);vec3 scatter_r=vec3(0.0);vec3 scatter_m=vec3(0.0);vec3 origin=vec3(0.0,PLANET_RADIUS,0.0);float ray_len=ray_sphere_exit(origin,ray_dir,ATMOSPHERE_RADIUS);float step_len=ray_len/float(SAMPLE_STEPS);for (int i=0; i < SAMPLE_STEPS;++i) {vec3 point_on_ray=origin+ray_dir*((float(i)+0.5)*step_len);vec2 density=local_density(point_on_ray)*step_len;density_orig_to_point+=density;vec2 density_point_to_atmosphere=density_to_atmosphere(point_on_ray,sun_direction);vec2 density_orig_to_atmosphere=density_orig_to_point+density_point_to_atmosphere;vec3 extinction=extinction(density_orig_to_atmosphere);scatter_r+=density.x*extinction;scatter_m+=density.y*extinction;}float cos_angle=dot(ray_dir,sun_direction);float phase_r=phase_ray(cos_angle);float phase_m=phase_mie(cos_angle);vec3 beta_r=BETA_R*u_color_tint_r.rgb*u_color_tint_r.a;vec3 beta_m=BETA_M*u_color_tint_m.rgb*u_color_tint_m.a;return (scatter_r*phase_r*beta_r+scatter_m*phase_m*beta_m)*sun_intensity;}const float A=0.15;const float B=0.50;const float C=0.10;const float D=0.20;const float E=0.02;const float F=0.30;vec3 uncharted2_tonemap(vec3 x) {return ((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;}void main() {vec3 ray_direction=v_position;ray_direction.y=pow(ray_direction.y,5.0);const float y_bias=0.015;ray_direction.y+=y_bias;vec3 color=atmosphere(normalize(ray_direction),u_sun_direction,u_sun_intensity);float white_scale=1.0748724675633854;color=uncharted2_tonemap((log2(2.0/pow(u_luminance,4.0)))*color)*white_scale;glFragColor=vec4(color,1.0);}`,"in highp vec3 a_pos_3f;uniform mat3 u_matrix_3f;out highp vec3 v_position;float map(float value,float start,float end,float new_start,float new_end) {return ((value-start)*(new_end-new_start))/(end-start)+new_start;}void main() {vec4 pos=vec4(u_matrix_3f*a_pos_3f,1.0);v_position=pos.xyz;v_position.y*=-1.0;v_position.y=map(v_position.y,-1.0,1.0,0.0,1.0);gl_Position=vec4(a_pos_3f.xy,0.0,1.0);}"),globeRaster:ps(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" uniform sampler2D u_image0; #ifdef LIGHTING_3D_ALPHA_EMISSIVENESS uniform sampler2D u_image1;uniform float u_emissive_texture_available; #endif uniform float u_far_z_cutoff;in vec2 v_pos0; #ifndef FOG uniform highp vec3 u_frustum_tl;uniform highp vec3 u_frustum_tr;uniform highp vec3 u_frustum_br;uniform highp vec3 u_frustum_bl;uniform highp vec3 u_globe_pos;uniform highp float u_globe_radius;uniform vec2 u_viewport; #endif void main() {vec4 color; #ifdef CUSTOM_ANTIALIASING highp vec2 uv=gl_FragCoord.xy/u_viewport; #ifdef FLIP_Y uv.y=1.0-uv.y; #endif highp vec3 ray_dir=mix( mix(u_frustum_tl,u_frustum_tr,uv.x),mix(u_frustum_bl,u_frustum_br,uv.x),1.0-uv.y);highp vec3 dir=normalize(ray_dir);highp vec3 closest_point=dot(u_globe_pos,dir)*dir;highp float norm_dist_from_center=1.0-length(closest_point-u_globe_pos)/u_globe_radius;const float antialias_pixel=2.0;highp float antialias_factor=antialias_pixel*fwidth(norm_dist_from_center);highp float antialias=smoothstep(0.0,antialias_factor,norm_dist_from_center);vec4 raster=texture(u_image0,v_pos0); #ifdef LIGHTING_3D_MODE #ifdef LIGHTING_3D_ALPHA_EMISSIVENESS float emissive_strength=u_emissive_texture_available > 0.5 ? texture(u_image1,v_pos0).r : raster.a;raster=apply_lighting_with_emission_ground(raster,emissive_strength);color=vec4(clamp(raster.rgb,vec3(0),vec3(1))*antialias,antialias); #else raster=apply_lighting_ground(raster);color=vec4(raster.rgb*antialias,raster.a*antialias); #endif #else color=vec4(raster.rgb*antialias,raster.a*antialias); #endif #else color=texture(u_image0,v_pos0); #ifdef LIGHTING_3D_MODE #ifdef LIGHTING_3D_ALPHA_EMISSIVENESS float emissive_strength=u_emissive_texture_available > 0.5 ? texture(u_image1,v_pos0).r : color.a;color=apply_lighting_with_emission_ground(color,emissive_strength);color.a=1.0; #else color=apply_lighting_ground(color); #endif #endif #endif #ifdef FOG color=fog_dither(fog_apply_premultiplied(color,v_fog_pos)); #endif color*=1.0-step(u_far_z_cutoff,1.0/gl_FragCoord.w);glFragColor=color; #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_terrain.vertex.glsl" uniform mat4 u_proj_matrix;uniform mat4 u_normalize_matrix;uniform mat4 u_globe_matrix;uniform mat4 u_merc_matrix;uniform float u_zoom_transition;uniform vec2 u_merc_center;uniform mat3 u_grid_matrix;uniform float u_skirt_height; #ifdef GLOBE_POLES in vec3 a_globe_pos;in vec2 a_uv; #else in vec2 a_pos; #endif out vec2 v_pos0;void main() { #ifdef GLOBE_POLES vec3 globe_pos=a_globe_pos;vec2 uv=a_uv; #else float tiles=u_grid_matrix[0][2];float idx=u_grid_matrix[1][2];float idy=u_grid_matrix[2][2];vec3 decomposed_pos_and_skirt=decomposeToPosAndSkirt(a_pos);vec3 latLng=u_grid_matrix*vec3(decomposed_pos_and_skirt.xy,1.0);float mercatorY=mercatorYfromLat(latLng[0]);float uvY=mercatorY*tiles-idy;float mercatorX=mercatorXfromLng(latLng[1]);float uvX=mercatorX*tiles-idx;vec3 globe_pos=latLngToECEF(latLng.xy);vec2 merc_pos=vec2(mercatorX,mercatorY);vec2 uv=vec2(uvX,uvY); #endif v_pos0=uv;vec2 tile_pos=uv*EXTENT;vec3 globe_derived_up_vector=normalize(globe_pos)*u_tile_up_scale; #ifdef GLOBE_POLES vec3 up_vector=globe_derived_up_vector; #else vec3 up_vector=elevationVector(tile_pos); #endif float height=elevation(tile_pos);globe_pos+=up_vector*height; #ifndef GLOBE_POLES globe_pos-=globe_derived_up_vector*u_skirt_height*decomposed_pos_and_skirt.z; #endif #ifdef GLOBE_POLES vec4 interpolated_pos=u_globe_matrix*vec4(globe_pos,1.0); #else vec4 globe_world_pos=u_globe_matrix*vec4(globe_pos,1.0);vec4 merc_world_pos=vec4(0.0);if (u_zoom_transition > 0.0) {merc_world_pos=vec4(merc_pos,height-u_skirt_height*decomposed_pos_and_skirt.z,1.0);merc_world_pos.xy-=u_merc_center;merc_world_pos.x=wrap(merc_world_pos.x,-0.5,0.5);merc_world_pos=u_merc_matrix*merc_world_pos;}vec4 interpolated_pos=vec4(mix(globe_world_pos.xyz,merc_world_pos.xyz,u_zoom_transition),1.0); #endif gl_Position=u_proj_matrix*interpolated_pos; #ifdef FOG v_fog_pos=fog_position((u_normalize_matrix*vec4(globe_pos,1.0)).xyz); #endif }`),globeAtmosphere:ps(`#include "_prelude_fog.fragment.glsl" uniform float u_transition;uniform highp float u_fadeout_range;uniform highp float u_temporal_offset;uniform vec4 u_atmosphere_fog_color;uniform vec4 u_high_color;uniform vec4 u_space_color;uniform float u_horizon_angle;in highp vec3 v_ray_dir;in highp vec3 v_horizon_dir;void main() {highp vec3 dir=normalize(v_ray_dir);float globe_pos_dot_dir; #ifdef PROJECTION_GLOBE_VIEW globe_pos_dot_dir=dot(u_globe_pos,dir);highp vec3 closest_point_forward=abs(globe_pos_dot_dir)*dir;float norm_dist_from_center=length(closest_point_forward-u_globe_pos)/u_globe_radius;if (norm_dist_from_center < 0.98) { #ifdef ALPHA_PASS glFragColor=vec4(0,0,0,0);return; #else #ifdef NATIVE glFragColor=vec4(1,1,1,1); #else glFragColor=vec4(0,0,0,1); #endif return; #endif } #endif highp vec3 horizon_dir=normalize(v_horizon_dir);float horizon_angle_mercator=dir.y < horizon_dir.y ? 0.0 : max(acos(clamp(dot(dir,horizon_dir),-1.0,1.0)),0.0);float horizon_angle; #ifdef PROJECTION_GLOBE_VIEW highp vec3 closest_point=globe_pos_dot_dir*dir;highp float closest_point_to_center=length(closest_point-u_globe_pos);highp float theta=asin(clamp(closest_point_to_center/length(u_globe_pos),-1.0,1.0));horizon_angle=globe_pos_dot_dir < 0.0 ? PI-theta-u_horizon_angle : theta-u_horizon_angle;float angle_t=pow(u_transition,10.0);horizon_angle=mix(horizon_angle,horizon_angle_mercator,angle_t); #else horizon_angle=horizon_angle_mercator; #endif horizon_angle/=PI;float t=exp(-horizon_angle/u_fadeout_range);float alpha_0=u_atmosphere_fog_color.a;float alpha_1=u_high_color.a;float alpha_2=u_space_color.a;vec3 color_stop_0=u_atmosphere_fog_color.rgb;vec3 color_stop_1=u_high_color.rgb;vec3 color_stop_2=u_space_color.rgb; #ifdef ALPHA_PASS float a0=mix(alpha_2,1.0,alpha_1);float a1=mix(a0,1.0,alpha_0);float a2=mix(a0,a1,t);float a =mix(alpha_2,a2,t);glFragColor=vec4(1.0,1.0,1.0,a); #else vec3 c0=mix(color_stop_2,color_stop_1,alpha_1);vec3 c1=mix(c0,color_stop_0,alpha_0);vec3 c2=mix(c0,c1,t);vec3 c=c2;glFragColor=vec4(c*t,t); #endif }`,`in vec3 a_pos;in vec2 a_uv;uniform vec3 u_frustum_tl;uniform vec3 u_frustum_tr;uniform vec3 u_frustum_br;uniform vec3 u_frustum_bl;uniform float u_horizon;out highp vec3 v_ray_dir;out highp vec3 v_horizon_dir;void main() {v_ray_dir=mix( mix(u_frustum_tl,u_frustum_tr,a_uv.x),mix(u_frustum_bl,u_frustum_br,a_uv.x),a_uv.y);v_horizon_dir=mix( mix(u_frustum_tl,u_frustum_bl,u_horizon),mix(u_frustum_tr,u_frustum_br,u_horizon),a_uv.x);gl_Position=vec4(a_pos,1.0);}`),model:ps(`#include "_prelude_fog.fragment.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_lighting.glsl" uniform float u_opacity;uniform vec3 u_lightcolor;uniform vec3 u_lightpos;uniform float u_lightintensity;uniform vec4 u_baseColorFactor;uniform vec4 u_emissiveFactor;uniform float u_metallicFactor;uniform float u_roughnessFactor;uniform float u_emissive_strength;in highp vec4 v_position_height;in lowp vec4 v_color_mix; #ifdef RENDER_SHADOWS in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in float v_depth_shadows; #endif #ifdef OCCLUSION_TEXTURE_TRANSFORM uniform vec4 u_occlusionTextureTransform; #endif #pragma mapbox: define-attribute highp vec3 normal_3f #pragma mapbox: define-attribute highp vec3 color_3f #pragma mapbox: define-attribute highp vec4 color_4f #pragma mapbox: define-attribute highp vec2 uv_2f #pragma mapbox: initialize-attribute highp vec3 normal_3f #pragma mapbox: initialize-attribute highp vec3 color_3f #pragma mapbox: initialize-attribute highp vec4 color_4f #pragma mapbox: initialize-attribute highp vec2 uv_2f #ifdef HAS_ATTRIBUTE_a_pbr in lowp vec4 v_roughness_metallic_emissive_alpha;in mediump vec4 v_height_based_emission_params; #endif #ifdef HAS_TEXTURE_u_baseColorTexture uniform sampler2D u_baseColorTexture;uniform bool u_baseTextureIsAlpha;uniform bool u_alphaMask;uniform float u_alphaCutoff; #endif #ifdef HAS_TEXTURE_u_metallicRoughnessTexture uniform sampler2D u_metallicRoughnessTexture; #endif #ifdef HAS_TEXTURE_u_occlusionTexture uniform sampler2D u_occlusionTexture;uniform float u_aoIntensity; #endif #ifdef HAS_TEXTURE_u_normalTexture uniform sampler2D u_normalTexture; #endif #ifdef HAS_TEXTURE_u_emissionTexture uniform sampler2D u_emissionTexture; #endif #ifdef APPLY_LUT_ON_GPU uniform highp sampler3D u_lutTexture; #endif #ifdef TERRAIN_FRAGMENT_OCCLUSION in highp float v_depth;uniform highp sampler2D u_depthTexture;uniform highp vec2 u_inv_depth_size;uniform highp vec2 u_depth_range_unpack; #ifdef DEPTH_D24 highp float unpack_depth(highp float depth) {return depth*u_depth_range_unpack.x+u_depth_range_unpack.y;} #else highp float unpack_depth_rgba(highp vec4 rgba_depth) {const highp vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(rgba_depth,bit_shift)*2.0-1.0;} #endif bool isOccluded() {highp vec2 coord=gl_FragCoord.xy*u_inv_depth_size; #ifdef FLIP_Y coord.y=1.0-coord.y; #endif #ifdef DEPTH_D24 highp float depth=unpack_depth(texture(u_depthTexture,coord).r); #else highp float depth=unpack_depth_rgba(texture(u_depthTexture,coord)); #endif return v_depth > depth+0.0005;} #endif #define saturate(_x) clamp(_x,0.,1.) vec3 linearTosRGB(vec3 color) {return pow(color,vec3(1./2.2));}vec3 sRGBToLinear(vec3 srgbIn) {return pow(srgbIn,vec3(2.2));}float calculate_NdotL(vec3 normal,vec3 lightDir) {const float ext=0.70710678118;return (clamp(dot(normal,lightDir),-ext,1.0)+ext)/(1.0+ext);}vec3 getDiffuseShadedColor(vec3 albedo,vec3 normal,vec3 lightDir,vec3 lightColor) { #ifdef LIGHTING_3D_MODE vec3 transformed_normal=vec3(-normal.xy,normal.z);float lighting_factor; #ifdef RENDER_SHADOWS lighting_factor=shadowed_light_factor_normal(transformed_normal,v_pos_light_view_0,v_pos_light_view_1,v_depth_shadows); #else lighting_factor=saturate(dot(transformed_normal,u_lighting_directional_dir)); #endif return apply_lighting(albedo,transformed_normal,lighting_factor); #else vec3 n=normal;float colorvalue=((albedo.x*0.2126)+(albedo.y*0.7152))+(albedo.z*0.0722);vec3 c=vec3(0.03,0.03,0.03);float directional=clamp(dot(n,vec3(lightDir)),0.0,1.0);directional=mix(1.0-u_lightintensity,max((1.0-colorvalue)+u_lightintensity,1.0),directional);vec3 c3=c+clamp((albedo*directional)*lightColor,mix(vec3(0.0),vec3(0.3),vec3(1.0)-lightColor),vec3(1.0));return c3; #endif }vec4 getBaseColor() {vec4 albedo=u_baseColorFactor; #ifdef HAS_ATTRIBUTE_a_color_3f albedo*=vec4(color_3f,1.0); #endif #ifdef HAS_ATTRIBUTE_a_pbr #else #ifdef HAS_ATTRIBUTE_a_color_4f albedo*=color_4f; #endif #endif #if defined (HAS_TEXTURE_u_baseColorTexture) && defined (HAS_ATTRIBUTE_a_uv_2f) vec4 texColor=texture(u_baseColorTexture,uv_2f);if(u_alphaMask) {if (texColor.w < u_alphaCutoff) {discard;}} #ifdef UNPREMULT_TEXTURE_IN_SHADER if(texColor.w > 0.0) {texColor.rgb/=texColor.w;}texColor.w=1.0; #endif if(u_baseTextureIsAlpha) {if (texColor.r < 0.5) {discard;}} else {texColor.rgb=sRGBToLinear(texColor.rgb);albedo*=texColor;} #endif vec4 color=vec4(mix(albedo.rgb,v_color_mix.rgb,v_color_mix.a),albedo.a); #ifdef APPLY_LUT_ON_GPU color=applyLUT(u_lutTexture,color); #endif return color;}highp mat3 cotangentFrame(highp vec3 N,highp vec3 p,highp vec2 uv ) { #ifdef HAS_TEXTURE_u_normalTexture highp vec3 dp1=vec3(dFdx(p.x),dFdx(p.y),dFdx(p.z));highp vec3 dp2=vec3(dFdy(p.x),dFdy(p.y),dFdy(p.z));highp vec2 duv1=vec2(dFdx(uv.x),dFdx(uv.y));highp vec2 duv2=vec2(dFdy(uv.x),dFdy(uv.y));highp vec3 dp2perp=cross( dp2,N );highp vec3 dp1perp=cross( N,dp1 );highp vec3 T=dp2perp*duv1.x+dp1perp*duv2.x;highp vec3 B=dp2perp*duv1.y+dp1perp*duv2.y; #ifdef FLIP_Y T=-T;B=-B; #endif highp float lengthT=dot(T,T);highp float lengthB=dot(B,B);highp float maxLength=max(lengthT,lengthB);highp float invmax=inversesqrt( maxLength );highp mat3 res=mat3( T*invmax,B*invmax,N );return res; #else return mat3(1.0); #endif }highp vec3 getNormal(){highp vec3 n; #ifdef HAS_ATTRIBUTE_a_normal_3f n=normalize(normal_3f); #else highp vec3 fdx=vec3(dFdx(v_position_height.x),dFdx(v_position_height.y),dFdx(v_position_height.z));highp vec3 fdy=vec3(dFdy(v_position_height.x),dFdy(v_position_height.y),dFdy(v_position_height.z)); #ifdef FLIP_Y n=normalize(cross(fdx,fdy)); #else n=normalize(cross(fdx,fdy))*-1.0; #endif #endif #if defined(HAS_TEXTURE_u_normalTexture) && defined(HAS_ATTRIBUTE_a_uv_2f) vec3 nMap=texture( u_normalTexture,uv_2f).xyz;nMap=normalize(2.0*nMap-vec3(1.0));highp vec3 v=normalize(-v_position_height.xyz);highp mat3 TBN=cotangentFrame(n,v,uv_2f);n=normalize(TBN*nMap); #endif return n;}struct Material {float perceptualRoughness;float alphaRoughness;float metallic;vec3 f90;vec4 baseColor;vec3 diffuseColor;vec3 specularColor;highp vec3 normal;};Material getPBRMaterial() {Material mat;mat.baseColor=getBaseColor();mat.perceptualRoughness=u_roughnessFactor;mat.metallic=u_metallicFactor; #ifdef HAS_ATTRIBUTE_a_pbr mat.perceptualRoughness=v_roughness_metallic_emissive_alpha.x;mat.metallic=v_roughness_metallic_emissive_alpha.y;mat.baseColor.w*=v_roughness_metallic_emissive_alpha.w; #endif #if defined(HAS_TEXTURE_u_metallicRoughnessTexture) && defined(HAS_ATTRIBUTE_a_uv_2f) vec4 mrSample=texture(u_metallicRoughnessTexture,uv_2f);mat.perceptualRoughness*=mrSample.g;mat.metallic*=mrSample.b; #endif const float c_minRoughness=0.04;mat.perceptualRoughness=clamp(mat.perceptualRoughness,c_minRoughness,1.0);mat.metallic=saturate(mat.metallic);mat.alphaRoughness=mat.perceptualRoughness*mat.perceptualRoughness;const vec3 f0=vec3(0.04);mat.diffuseColor=mat.baseColor.rgb*(vec3(1.0)-f0);mat.diffuseColor*=1.0-mat.metallic;mat.specularColor=mix(f0,mat.baseColor.rgb,mat.metallic);highp float reflectance=max(max(mat.specularColor.r,mat.specularColor.g),mat.specularColor.b);highp float reflectance90=saturate(reflectance*25.0);mat.f90=vec3(reflectance90);mat.normal=getNormal();return mat;}float V_GGX(float NdotL,float NdotV,float roughness) {float a2=roughness*roughness;float GGXV=NdotL*sqrt(NdotV*NdotV*(1.0-a2)+a2);float GGXL=NdotV*sqrt(NdotL*NdotL*(1.0-a2)+a2);return 0.5/(GGXV+GGXL);}float V_GGXFast(float NdotL,float NdotV,float roughness) {float a=roughness;float GGXV=NdotL*(NdotV*(1.0-a)+a);float GGXL=NdotV*(NdotL*(1.0-a)+a);return 0.5/(GGXV+GGXL);}vec3 F_Schlick(vec3 specularColor,vec3 f90,float VdotH) {return specularColor+(f90-specularColor)*pow(clamp(1.0-VdotH,0.0,1.0),5.0);}vec3 F_SchlickFast(vec3 specularColor,float VdotH) {float x=1.0-VdotH;float x4=x*x*x*x;return specularColor+(1.0-specularColor)*x4*x;}float D_GGX(highp float NdotH,float alphaRoughness) {highp float a4=alphaRoughness*alphaRoughness;highp float f=(NdotH*a4-NdotH)*NdotH+1.0;return a4/(PI*f*f);}vec3 diffuseBurley(Material mat,float LdotH,float NdotL,float NdotV) {float f90=2.0*LdotH*LdotH*mat.alphaRoughness-0.5;return (mat.diffuseColor/PI)*(1.0+f90*pow((1.0-NdotL),5.0))*(1.0+f90*pow((1.0-NdotV),5.0));}vec3 diffuseLambertian(Material mat) { #ifdef LIGHTING_3D_MODE return mat.diffuseColor; #else return mat.diffuseColor/PI; #endif }vec3 EnvBRDFApprox(vec3 specularColor,float roughness,highp float NdotV) {vec4 c0=vec4(-1,-0.0275,-0.572,0.022);vec4 c1=vec4(1,0.0425,1.04,-0.04);highp vec4 r=roughness*c0+c1;highp float a004=min(r.x*r.x,exp2(-9.28*NdotV))*r.x+r.y;vec2 AB=vec2(-1.04,1.04)*a004+r.zw;return specularColor*AB.x+AB.y;}vec3 computeIndirectLightContribution(Material mat,float NdotV,vec3 normal) {vec3 env_light=vec3(0.65,0.65,0.65); #ifdef LIGHTING_3D_MODE float ambient_factor=calculate_ambient_directional_factor(normal);env_light=u_lighting_ambient_color*ambient_factor; #endif vec3 envBRDF=EnvBRDFApprox(mat.specularColor,mat.perceptualRoughness,NdotV);vec3 indirectSpecular= envBRDF*env_light;vec3 indirectDiffuse=mat.diffuseColor*env_light;return indirectSpecular+indirectDiffuse;}vec3 computeLightContribution(Material mat,vec3 lightPosition,vec3 lightColor) {highp vec3 n=mat.normal;highp vec3 v=normalize(-v_position_height.xyz);highp vec3 l=normalize(lightPosition);highp vec3 h=normalize(v+l);float NdotV=clamp(abs(dot(n,v)),0.001,1.0);float NdotL=saturate(dot(n,l));highp float NdotH=saturate(dot(n,h));float VdotH=saturate(dot(v,h));vec3 f=F_SchlickFast(mat.specularColor,VdotH);float g=V_GGXFast(NdotL,NdotV,mat.alphaRoughness);float d=D_GGX(NdotH,mat.alphaRoughness);vec3 diffuseTerm=(1.0-f)*diffuseLambertian(mat);vec3 specularTerm=f*g*d;vec3 transformed_normal=vec3(-n.xy,n.z);float lighting_factor; #ifdef RENDER_SHADOWS lighting_factor=shadowed_light_factor_normal(transformed_normal,v_pos_light_view_0,v_pos_light_view_1,v_depth_shadows); #else lighting_factor=NdotL; #endif vec3 directLightColor=(specularTerm+diffuseTerm)*lighting_factor*lightColor;vec3 indirectLightColor=computeIndirectLightContribution(mat,NdotV,transformed_normal);vec3 color=(saturate(directLightColor)+indirectLightColor);float intensityFactor=1.0; #if !defined(LIGHTING_3D_MODE) const vec3 luminosityFactor=vec3(0.2126,0.7152,0.0722);float luminance=dot(diffuseTerm,luminosityFactor);intensityFactor=mix((1.0-u_lightintensity),max((1.0-luminance+u_lightintensity),1.0),NdotL); #endif color*=intensityFactor;return color;}void main() { #ifdef TERRAIN_FRAGMENT_OCCLUSION if (isOccluded()) {discard;} #endif vec3 lightDir=u_lightpos;vec3 lightColor=u_lightcolor; #ifdef LIGHTING_3D_MODE lightDir=u_lighting_directional_dir;lightDir.xy=-lightDir.xy;lightColor=u_lighting_directional_color; #endif vec4 finalColor; #ifdef DIFFUSE_SHADED vec3 N=getNormal();vec3 baseColor=getBaseColor().rgb;vec3 diffuse=getDiffuseShadedColor(baseColor,N,lightDir,lightColor); #ifdef HAS_TEXTURE_u_occlusionTexture float ao=(texture(u_occlusionTexture,uv_2f).r-1.0)*u_aoIntensity+1.0;diffuse*=ao; #endif finalColor=vec4(mix(diffuse,baseColor,u_emissive_strength),1.0)*u_opacity; #else Material mat=getPBRMaterial();vec3 color=computeLightContribution(mat,lightDir,lightColor);float ao=1.0; #if defined (HAS_TEXTURE_u_occlusionTexture) && defined(HAS_ATTRIBUTE_a_uv_2f) #ifdef OCCLUSION_TEXTURE_TRANSFORM vec2 uv=uv_2f.xy*u_occlusionTextureTransform.zw+u_occlusionTextureTransform.xy; #else vec2 uv=uv_2f; #endif ao=(texture(u_occlusionTexture,uv).x-1.0)*u_aoIntensity+1.0;color*=ao; #endif vec4 emissive=u_emissiveFactor; #if defined(HAS_TEXTURE_u_emissionTexture) && defined(HAS_ATTRIBUTE_a_uv_2f) emissive.rgb*=sRGBToLinear(texture(u_emissionTexture,uv_2f).rgb); #endif #ifdef APPLY_LUT_ON_GPU float emissiveFactorLength=max(length(u_emissiveFactor.rgb),0.001);emissive.rgb=sRGBToLinear(applyLUT(u_lutTexture,linearTosRGB(emissive.rgb/emissiveFactorLength).rbg))*emissiveFactorLength; #endif color+=emissive.rgb;float opacity=mat.baseColor.w*u_opacity; #ifdef HAS_ATTRIBUTE_a_pbr float resEmission=v_roughness_metallic_emissive_alpha.z;resEmission*=v_height_based_emission_params.z+v_height_based_emission_params.w*pow(clamp(v_height_based_emission_params.x,0.0,1.0),v_height_based_emission_params.y);vec3 color_mix=v_color_mix.rgb; #ifdef APPLY_LUT_ON_GPU color_mix=applyLUT(u_lutTexture,color_mix); #endif color=mix(color,color_mix,min(1.0,resEmission)); #ifdef HAS_ATTRIBUTE_a_color_4f float distance=length(vec2(1.3*max(0.0,abs(color_4f.x)-color_4f.z),color_4f.y));distance+= mix(0.5,0.0,clamp(resEmission-1.0,0.0,1.0));opacity*=v_roughness_metallic_emissive_alpha.w*saturate(1.0-distance*distance); #endif #endif vec3 unlitColor=mat.baseColor.rgb*ao+emissive.rgb;color=mix(color,unlitColor,u_emissive_strength);color=linearTosRGB(color);color*=opacity;finalColor=vec4(color,opacity); #endif #ifdef FOG finalColor=fog_dither(fog_apply_premultiplied(finalColor,v_fog_pos,v_position_height.w)); #endif #ifdef RENDER_CUTOFF finalColor*=v_cutoff_opacity; #endif #ifdef INDICATOR_CUTOUT finalColor=applyCutout(finalColor,v_position_height.w); #endif #ifdef FEATURE_CUTOUT finalColor=apply_feature_cutout(finalColor,gl_FragCoord); #endif glFragColor=finalColor; #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_shadow.vertex.glsl" in vec3 a_pos_3f; #pragma mapbox: define-attribute highp vec3 normal_3f #pragma mapbox: define-attribute highp vec2 uv_2f #pragma mapbox: define-attribute highp vec3 color_3f #pragma mapbox: define-attribute highp vec4 color_4f #pragma mapbox: define-attribute-vertex-shader-only highp vec4 pbr #pragma mapbox: define-attribute-vertex-shader-only highp vec3 heightBasedEmissiveStrength uniform mat4 u_matrix;uniform mat4 u_node_matrix;uniform mat4 u_lighting_matrix;uniform vec3 u_camera_pos;uniform vec4 u_color_mix; #ifdef INSTANCED_ARRAYS in vec4 a_normal_matrix0;in vec4 a_normal_matrix1;in vec4 a_normal_matrix2;in vec4 a_normal_matrix3; #else uniform highp mat4 u_normal_matrix; #endif #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out float v_depth_shadows; #endif out vec4 v_position_height;out lowp vec4 v_color_mix; #ifdef TERRAIN_FRAGMENT_OCCLUSION out highp float v_depth; #endif #ifdef HAS_ATTRIBUTE_a_pbr out lowp vec4 v_roughness_metallic_emissive_alpha;out mediump vec4 v_height_based_emission_params; #endif vec3 sRGBToLinear(vec3 srgbIn) {return pow(srgbIn,vec3(2.2));}void main() { #pragma mapbox: initialize-attribute highp vec3 normal_3f #pragma mapbox: initialize-attribute highp vec2 uv_2f #pragma mapbox: initialize-attribute highp vec3 color_3f #pragma mapbox: initialize-attribute highp vec4 color_4f #pragma mapbox: initialize-attribute-custom highp vec4 pbr #pragma mapbox: initialize-attribute-custom highp vec3 heightBasedEmissiveStrength highp mat4 normal_matrix; #ifdef INSTANCED_ARRAYS normal_matrix=mat4(a_normal_matrix0,a_normal_matrix1,a_normal_matrix2,a_normal_matrix3); #else normal_matrix=u_normal_matrix; #endif vec3 local_pos;mat3 rs; #ifdef MODEL_POSITION_ON_GPU vec3 pos_color=normal_matrix[0].xyz;vec4 translate=normal_matrix[1];vec3 pos_a=floor(pos_color);vec3 rgb=1.05*(pos_color-pos_a);float hidden=float(pos_a.x > EXTENT);float color_mix=pos_a.z/100.0;v_color_mix=vec4(sRGBToLinear(rgb),color_mix);float meter_to_tile=normal_matrix[0].w;vec4 pos=vec4(pos_a.xy,translate.z,1.0);rs[0].x=normal_matrix[1].w;rs[0].yz=normal_matrix[2].xy;rs[1].xy=normal_matrix[2].zw;rs[1].z=normal_matrix[3].x;rs[2].xyz=normal_matrix[3].yzw;vec4 pos_node=u_lighting_matrix*vec4(a_pos_3f,1.0);vec3 rotated_pos_node=rs*pos_node.xyz;vec3 pos_model_tile=(rotated_pos_node+vec3(translate.xy,0.0))*vec3(meter_to_tile,meter_to_tile,1.0);pos.xyz+=pos_model_tile;local_pos=pos.xyz;gl_Position=mix(u_matrix*pos,AWAY,hidden);pos.z*=meter_to_tile;v_position_height.xyz=pos.xyz-u_camera_pos; #else local_pos=a_pos_3f;gl_Position=u_matrix*vec4(a_pos_3f,1);v_position_height.xyz=vec3(u_lighting_matrix*vec4(a_pos_3f,1));v_color_mix=vec4(sRGBToLinear(u_color_mix.rgb),u_color_mix.a); #endif v_position_height.w=a_pos_3f.z; #ifdef HAS_ATTRIBUTE_a_pbr vec4 albedo_c=decode_color(pbr.xy);vec2 e_r_m=unpack_float(pbr.z);vec2 r_m= unpack_float(e_r_m.y*16.0);r_m.r=r_m.r*16.0;v_color_mix=vec4(albedo_c.rgb,1.0);v_roughness_metallic_emissive_alpha=vec4(vec3(r_m,e_r_m.x)/255.0,albedo_c.a);v_roughness_metallic_emissive_alpha.z*=2.0;float heightBasedRelativeIntepolation=a_pos_3f.z*heightBasedEmissiveStrength.x+heightBasedEmissiveStrength.y;v_height_based_emission_params.x=heightBasedRelativeIntepolation;v_height_based_emission_params.y=heightBasedEmissiveStrength.z;vec2 emissionMultiplierValues=unpack_float(pbr.w)/256.0;v_height_based_emission_params.z=emissionMultiplierValues.x;v_height_based_emission_params.w=emissionMultiplierValues.y-emissionMultiplierValues.x; #endif #ifdef FOG v_fog_pos=fog_position(local_pos); #endif #ifdef RENDER_CUTOFF v_cutoff_opacity=cutoff_opacity(u_cutoff_params,gl_Position.z); #endif #ifdef TERRAIN_FRAGMENT_OCCLUSION v_depth=gl_Position.z/gl_Position.w; #ifdef CLIP_ZERO_TO_ONE v_depth=-1.0+2.0*v_depth; #endif #endif #ifdef HAS_ATTRIBUTE_a_normal_3f #ifdef MODEL_POSITION_ON_GPU float x_squared_scale=dot(rs[0],rs[0]);float y_squared_scale=dot(rs[1],rs[1]);float z_squared_scale=dot(rs[2],rs[2]);vec3 squared_scale=vec3(x_squared_scale,y_squared_scale,z_squared_scale);normal_3f=rs*((u_lighting_matrix*vec4(normal_3f,0.0)).xyz/squared_scale);normal_3f=normalize(normal_3f); #else normal_3f=vec3(normal_matrix*vec4(normal_3f,0)); #endif #endif #ifdef HAS_ATTRIBUTE_a_pbr #ifdef HAS_ATTRIBUTE_a_color_4f v_roughness_metallic_emissive_alpha.w=clamp(color_4f.a*v_roughness_metallic_emissive_alpha.w*(v_roughness_metallic_emissive_alpha.z-1.0),0.0,1.0); #endif #endif #ifdef RENDER_SHADOWS vec4 shadow_pos=u_node_matrix*vec4(local_pos,1.0); #ifdef NORMAL_OFFSET #ifdef HAS_ATTRIBUTE_a_normal_3f #ifdef MODEL_POSITION_ON_GPU vec3 offset=shadow_normal_offset(vec3(-normal_3f.xy,normal_3f.z));shadow_pos.xyz+=offset*shadow_normal_offset_multiplier0(); #else vec3 offset=shadow_normal_offset_model(normal_3f);shadow_pos.xyz+=offset*shadow_normal_offset_multiplier0(); #endif #endif #endif v_pos_light_view_0=u_light_matrix_0*shadow_pos;v_pos_light_view_1=u_light_matrix_1*shadow_pos;v_depth_shadows=gl_Position.w; #endif }`),modelDepth:ps(`in highp float v_depth;void main() { #ifndef DEPTH_TEXTURE glFragColor=pack_depth(v_depth); #endif }`,`in vec3 a_pos_3f;uniform mat4 u_matrix;out highp float v_depth; #ifdef MODEL_POSITION_ON_GPU #ifdef INSTANCED_ARRAYS in vec4 a_normal_matrix0;in vec4 a_normal_matrix1;in vec4 a_normal_matrix2;in vec4 a_normal_matrix3; #else uniform highp mat4 u_instance; #endif uniform highp mat4 u_node_matrix; #endif void main() { #ifdef MODEL_POSITION_ON_GPU highp mat4 instance; #ifdef INSTANCED_ARRAYS instance=mat4(a_normal_matrix0,a_normal_matrix1,a_normal_matrix2,a_normal_matrix3); #else instance=u_instance; #endif vec3 pos_color=instance[0].xyz;vec4 translate=instance[1];vec3 pos_a=floor(pos_color);float hidden=float(pos_a.x > EXTENT);float meter_to_tile=instance[0].w;vec4 pos=vec4(pos_a.xy,translate.z,1.0);mat3 rs;rs[0].x=instance[1].w;rs[0].yz=instance[2].xy;rs[1].xy=instance[2].zw;rs[1].z=instance[3].x;rs[2].xyz=instance[3].yzw;vec4 pos_node=u_node_matrix*vec4(a_pos_3f,1.0);vec3 rotated_pos_node=rs*pos_node.xyz;vec3 pos_model_tile=(rotated_pos_node+vec3(translate.xy,0.0))*vec3(meter_to_tile,meter_to_tile,1.0);pos.xyz+=pos_model_tile;gl_Position=mix(u_matrix*pos,AWAY,hidden); #else gl_Position=u_matrix*vec4(a_pos_3f,1); #endif v_depth=gl_Position.z/gl_Position.w;}`),stars:ps(`in highp vec2 v_uv;in mediump float v_intensity;float shapeCircle(in vec2 uv) {float beginFade=0.6;float lengthFromCenter=length(v_uv);return 1.0-clamp((lengthFromCenter-beginFade)/(1.0-beginFade),0.0,1.0);}void main() {float alpha=shapeCircle(v_uv);vec3 color=vec3(1.0,1.0,1.0);alpha*=v_intensity;glFragColor=vec4(color*alpha,alpha);HANDLE_WIREFRAME_DEBUG;}`,` in vec3 a_pos_3f;in vec2 a_uv;in float a_size_scale;in float a_fade_opacity;uniform mat4 u_matrix;uniform vec3 u_up;uniform vec3 u_right;uniform float u_intensity_multiplier;out highp vec2 v_uv;out mediump float v_intensity;void main() {v_uv=a_uv;v_intensity=a_fade_opacity*u_intensity_multiplier;vec3 pos=a_pos_3f;pos+=a_uv.x*u_right*a_size_scale;pos+=a_uv.y*u_up*a_size_scale;gl_Position=u_matrix*vec4(pos,1.0);}`),snowParticle:ps("in highp vec2 uv;in highp float alphaMultiplier;uniform vec4 u_particleColor;uniform vec2 u_simpleShapeParameters;void main() {float t=clamp((length(uv)-u_simpleShapeParameters.x)/(1.0-u_simpleShapeParameters.x),0.0,1.0);float alpha=1.0-pow(t,pow(10.0,u_simpleShapeParameters.y));alpha*=alphaMultiplier;alpha*=u_particleColor.a;vec3 color=u_particleColor.rgb*alpha;glFragColor=vec4(color,alpha) ;HANDLE_WIREFRAME_DEBUG;}",` in highp vec3 a_pos_3f;in highp vec2 a_uv;in highp vec4 a_snowParticleData;in highp vec4 a_snowParticleDataHorizontalOscillation;uniform mat4 u_modelview;uniform mat4 u_projection;uniform vec3 u_cam_pos;uniform vec2 u_screenSize;uniform float u_time;uniform float u_boxSize;uniform float u_velocityConeAperture; uniform float u_velocity;uniform vec3 u_direction;uniform float u_horizontalOscillationRadius; uniform float u_horizontalOscillationRate; uniform float u_billboardSize;uniform vec2 u_thinningCenterPos;uniform vec3 u_thinningShape;uniform float u_thinningAffectedRatio;uniform float u_thinningParticleOffset;out highp vec2 uv;out highp float alphaMultiplier;void main() {vec3 pos=a_pos_3f;float halfBoxSize=0.5*u_boxSize;pos.xyz*=halfBoxSize;pos+=u_cam_pos;float velocityConeApertureRad=radians(u_velocityConeAperture*0.5);float coneAnglePichRad=velocityConeApertureRad*a_snowParticleData.z;float coneAngleHeadingRad=a_snowParticleData.w*radians(360.0);vec3 localZ=normalize(u_direction);vec3 localX=normalize(cross(localZ,vec3(1,0,0)));vec3 localY=normalize(cross(localZ,localX));vec3 direction;direction.x=cos(coneAngleHeadingRad)*sin(coneAnglePichRad);direction.y=sin(coneAngleHeadingRad)*sin(coneAnglePichRad);direction.z=cos(coneAnglePichRad);direction=normalize(direction);vec3 simPosLocal=vec3(0,0,0);float velocityScale=(1.0+3.0*a_snowParticleData.y)*u_velocity;simPosLocal+=direction*velocityScale*u_time;float horizontalOscillationRadius=u_horizontalOscillationRadius*a_snowParticleDataHorizontalOscillation.x;float horizontalOscillationAngle=u_horizontalOscillationRate*u_time*(-1.0+2.0*a_snowParticleDataHorizontalOscillation.y);simPosLocal.xy+=horizontalOscillationRadius*vec2(cos(horizontalOscillationAngle),sin(horizontalOscillationAngle));vec3 simPos=localX*simPosLocal.x+ localY*simPosLocal.y+localZ*simPosLocal.z;pos+=simPos;pos=fract((pos+vec3(halfBoxSize))/vec3(u_boxSize))*u_boxSize-vec3(halfBoxSize);float clipZ=-u_cam_pos.z+pos.z;vec4 posView=u_modelview*vec4(pos,1.0);float size=u_billboardSize;alphaMultiplier=1.0;vec4 posScreen=u_projection*posView;posScreen/=posScreen.w;posScreen.xy=vec2(0.5)+posScreen.xy*0.5;posScreen.xy*=u_screenSize;vec2 thinningCenterPos=u_thinningCenterPos.xy;thinningCenterPos.y=u_screenSize.y-thinningCenterPos.y;float screenDist=length((thinningCenterPos-posScreen.xy)/(0.5*u_screenSize));screenDist+=a_snowParticleData.x*u_thinningParticleOffset;float scaleFactorMode=0.0;float thinningShapeDist=u_thinningShape.x+u_thinningShape.y;if (screenDist < thinningShapeDist) {float thinningFadeRatio=clamp((screenDist-u_thinningShape.x)/u_thinningShape.y,0.0,1.0);thinningFadeRatio=pow(thinningFadeRatio,u_thinningShape.z);if (a_snowParticleData.x < u_thinningAffectedRatio) {scaleFactorMode=1.0-thinningFadeRatio;alphaMultiplier=thinningFadeRatio;}}vec4 posScreen1=u_projection*vec4(posView.x-size,posView.yzw);posScreen1/=posScreen1.w;vec4 posScreen2=u_projection*vec4(posView.x+size,posView.yzw);posScreen2/=posScreen2.w;posScreen1.xy=vec2(0.5)+posScreen1.xy*0.5;posScreen1.xy*=u_screenSize;posScreen2.xy=vec2(0.5)+posScreen2.xy*0.5;posScreen2.xy*=u_screenSize;float screenLength=length(posScreen1.xy-posScreen2.xy);float screenEpsilon=3.0;float scaleFactor=1.0;if (screenLength < screenEpsilon) {scaleFactor=screenEpsilon/max(screenLength,0.01);scaleFactor=mix(scaleFactor,1.0,scaleFactorMode);}float screenEpsilon2=15.0;if (screenLength > screenEpsilon2) {scaleFactor=screenEpsilon2/max(screenLength,0.01);}size*=scaleFactor;vec2 right=size*vec2(1,0);vec2 up=size*vec2(0,1);posView.xy+=right*a_uv.x;posView.xy+=up*a_uv.y;uv=a_uv;gl_Position=u_projection*posView;}`),rainParticle:ps("in highp vec2 uv;in highp float particleRandomValue;uniform sampler2D u_texScreen;uniform float u_distortionStrength;uniform vec4 u_color;uniform vec2 u_thinningCenterPos;uniform vec3 u_thinningShape;uniform float u_thinningAffectedRatio;uniform float u_thinningParticleOffset;uniform float u_shapeDirectionalPower;uniform float u_mode;void main() {vec2 st=uv*0.5+vec2(0.5);vec2 uvm=uv;uvm.y=-1.0+2.0*pow(st.y,u_shapeDirectionalPower);float shape=clamp(1.0-length(uvm),0.0,1.0);float alpha=abs(shape)*u_color.a;vec2 screenSize=vec2(textureSize(u_texScreen,0));vec2 thinningCenterPos=u_thinningCenterPos.xy;thinningCenterPos.y=screenSize.y-thinningCenterPos.y;float screenDist=length((thinningCenterPos-gl_FragCoord.xy)/(0.5*screenSize));screenDist+=(0.5+0.5*particleRandomValue)*u_thinningParticleOffset;float thinningShapeDist=u_thinningShape.x+u_thinningShape.y;float thinningAlpha=1.0;if (screenDist < thinningShapeDist) {float thinningFadeRatio=clamp((screenDist-u_thinningShape.x)/u_thinningShape.y,0.0,1.0);thinningFadeRatio=pow(thinningFadeRatio,u_thinningShape.z);thinningAlpha*=thinningFadeRatio;}vec2 offsetXY=normalize(uvm)*abs(shape);vec2 stScreen=(gl_FragCoord.xy+offsetXY*u_distortionStrength*thinningAlpha)/screenSize;vec3 colorScreen=texture(u_texScreen,stScreen).rgb;alpha*=thinningAlpha;glFragColor=mix(vec4(colorScreen,1.0),vec4(u_color.rgb*alpha,alpha),u_mode);HANDLE_WIREFRAME_DEBUG;}",` in highp vec3 a_pos_3f;in highp vec2 a_uv;in highp vec4 a_rainParticleData;uniform mat4 u_modelview;uniform mat4 u_projection;uniform vec3 u_cam_pos;uniform float u_time;uniform float u_boxSize;uniform float u_velocityConeAperture; uniform float u_velocity; uniform vec2 u_rainDropletSize;uniform vec3 u_rainDirection;out highp vec2 uv;out highp float particleRandomValue;void main() {vec3 pos=a_pos_3f;float halfBoxSize=0.5*u_boxSize;pos*=halfBoxSize; pos+=u_cam_pos;float velocityConeApertureRad=radians(u_velocityConeAperture*0.5);float coneAnglePichRad=velocityConeApertureRad*a_rainParticleData.z;float coneAngleHeadingRad=a_rainParticleData.w*radians(360.0);vec3 localZ=normalize(u_rainDirection);vec3 localX=normalize(cross(localZ,vec3(1,0,0)));vec3 localY=normalize(cross(localZ,localX));vec3 directionLocal;directionLocal.x=cos(coneAngleHeadingRad)*sin(coneAnglePichRad);directionLocal.y=sin(coneAngleHeadingRad)*sin(coneAnglePichRad);directionLocal.z=cos(coneAnglePichRad);directionLocal=normalize(directionLocal);vec3 directionWorld=localX*directionLocal.x+localY*directionLocal.y+localZ*directionLocal.z;float velocityScale=(1.0+3.0*a_rainParticleData.y)*u_velocity;vec3 simPosLocal=vec3(0,0,0);simPosLocal+=directionLocal*velocityScale*u_time;vec3 simPos=localX*simPosLocal.x+ localY*simPosLocal.y+localZ*simPosLocal.z;pos+=simPos;pos=fract((pos+vec3(halfBoxSize))/vec3(u_boxSize))*u_boxSize-vec3(halfBoxSize);vec4 posView=u_modelview*vec4(pos,1.0);vec3 directionView=normalize((u_modelview*vec4(directionWorld,0.0)).xyz);vec3 side=cross(directionView,normalize(posView.xyz));posView.xyz+=side*a_uv.x*u_rainDropletSize.x;posView.xyz+=directionView*a_uv.y*u_rainDropletSize.y;uv=a_uv;particleRandomValue=a_rainParticleData.x;gl_Position=u_projection*posView;}`),vignette:ps("uniform vec3 u_vignetteShape;uniform vec4 u_vignetteColor;in vec2 st;void main() {float screenDist=length(st);float alpha=clamp((screenDist-u_vignetteShape.x)/u_vignetteShape.y,0.0,1.0);alpha=pow(alpha,u_vignetteShape.z)*u_vignetteColor.a;vec3 color=u_vignetteColor.rgb;glFragColor=vec4(color*alpha,alpha) ;}","in vec2 a_pos_2f;out vec2 st;void main() {st=a_pos_2f;gl_Position=vec4(a_pos_2f,0,1);}"),occlusion:ps("uniform vec4 u_color;void main() {glFragColor=u_color;}",`#include "_prelude_terrain.vertex.glsl" in highp vec2 a_offset_xy;uniform highp vec3 u_anchorPos;uniform mat4 u_matrix;uniform vec2 u_screenSizePx;uniform vec2 u_occluderSizePx;void main() {vec3 world_pos=u_anchorPos; #ifdef TERRAIN float e=elevation(world_pos.xy);world_pos.z+=e; #endif vec4 projected_point=u_matrix*vec4(world_pos,1.0);projected_point.xy+=projected_point.w*a_offset_xy*0.5*u_occluderSizePx/u_screenSizePx;gl_Position=projected_point;}`)};function $f(x,u){const f=x.split(` `);for(let v of f){if(v=v.trimStart(),v[0]!=="#"||!v.includes("if")||v.startsWith("#endif"))continue;const S=v.match(bS);if(S)for(const T of S)Wp.has(T)||u.add(T)}}function ps(x,u){const f=new Set,v=[],S=[];x=x.replace(Gx,(E,L)=>(S.push(L),"")),u=u.replace(Gx,(E,L)=>(v.push(L),""));let T=new Set(Gp);$f(x,T),$f(u,T);for(const E of[...v,...S])D0[E]||(D0[E]=new Set,$f(Bf[E],D0[E])),T=new Set([...T,...D0[E]]);return{fragmentSource:x=x.replace(Rd,(E,L,B,q,G)=>(f.add(G),L==="define"?` #ifndef HAS_UNIFORM_u_${G} in ${B} ${q} ${G}; #else uniform ${B} ${q} u_${G}; #endif `:L==="initialize"?` #ifdef HAS_UNIFORM_u_${G} ${B} ${q} ${G} = u_${G}; #endif `:L==="define-attribute"?` #ifdef HAS_ATTRIBUTE_a_${G} in ${B} ${q} ${G}; #endif `:L==="initialize-attribute"?"":void 0)),vertexSource:u=u.replace(Rd,(E,L,B,q,G)=>{const ee=`MATERIAL_ATTRIBUTE_OFFSET_${G}`,J=q==="float"?"vec2":q,re=`GET_ATTRIBUTE_${J}(a_${G}, materialInfo, ${ee})`,oe=G.match(/color/)?"color":J;return L==="define-attribute-vertex-shader-only"?` #ifdef HAS_ATTRIBUTE_a_${G} in ${B} ${q} a_${G}; #endif `:f.has(G)?L==="define"?` #ifndef HAS_UNIFORM_u_${G} uniform lowp float u_${G}_t; #if !defined(${ee}) in ${B} ${J} a_${G}; #endif out ${B} ${q} ${G}; #else uniform ${B} ${q} u_${G}; #endif `:L==="initialize"?oe==="vec4"?` #ifndef HAS_UNIFORM_u_${G} ${G} = a_${G}; #else ${B} ${q} ${G} = u_${G}; #endif `:` #if !defined(HAS_UNIFORM_u_${G}) #ifdef ${ee} ${G} = unpack_mix_${oe}(${re}, u_${G}_t); #else ${G} = unpack_mix_${oe}(a_${G}, u_${G}_t); #endif #else ${B} ${q} ${G} = u_${G}; #endif `:L==="define-attribute"?` #ifdef HAS_ATTRIBUTE_a_${G} in ${B} ${q} a_${G}; out ${B} ${q} ${G}; #endif `:L==="initialize-attribute"?` #ifdef HAS_ATTRIBUTE_a_${G} ${G} = a_${G}; #endif `:void 0:L==="define"?` #ifndef HAS_UNIFORM_u_${G} uniform lowp float u_${G}_t; #if !defined(${ee}) in ${B} ${J} a_${G}; #endif #else uniform ${B} ${q} u_${G}; #endif `:L==="define-instanced"?oe==="mat4"?` #ifdef INSTANCED_ARRAYS in vec4 a_${G}0; in vec4 a_${G}1; in vec4 a_${G}2; in vec4 a_${G}3; #else uniform ${B} ${q} u_${G}; #endif `:` #ifdef INSTANCED_ARRAYS in ${B} ${J} a_${G}; #else uniform ${B} ${q} u_${G}; #endif `:L==="initialize-attribute-custom"?` #ifdef HAS_ATTRIBUTE_a_${G} ${B} ${q} ${G} = a_${G}; #endif `:oe==="vec4"?` #ifndef HAS_UNIFORM_u_${G} #ifdef ${ee} ${B} ${q} ${G} = ${re}; #else ${B} ${q} ${G} = a_${G}; #endif #else ${B} ${q} ${G} = u_${G}; #endif `:` #ifndef HAS_UNIFORM_u_${G} #ifdef ${ee} ${B} ${q} ${G} = unpack_mix_${oe}(${re}, u_${G}_t); #else ${B} ${q} ${G} = unpack_mix_${oe}(a_${G}, u_${G}_t); #endif #else ${B} ${q} ${G} = u_${G}; #endif `}),usedDefines:T,vertexIncludes:v,fragmentIncludes:S}}class d4{constructor(){this.boundProgram=null,this.boundLayoutVertexBuffer=null,this.boundPaintVertexBuffers=[],this.boundIndexBuffer=null,this.boundVertexOffset=null,this.boundDynamicVertexBuffers=[],this.vao=null}bind(u,f,v,S,T,E,L,B){this.context=u;let q=this.boundPaintVertexBuffers.length!==S.length;for(let ee=0;!q&&ee{const Ze=Ae.paint.get("hillshade-shadow-color"),$e=Ae.paint.get("hillshade-shadow-color-use-theme").constantOr("default")==="none",He=Ae.paint.get("hillshade-highlight-color"),ze=Ae.paint.get("hillshade-highlight-color-use-theme").constantOr("default")==="none",De=Ae.paint.get("hillshade-accent-color"),Qe=Ae.paint.get("hillshade-accent-color-use-theme").constantOr("default")==="none",ht=Ae.paint.get("hillshade-emissive-strength");let ot=a.an(Ae.paint.get("hillshade-illumination-direction"));if(Ae.paint.get("hillshade-illumination-anchor")==="viewport")ot-=fe.transform.angle;else if(fe.style&&fe.style.enable3dLights()&&fe.style.directionalLight){const At=fe.style.directionalLight.properties.get("direction"),Bt=a.d4(At.x,At.y,At.z);ot=a.an(Bt[1])}const Tt=!fe.options.moving;return{u_matrix:Te||fe.transform.calculateProjMatrix(Ne.tileID.toUnwrapped(),Tt),u_image:0,u_latrange:h4(0,Ne.tileID),u_light:[Ae.paint.get("hillshade-exaggeration"),ot],u_shadow:Ze.toPremultipliedRenderColor($e?null:Ae.lut),u_highlight:He.toPremultipliedRenderColor(ze?null:Ae.lut),u_emissive_strength:ht,u_accent:De.toPremultipliedRenderColor(Qe?null:Ae.lut)}})(x,f,v,x.terrain?u.projMatrix:null);x.uploadCommonUniforms(L,J,u.toUnwrapped());const{tileBoundsBuffer:oe,tileBoundsIndexBuffer:se,tileBoundsSegments:me}=x.getTileBoundsBuffers(f);J.draw(x,B.TRIANGLES,S,T,E,vn.disabled,re,v.id,oe,se,me)}function jS(x,u,f){if(!u.needsDEMTextureUpload)return;const v=x.context,S=v.gl;v.pixelStoreUnpackPremultiplyAlpha.set(!1),u.demTexture=u.demTexture||x.getTileTexture(f.stride);const T=f.getPixels();u.demTexture?u.demTexture.update(T,{premultiply:!1}):u.demTexture=new a.T(v,T,S.R32F,{premultiply:!1}),u.needsDEMTextureUpload=!1}function p4(x,u,f){const v=x.context,S=v.gl;if(!u.dem)return;const T=u.dem;if(v.activeTexture.set(S.TEXTURE1),jS(x,u,T),!u.demTexture)return;u.demTexture.bind(S.NEAREST,S.CLAMP_TO_EDGE);const E=T.dim;v.activeTexture.set(S.TEXTURE0);let L=u.hillshadeFBO;if(!L){const J=new a.T(v,{width:E,height:E,data:null},S.RGBA8);J.bind(S.LINEAR,S.CLAMP_TO_EDGE),L=u.hillshadeFBO=v.createFramebuffer(E,E,1,"renderbuffer"),L.colorAttachment0.set(J.texture)}v.bindFramebuffer.set(L.framebuffer),v.viewport.set([0,0,E,E]);const{tileBoundsBuffer:B,tileBoundsIndexBuffer:q,tileBoundsSegments:G}=x.getMercatorTileBoundsBuffers(),ee=[];x.linearFloatFilteringSupported()&&ee.push("TERRAIN_DEM_FLOAT_FORMAT"),x.terrain&&x.terrain.renderingToTexture&&x.emissiveMode==="mrt-fallback"&&ee.push("USE_MRT1"),x.getOrCreateProgram("hillshadePrepare",{defines:ee}).draw(x,S.TRIANGLES,Wr.disabled,_n.disabled,En.unblended,vn.disabled,((J,re)=>{const oe=re.stride,se=a.bC();return a.ce(se,0,a.al,-a.al,0,0,1),a.br(se,se,[0,-a.al,0]),{u_matrix:se,u_image:1,u_dimension:[oe,oe],u_zoom:J.overscaledZ}})(u.tileID,T),f.id,B,q,G),u.needsHillshadePrepare=!1}class Ui{constructor(u){this.gl=u.gl,this.default=this.getDefault(),this.current=this.default,this.dirty=!1}get(){return this.current}set(u){}getDefault(){return this.default}setDefault(){this.set(this.default)}}class m4 extends Ui{getDefault(){return a.ao.transparent.toNonPremultipliedRenderColor(null)}set(u){const f=this.current;(u.r!==f.r||u.g!==f.g||u.b!==f.b||u.a!==f.a||this.dirty)&&(this.gl.clearColor(u.r,u.g,u.b,u.a),this.current=u,this.dirty=!1)}}class dE extends Ui{getDefault(){return 1}set(u){(u!==this.current||this.dirty)&&(this.gl.clearDepth(u),this.current=u,this.dirty=!1)}}class SS extends Ui{getDefault(){return 0}set(u){(u!==this.current||this.dirty)&&(this.gl.clearStencil(u),this.current=u,this.dirty=!1)}}class F0 extends Ui{getDefault(){return[!0,!0,!0,!0]}set(u){const f=this.current;(u[0]!==f[0]||u[1]!==f[1]||u[2]!==f[2]||u[3]!==f[3]||this.dirty)&&(this.gl.colorMask(u[0],u[1],u[2],u[3]),this.current=u,this.dirty=!1)}}class NS extends Ui{getDefault(){return!0}set(u){(u!==this.current||this.dirty)&&(this.gl.depthMask(u),this.current=u,this.dirty=!1)}}class Kp extends Ui{getDefault(){return 255}set(u){(u!==this.current||this.dirty)&&(this.gl.stencilMask(u),this.current=u,this.dirty=!1)}}class vg extends Ui{getDefault(){return{func:this.gl.ALWAYS,ref:0,mask:255}}set(u){const f=this.current;(u.func!==f.func||u.ref!==f.ref||u.mask!==f.mask||this.dirty)&&(this.gl.stencilFunc(u.func,u.ref,u.mask),this.current=u,this.dirty=!1)}}class Kx extends Ui{getDefault(){const u=this.gl;return[u.KEEP,u.KEEP,u.KEEP]}set(u){const f=this.current;(u[0]!==f[0]||u[1]!==f[1]||u[2]!==f[2]||this.dirty)&&(this.gl.stencilOp(u[0],u[1],u[2]),this.current=u,this.dirty=!1)}}class _g extends Ui{getDefault(){return!1}set(u){if(u===this.current&&!this.dirty)return;const f=this.gl;u?f.enable(f.STENCIL_TEST):f.disable(f.STENCIL_TEST),this.current=u,this.dirty=!1}}class hE extends Ui{getDefault(){return[0,1]}set(u){const f=this.current;(u[0]!==f[0]||u[1]!==f[1]||this.dirty)&&(this.gl.depthRange(u[0],u[1]),this.current=u,this.dirty=!1)}}class CS extends Ui{getDefault(){return!1}set(u){if(u===this.current&&!this.dirty)return;const f=this.gl;u?f.enable(f.DEPTH_TEST):f.disable(f.DEPTH_TEST),this.current=u,this.dirty=!1}}class fE extends Ui{getDefault(){return this.gl.LESS}set(u){(u!==this.current||this.dirty)&&(this.gl.depthFunc(u),this.current=u,this.dirty=!1)}}class bg extends Ui{getDefault(){return!1}set(u){if(u===this.current&&!this.dirty)return;const f=this.gl;u?f.enable(f.BLEND):f.disable(f.BLEND),this.current=u,this.dirty=!1}}class z0 extends Ui{getDefault(){const u=this.gl;return[u.ONE,u.ZERO,u.ONE,u.ZERO]}set(u){const f=this.current;(u[0]!==f[0]||u[1]!==f[1]||u[2]!==f[2]||u[3]!==f[3]||this.dirty)&&(this.gl.blendFuncSeparate(u[0],u[1],u[2],u[3]),this.current=u,this.dirty=!1)}}class B0 extends Ui{getDefault(){return a.ao.transparent.toNonPremultipliedRenderColor(null)}set(u){const f=this.current;(u.r!==f.r||u.g!==f.g||u.b!==f.b||u.a!==f.a||this.dirty)&&(this.gl.blendColor(u.r,u.g,u.b,u.a),this.current=u,this.dirty=!1)}}class kS extends Ui{getDefault(){return this.gl.FUNC_ADD}set(u){(u!==this.current||this.dirty)&&(this.gl.blendEquationSeparate(u,u),this.current=u,this.dirty=!1)}}class $0 extends Ui{getDefault(){return!1}set(u){if(u===this.current&&!this.dirty)return;const f=this.gl;u?f.enable(f.CULL_FACE):f.disable(f.CULL_FACE),this.current=u,this.dirty=!1}}class Zx extends Ui{getDefault(){return this.gl.BACK}set(u){(u!==this.current||this.dirty)&&(this.gl.cullFace(u),this.current=u,this.dirty=!1)}}class pE extends Ui{getDefault(){return this.gl.CCW}set(u){(u!==this.current||this.dirty)&&(this.gl.frontFace(u),this.current=u,this.dirty=!1)}}let mE=class extends Ui{getDefault(){return null}set(x){(x!==this.current||this.dirty)&&(this.gl.useProgram(x),this.current=x,this.dirty=!1)}};class gE extends Ui{getDefault(){return this.gl.TEXTURE0}set(u){(u!==this.current||this.dirty)&&(this.gl.activeTexture(u),this.current=u,this.dirty=!1)}}class wg extends Ui{getDefault(){const u=this.gl;return[0,0,u.drawingBufferWidth,u.drawingBufferHeight]}set(u){const f=this.current;(u[0]!==f[0]||u[1]!==f[1]||u[2]!==f[2]||u[3]!==f[3]||this.dirty)&&(this.gl.viewport(u[0],u[1],u[2],u[3]),this.current=u,this.dirty=!1)}}class yE extends Ui{getDefault(){return null}set(u){if(u===this.current&&!this.dirty)return;const f=this.gl;f.bindFramebuffer(f.FRAMEBUFFER,u),this.current=u,this.dirty=!1}}class g4 extends Ui{getDefault(){return null}set(u){if(u===this.current&&!this.dirty)return;const f=this.gl;f.bindRenderbuffer(f.RENDERBUFFER,u),this.current=u,this.dirty=!1}}class y4 extends Ui{getDefault(){return null}set(u){if(u===this.current&&!this.dirty)return;const f=this.gl;f.bindTexture(f.TEXTURE_2D,u),this.current=u,this.dirty=!1}}class x4 extends Ui{getDefault(){return null}set(u){if(u===this.current&&!this.dirty)return;const f=this.gl;f.bindBuffer(f.ARRAY_BUFFER,u),this.current=u,this.dirty=!1}}class TS extends Ui{getDefault(){return null}set(u){const f=this.gl;f.bindBuffer(f.ELEMENT_ARRAY_BUFFER,u),this.current=u,this.dirty=!1}}class ES extends Ui{getDefault(){return null}set(u){this.gl&&(u!==this.current||this.dirty)&&(this.gl.bindVertexArray(u),this.current=u,this.dirty=!1)}}class AS extends Ui{getDefault(){return 4}set(u){if(u===this.current&&!this.dirty)return;const f=this.gl;f.pixelStorei(f.UNPACK_ALIGNMENT,u),this.current=u,this.dirty=!1}}class PS extends Ui{getDefault(){return!1}set(u){if(u===this.current&&!this.dirty)return;const f=this.gl;f.pixelStorei(f.UNPACK_PREMULTIPLY_ALPHA_WEBGL,u),this.current=u,this.dirty=!1}}class xE extends Ui{getDefault(){return!1}set(u){if(u===this.current&&!this.dirty)return;const f=this.gl;f.pixelStorei(f.UNPACK_FLIP_Y_WEBGL,u),this.current=u,this.dirty=!1}}class U0 extends Ui{constructor(u,f){super(u),this.context=u,this.parent=f}getDefault(){return null}}class V0 extends U0{constructor(u,f,v=0){super(u,f),this.attachmentPoint=u.gl.COLOR_ATTACHMENT0+v}setDirty(){this.dirty=!0}set(u){if(u===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const f=this.gl;f.framebufferTexture2D(f.FRAMEBUFFER,this.attachmentPoint,f.TEXTURE_2D,u,0),this.current=u,this.dirty=!1}}class jg extends U0{attachment(){return this.gl.DEPTH_ATTACHMENT}set(u){if(u===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const f=this.gl;f.framebufferRenderbuffer(f.FRAMEBUFFER,this.attachment(),f.RENDERBUFFER,u),this.current=u,this.dirty=!1}}class Yx extends U0{attachment(){return this.gl.DEPTH_ATTACHMENT}set(u){if(u===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const f=this.gl;f.framebufferTexture2D(f.FRAMEBUFFER,this.attachment(),f.TEXTURE_2D,u,0),this.current=u,this.dirty=!1}}class vE extends jg{attachment(){return this.gl.DEPTH_STENCIL_ATTACHMENT}}const Uc=(x,u,f,v)=>({u_matrix:x,u_image0:0,u_image1:1,u_skirt_height:u,u_ground_shadow_factor:f,u_emissive_texture_available:v}),q0=(x,u,f,v,S,T,E,L,B,q,G,ee,J,re,oe,se,me)=>({u_proj_matrix:Float32Array.from(x),u_globe_matrix:u,u_normalize_matrix:Float32Array.from(v),u_merc_matrix:f,u_zoom_transition:S,u_merc_center:T,u_image0:0,u_image1:1,u_frustum_tl:E,u_frustum_tr:L,u_frustum_br:B,u_frustum_bl:q,u_globe_pos:G,u_globe_radius:ee,u_viewport:J,u_grid_matrix:me?Float32Array.from(me):new Float32Array(9),u_skirt_height:re,u_far_z_cutoff:oe,u_emissive_texture_available:se});function Xx(x,u){return x!=null&&u!=null&&!(!x.hasData()||!u.hasData())&&x.demTexture!=null&&u.demTexture!=null&&x.tileID.key!==u.tileID.key}const Th=new class{constructor(){this.operations={}}newMorphing(x,u,f,v,S){if(x in this.operations){const T=this.operations[x];T.to.tileID.key!==f.tileID.key&&(T.queued=f)}else this.operations[x]={startTime:v,phase:0,duration:S,from:u,to:f,queued:null}}getMorphValuesForProxy(x){if(!(x in this.operations))return null;const u=this.operations[x];return{from:u.from,to:u.to,phase:u.phase}}update(x){for(const u in this.operations){const f=this.operations[u];for(f.phase=(x-f.startTime)/f.duration;f.phase>=1||!this._validOp(f);)if(!this._nextOp(f,x)){delete this.operations[u];break}}}_nextOp(x,u){return!!x.queued&&(x.from=x.to,x.to=x.queued,x.queued=null,x.phase=0,x.startTime=u,!0)}_validOp(x){return x.from.hasData()&&x.to.hasData()}},H0={0:null,1:"TERRAIN_VERTEX_MORPHING"};function W0(x,u,f){if(u===0)return 0;const v=u<1&&f===514?.25/u:1;return 6*Math.pow(1.5,22-x)*Math.max(u,1)*v}function IS(x,u){const f=1<({u_matrix:x});function Jx(x,u,f,v,S){if(S>0){const T=a.o.now(),E=(T-x.timeAdded)/S,L=u?(T-u.timeAdded)/S:-1,B=f.getSource(),q=v.coveringZoomLevel({tileSize:B.tileSize,roundZoom:B.roundZoom}),G=!u||Math.abs(u.tileID.overscaledZ-q)>Math.abs(x.tileID.overscaledZ-q),ee=G&&x.refreshedUponExpiration?1:a.aA(G?E:1-L,0,1);return u?{opacity:1,mix:1-ee,isFading:E<1}:{opacity:ee,mix:0,isFading:E<1}}return{opacity:1,mix:0,isFading:!1}}class G0 extends jc{constructor(u){const f=lo("mock-dem",{type:"raster-dem",maxzoom:u.transform.maxZoom},u.style.dispatcher,u.style);super("mock-dem",f,!1),f.setEventedParent(this),this._sourceLoaded=!0}_loadTile(u,f){u.state="loaded",f(null)}}class MS extends jc{constructor(u){const f=lo("proxy",{type:"geojson",maxzoom:u.transform.maxZoom},u.style.dispatcher,u.style);super("proxy",f,!1),f.setEventedParent(this),this.map=this.getSource().map=u,this.used=this._sourceLoaded=!0,this.renderCache=[],this.renderCachePool=[],this.proxyCachedFBO={}}update(u,f,v){if(u.freezeTileCoverage)return;this.transform=u;const S=u.coveringTiles({tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled}).reduce((T,E)=>{if(T[E.key]="",!this._tiles[E.key]){const L=new Up(E,this._source.tileSize*E.overscaleFactor(),u.tileZoom,void 0,void 0,this._source.worldview);L.state="loaded",this._tiles[E.key]=L}return T},{});for(const T in this._tiles)T in S||(this.freeFBO(T),this._tiles[T].unloadVectorData(),delete this._tiles[T])}freeFBO(u){const f=this.proxyCachedFBO[u];if(f!==void 0){const v=Object.values(f);this.renderCachePool.push(...v),delete this.proxyCachedFBO[u]}}deallocRenderCache(){this.renderCache.forEach(u=>u.fb.destroy()),this.renderCache=[],this.renderCachePool=[],this.proxyCachedFBO={}}}class OS extends a.aQ{constructor(u,f,v){super(u.overscaledZ,u.wrap,u.canonical.z,u.canonical.x,u.canonical.y),this.proxyTileKey=f,this.projMatrix=v}}class RS extends a.bV{constructor(u,f){super(),this._debugParams={sortTilesHiZFirst:!0,disableRenderCache:!1},this.painter=u,this.terrainTileForTile={},this.prevTerrainTileForTile={};const[v,S,T]=function(B){const q=new a.bd,G=new a.b0,ee=131;q.reserve(17161),G.reserve(33800);const J=a.al/128,re=a.al+J/2,oe=re+J;for(let me=-J;mere||me<0||me>re?24575:0,Ae=a.aA(Math.round(fe),0,a.al),Te=a.aA(Math.round(me),0,a.al);q.emplaceBack(Ae+Ne,Te)}const se=(me,fe)=>{const Ne=fe*ee+me;G.emplaceBack(Ne+1,Ne,Ne+ee),G.emplaceBack(Ne+ee,Ne+ee+1,Ne+1)};for(let me=1;me<129;me++)for(let fe=1;fe<129;fe++)se(fe,me);return[0,129].forEach(me=>{for(let fe=0;fe<130;fe++)se(fe,me),se(me,fe)}),[q,G,32768]}(),E=u.context;this.gridBuffer=E.createVertexBuffer(v,a.bf.members),this.gridIndexBuffer=E.createIndexBuffer(S),this.gridSegments=a.bg.simpleSegment(0,0,v.length,S.length),this.gridNoSkirtSegments=a.bg.simpleSegment(0,0,v.length,T),this.proxyCoords=[],this.proxiedCoords={},this._visibleDemTiles=[],this._drapedRenderBatches=[],this._sourceTilesOverlap={},this.proxySourceCache=new MS(f.map),this.orthoMatrix=a.bC(),a.ce(this.orthoMatrix,this.painter.transform.projection.name==="globe"?.015:0,a.al,0,a.al,0,1);const L=E.gl;this._overlapStencilMode=new _n({func:L.GEQUAL,mask:255},0,255,L.KEEP,L.KEEP,L.REPLACE),this._previousZoom=u.transform.zoom,this.pool=[],this._findCoveringTileCache={},this._tilesDirty={},this.style=f,this._useVertexMorphing=!0,this._exaggeration=1,this._mockSourceCache=new G0(f.map),this._pendingGroundEffectLayers=[],this._emissiveTexture=!1}set style(u){u.on("data",this._onStyleDataEvent.bind(this)),this._style=u,this._style.map.on("moveend",()=>{this._clearLineLayersFromRenderCache()})}update(u,f,v){if(u&&u.terrain){this._style!==u&&(this.style=u,this._evaluationZoom=void 0);const S=u.terrain.properties,T=u.terrain.drapeRenderMode===0,E=u.terrain.isZoomDependent();this._previousUpdateTimestamp=this.enabled?this._updateTimestamp:void 0,this._updateTimestamp=a.o.now();const L=u.terrain&&u.terrain.scope,B=S.get("source"),q=T?this._mockSourceCache:u.getSourceCache(B,L);if(!q)return void a.w(`Couldn't find terrain source "${B}".`);if(this.sourceCache=q,this._attenuationRange=u.terrain.getAttenuationRange(),this._exaggeration=E?this.calculateExaggeration(f):S.get("exaggeration"),!f.projection.requiresDraping&&E&&this._exaggeration===0)return void this._disable();this.enabled=!0;const G=()=>{this.sourceCache.used&&a.w(`Raster DEM source '${this.sourceCache.id}' is used both for terrain and as layer source. This leads to lower resolution of hillshade. For full hillshade resolution but higher memory consumption, define another raster DEM source.`);const ee=this.getScaledDemTileSize();this.sourceCache.update(f,ee,!0),this.resetTileLookupCache(this.sourceCache.id)};this.sourceCache.usedForTerrain||(this.resetTileLookupCache(this.sourceCache.id),this.sourceCache.usedForTerrain=!0,G(),this._initializing=!0),G(),f.updateElevation(!0,v),this.resetTileLookupCache(this.proxySourceCache.id),this.proxySourceCache.update(f),this._emptyDEMTextureDirty=!0,this._previousZoom=f.zoom}else this._disable()}calculateExaggeration(u){if(this._attenuationRange&&u.zoom>=Math.ceil(this._attenuationRange[1]))return this._style.terrain.getExaggeration(u.zoom);const f=this._previousCameraAltitude,v=u.getFreeCameraOptions().position.z/u.pixelsPerMeter*u.worldSize;this._previousCameraAltitude=v;const S=f!=null?v-f:Number.MAX_VALUE;if(Math.abs(S)<2)return this._exaggeration;const T=u.zoom,E=this._style.terrain;if(!this._previousUpdateTimestamp)return E.getExaggeration(T);let L=T-this._previousZoom;const B=this._previousUpdateTimestamp;let q=T;this._evaluationZoom!=null&&(q=this._evaluationZoom,Math.abs(T-q)>.5&&(L=.5*(T-q+L)),L*S<0&&(q+=L)),this._evaluationZoom=q;const G=E.getExaggeration(q),ee=G===E.getExaggeration(Math.max(0,q-.1));if(ee&&Math.abs(G-this._exaggeration)<.01)return G;let J=Math.min(.1,.00375*(this._updateTimestamp-B));return(ee||G<.1||Math.abs(L)<1e-4)&&(J=Math.min(.2,4*J)),a.ak(this._exaggeration,G,J)}resetTileLookupCache(u){this._findCoveringTileCache[u]={}}attenuationRange(){return this._attenuationRange}getDemUpscale(){return this.proxySourceCache.getSource().tileSize/128}getScaledDemTileSize(){return this.sourceCache.getSource().tileSize/128*this.proxySourceCache.getSource().tileSize}_onStyleDataEvent(u){u.dataType==="source"&&u.coord?this._clearRenderCacheForTile(u.sourceCacheId,u.coord):u.dataType==="style"&&(this.invalidateRenderCache=!0,this._evaluationZoom=void 0,this._previousUpdateTimestamp=void 0,this._previousCameraAltitude=void 0)}_disable(){if(this.enabled&&(this.enabled=!1,this._emptyDEMTextureDirty=!0,this._sharedDepthStencil=void 0,this._evaluationZoom=void 0,this._previousUpdateTimestamp=void 0,this.proxySourceCache.deallocRenderCache(),this._style))for(const u in this._style._mergedSourceCaches)this._style._mergedSourceCaches[u].usedForTerrain=!1}destroy(){this._disable(),this._emptyDEMTexture&&this._emptyDEMTexture.destroy(),this.pool.forEach(u=>u.fb.destroy()),this.pool=[],this.framebufferCopyTexture&&this.framebufferCopyTexture.destroy()}_source(){return this.enabled?this.sourceCache:null}isUsingMockSource(){return this.sourceCache===this._mockSourceCache}exaggeration(){return this.enabled?this._exaggeration:0}get visibleDemTiles(){return this._visibleDemTiles}get drapeBufferSize(){const u=2*this.proxySourceCache.getSource().tileSize;return[u,u]}set useVertexMorphing(u){this._useVertexMorphing=u}updateTileBinding(u){if(!this.enabled)return;this.prevTerrainTileForTile=this.terrainTileForTile;const f=this.proxySourceCache,v=this.painter.transform;this._initializing&&(this._initializing=v._centerAltitude===0&&this.getAtPointOrZero(a.ae.fromLngLat(v.center),-1)===-1,this._emptyDEMTextureDirty=!this._initializing);const S=this.proxyCoords=f.getIds().map(B=>{const q=f.getTileByID(B).tileID;return q.projMatrix=v.calculateProjMatrix(q.toUnwrapped()),q});(function(B,q){const G=q.transform.pointCoordinate(q.transform.getCameraPoint()),ee=new a.P(G.x,G.y);B.sort((J,re)=>{if(re.overscaledZ-J.overscaledZ)return re.overscaledZ-J.overscaledZ;const oe=new a.P(J.canonical.x+(1<{this.proxyToSource[B.key]={}}),this.terrainTileForTile={};const E=this._style._mergedSourceCaches;for(const B in E){const q=E[B];if(!q.used||(q!==this.sourceCache&&this.resetTileLookupCache(q.id),this._setupProxiedCoordsForOrtho(q,u[B],T),q.usedForTerrain))continue;const G=u[B];q.getSource().reparseOverscaled&&this._assignTerrainTiles(G)}this.proxiedCoords[f.id]=S.map(B=>new OS(B,B.key,this.orthoMatrix)),this._assignTerrainTiles(S),this._prepareDEMTextures(),this._setupDrapedRenderBatches(),this._initFBOPool(),this._setupRenderCache(T),this.renderingToTexture=!1;const L={};this._visibleDemTiles=[];for(const B of this.proxyCoords){const q=this.terrainTileForTile[B.key];if(!q)continue;const G=q.tileID.key;G in L||(this._visibleDemTiles.push(q),L[G]=G)}}_assignTerrainTiles(u){this._initializing||u.forEach(f=>{if(this.terrainTileForTile[f.key])return;const v=this._findTileCoveringTileID(f,this.sourceCache);v&&(this.terrainTileForTile[f.key]=v)})}_prepareDEMTextures(){const u=this.painter.context,f=u.gl;for(const v in this.terrainTileForTile){const S=this.terrainTileForTile[v],T=S.dem;!T||S.demTexture&&!S.needsDEMTextureUpload||(u.activeTexture.set(f.TEXTURE1),jS(this.painter,S,T))}}_prepareDemTileUniforms(u,f,v,S){if(!f||f.demTexture==null)return!1;const T=u.tileID.canonical,E=Math.pow(2,f.tileID.canonical.z-T.z),L=S||"";return v[`u_dem_tl${L}`]=[T.x*E%1,T.y*E%1],v[`u_dem_scale${L}`]=E,!0}get emptyDEMTexture(){return!this._emptyDEMTextureDirty&&this._emptyDEMTexture?this._emptyDEMTexture:this._updateEmptyDEMTexture()}_getLoadedAreaMinimum(){if(!this.enabled)return 0;let u=0;const f=this._visibleDemTiles.reduce((v,S)=>{if(!S.dem)return v;const T=S.dem.tree.minimums[0];return T>0&&u++,v+T},0);return u?f/u:0}_updateEmptyDEMTexture(){const u=this.painter.context,f=u.gl;u.activeTexture.set(f.TEXTURE2);const v=this._getLoadedAreaMinimum(),S=new a.dL({width:1,height:1},new Float32Array([v]));this._emptyDEMTextureDirty=!1;let T=this._emptyDEMTexture;return T?T.update(S,{premultiply:!1}):T=this._emptyDEMTexture=new a.T(u,S,f.R32F,{premultiply:!1}),T}setupElevationDraw(u,f,v){const S=this.painter.context,T=S.gl,E={u_dem:2,u_dem_prev:4,u_dem_tl:[0,0],u_dem_tl_prev:[0,0],u_dem_scale:0,u_dem_scale_prev:0,u_dem_size:0,u_dem_lerp:1,u_depth:3,u_depth_size_inv:[0,0],u_depth_range_unpack:[0,1],u_occluder_half_size:16,u_occlusion_depth_offset:-1e-4,u_exaggeration:0};E.u_exaggeration=this.exaggeration();let L=null,B=null,q=1;if(v&&v.morphing&&this._useVertexMorphing){const re=v.morphing.srcDemTile,oe=v.morphing.dstDemTile;q=v.morphing.phase,re&&oe&&(this._prepareDemTileUniforms(u,re,E,"_prev")&&(B=re),this._prepareDemTileUniforms(u,oe,E)&&(L=oe))}const G=re=>re&&re.demTexture&&this.painter.linearFloatFilteringSupported()?T.LINEAR:T.NEAREST;let ee=null;var J;if(this.enabled?B&&L?(ee=L.demTexture,S.activeTexture.set(T.TEXTURE4),B.demTexture.bind(G(B),T.CLAMP_TO_EDGE),E.u_dem_lerp=q):(L=this.terrainTileForTile[u.tileID.key],ee=this._prepareDemTileUniforms(u,L,E)?L.demTexture:this.emptyDEMTexture):ee=this.emptyDEMTexture,S.activeTexture.set(T.TEXTURE2),ee&&(E.u_dem_size=(J=ee).size[0]===1?1:J.size[0]-2,ee.bind(G(L),T.CLAMP_TO_EDGE)),this.painter.setupDepthForOcclusion(v&&v.useDepthForOcclusion,f,E),v&&v.useMeterToDem&&L){const re=(1<{if(fe===At)return;const Bt=[H0[At],"PROJECTION_GLOBE_VIEW"];Ae&&Bt.push("CUSTOM_ANTIALIASING");const or=q.isTileAffectedByFog(Tt);me=q.getOrCreateProgram("globeRaster",{defines:Bt,overrideFog:or}),fe=At},Ze=q.colorModeForRenderPass(),$e=new Wr(se.LEQUAL,Wr.ReadWrite,q.depthRangeFor3D);Th.update(re);const He=a.dF(Ne),ze=[a.aF(Ne.center.lng),a.aJ(Ne.center.lat)],De=q.globeSharedBuffers,Qe=[Ne.width*a.o.devicePixelRatio,Ne.height*a.o.devicePixelRatio],ht=Float32Array.from(Ne.globeMatrix),ot={useDenormalizedUpVectorScale:!0};{const Tt=q.transform,At=W0(Tt.zoom,G.exaggeration(),G.sourceCache._source.tileSize);fe=-1;const Bt=se.TRIANGLES;for(const or of J){const wt=ee.getTile(or),st=_n.disabled,Mt=G.prevTerrainTileForTile[or.key],kt=G.terrainTileForTile[or.key];Xx(Mt,kt)&&Th.newMorphing(or.key,Mt,kt,re,250),Sg(q,wt.emissiveTexture),oe.activeTexture.set(se.TEXTURE0),wt.texture&&wt.texture.bind(se.LINEAR,se.CLAMP_TO_EDGE);const Zt=Th.getMorphValuesForProxy(or.key),yr=Zt?1:0;Zt&&Object.assign(ot,{morphing:{srcDemTile:Zt.from,dstDemTile:Zt.to,phase:a.dD(Zt.phase)}});const Pr=a.dG(or.canonical),fr=a.dH(Pr.getCenter().lat),lr=a.dI(or.canonical,Pr,fr,Tt.worldSize/Tt._pixelsPerMercatorPixel),Ur=a.bk(a.dJ(or.canonical)),Fr=q.emissiveMode==="mrt-fallback"?1:0,Tr=q0(Tt.expandedFarZProjMatrix,ht,He,Ur,a.aj(Tt.zoom),ze,Tt.frustumCorners.TL,Tt.frustumCorners.TR,Tt.frustumCorners.BR,Tt.frustumCorners.BL,Tt.globeCenterInViewSpace,Tt.globeRadius,Qe,At,Tt._farZ,Fr,lr);if(Te(or,yr),me&&(G.setupElevationDraw(wt,me,ot),q.uploadCommonUniforms(oe,me,or.toUnwrapped()),De)){const[Mr,tn,Cn]=De.getGridBuffers(fr,At!==0);me.draw(q,Bt,$e,st,Ze,vn.backCCW,Tr,"globe_raster",Mr,tn,Cn)}}}if(De&&(q.renderDefaultNorthPole||q.renderDefaultSouthPole)){const Tt=["GLOBE_POLES","PROJECTION_GLOBE_VIEW"];Ae&&Tt.push("CUSTOM_ANTIALIASING"),me=q.getOrCreateProgram("globeRaster",{defines:Tt});for(const At of J){const{x:Bt,y:or,z:wt}=At.canonical,st=or===0,Mt=or===(1<Mr.draw(q,se.TRIANGLES,$e,_n.disabled,Ze,vn.disabled,q0(Ne.expandedFarZProjMatrix,lr,lr,Ur,0,ze,Ne.frustumCorners.TL,Ne.frustumCorners.TR,Ne.frustumCorners.BR,Ne.frustumCorners.BL,Ne.globeCenterInViewSpace,Ne.globeRadius,Qe,0,Ne._farZ,Fr),"globe_pole_raster",tn,yr,Pr);G.setupElevationDraw(fr,me,ot),q.uploadCommonUniforms(oe,me,At.toUnwrapped()),st&&q.renderDefaultNorthPole&&Tr(me,kt),Mt&&q.renderDefaultSouthPole&&(lr=a.cS(a.bC(),lr,[1,-1,1]),Tr(me,Zt))}}}})(S,T,E,L,B);else{const q=S.context,G=q.gl;let ee,J;const re=S.shadowRenderer,oe=Df(S,S.longestCutoffRange),se=Ze=>{if(J===Ze)return;const $e=[];$e.push(H0[Ze]),oe.shouldRenderCutoff&&$e.push("RENDER_CUTOFF"),re&&($e.push("RENDER_SHADOWS","DEPTH_TEXTURE"),re.useNormalOffset&&$e.push("NORMAL_OFFSET")),ee=S.getOrCreateProgram("terrainRaster",{defines:$e}),J=Ze},me=S.colorModeForRenderPass(),fe=new Wr(G.LEQUAL,Wr.ReadWrite,S.depthRangeFor3D);Th.update(B);const Ne=S.transform,Ae=W0(Ne.zoom,T.exaggeration(),T.sourceCache._source.tileSize);let Te=[0,0,0];if(re){const Ze=S.style.directionalLight,$e=S.style.ambientLight;Ze&&$e&&(Te=kh(S.style,Ze,$e))}{J=-1;const Ze=G.TRIANGLES,[$e,He]=[T.gridIndexBuffer,T.gridSegments];for(const ze of L){const De=E.getTile(ze),Qe=_n.disabled,ht=T.prevTerrainTileForTile[ze.key],ot=T.terrainTileForTile[ze.key];Xx(ht,ot)&&Th.newMorphing(ze.key,ht,ot,B,250),Sg(S,De.emissiveTexture),q.activeTexture.set(G.TEXTURE0),De.texture&&De.texture.bind(G.LINEAR,G.CLAMP_TO_EDGE);const Tt=Th.getMorphValuesForProxy(ze.key),At=Tt?1:0;let Bt;Tt&&(Bt={morphing:{srcDemTile:Tt.from,dstDemTile:Tt.to,phase:a.dD(Tt.phase)}});const or=S.emissiveMode==="mrt-fallback"?1:0,wt=Uc(ze.projMatrix,IS(ze.canonical,Ne.renderWorldCopies)?Ae/10:Ae,Te,or);if(se(At),!ee)continue;T.setupElevationDraw(De,ee,Bt);const st=ze.toUnwrapped();re&&re.setupShadows(st,ee),S.uploadCommonUniforms(q,ee,st,null,oe),ee.draw(S,Ze,fe,Qe,me,vn.backCCW,wt,"terrain_raster",T.gridBuffer,$e,He)}}}}(f,this,this.proxySourceCache,u,this._updateTimestamp),this.renderingToTexture=!0,f.gpuTimingDeferredRenderEnd(),u.splice(0,u.length))}renderBatch(u){if(this._drapedRenderBatches.length===0)return u+1;this.renderingToTexture=!0;const f=this.painter,v=this.painter.context,S=this.proxySourceCache,T=this.proxiedCoords[S.id],E=this._drapedRenderBatches.shift(),L=f.style.order,B=[];this._updateFBOs(f.emissiveMode==="mrt-fallback");let q=0;for(const G of T){const ee=S.getTileByID(G.proxyTileKey),J=S.proxyCachedFBO[G.key]?S.proxyCachedFBO[G.key][u]:void 0,re=J!==void 0?S.renderCache[J]:this.pool[q++],oe=J!==void 0;if(ee.texture=re.tex,ee.emissiveTexture=re.emissiveTex,oe&&!re.dirty){B.push(ee.tileID);continue}v.bindFramebuffer.set(re.fb.framebuffer);const se=v.gl;let me;se.drawBuffers(f.emissiveMode==="mrt-fallback"?[se.COLOR_ATTACHMENT0,se.COLOR_ATTACHMENT1]:[se.COLOR_ATTACHMENT0]),this.renderedToTile=!1,re.dirty&&(v.clear({color:a.ao.transparent,stencil:0}),re.dirty=!1);for(let fe=E.start;fe<=E.end;++fe){const Ne=f.style._mergedLayers[L[fe]];if(Ne.isHidden(f.transform.zoom))continue;const Ae=f.style.getLayerSourceCache(Ne),Te=Ae?this.proxyToSource[G.key][Ae.id]:[G];if(!Te)continue;const Ze=Te;v.viewport.set([0,0,re.fb.width,re.fb.height]),me!==(Ae?Ae.id:null)&&(this._setupStencil(re,Te,Ne,Ae),me=Ae?Ae.id:null),f.renderLayer(f,Ae,Ne,Ze)}if(se.drawBuffers([se.COLOR_ATTACHMENT0]),this._drapedRenderBatches.length===0)for(const fe of this._pendingGroundEffectLayers){const Ne=f.style._mergedLayers[L[fe]];if(Ne.isHidden(f.transform.zoom))continue;const Ae=f.style.getLayerSourceCache(Ne),Te=Ae?this.proxyToSource[G.key][Ae.id]:[G];if(!Te)continue;const Ze=Te;v.viewport.set([0,0,re.fb.width,re.fb.height]),me!==(Ae?Ae.id:null)&&(this._setupStencil(re,Te,Ne,Ae),me=Ae?Ae.id:null),f.renderLayer(f,Ae,Ne,Ze)}this.renderedToTile?(re.dirty=!0,B.push(ee.tileID)):oe||--q,q===5&&(q=0,this.renderToBackBuffer(B))}return this.renderToBackBuffer(B),this.renderingToTexture=!1,v.bindFramebuffer.set(null),v.viewport.set([0,0,f.width,f.height]),E.end+1}postRender(){}isLayerOrderingCorrect(u){const f=u.order.length;let v=-1,S=f;for(let T=0;Tv}getMinElevationBelowMSL(){let u=0;return this._visibleDemTiles.filter(f=>f.dem).forEach(f=>{u=Math.min(u,f.dem.tree.minimums[0])}),u===0?u:(u-30)*this._exaggeration}raycast(u,f,v){if(!this._visibleDemTiles)return null;const S=this._visibleDemTiles.filter(T=>T.dem).map(T=>{const E=T.tileID,L=1<(T.t!==null?T.t:Number.MAX_VALUE)-(E.t!==null?E.t:Number.MAX_VALUE));for(const T of S){if(T.t==null)return null;const E=T.tile.dem.tree.raycast(T.minx,T.miny,T.maxx,T.maxy,u,f,v);if(E!=null)return E}return null}_createFBO(){const u=this.painter.context,f=u.gl,v=this.drapeBufferSize;u.activeTexture.set(f.TEXTURE0);const S=new a.T(u,{width:v[0],height:v[1],data:null},f.RGBA8);S.bind(f.LINEAR,f.CLAMP_TO_EDGE);const T=u.createFramebuffer(v[0],v[1],1,null);let E;return T.colorAttachment0.set(S.texture),this._emissiveTexture&&(E=new a.T(u,{width:v[0],height:v[1],data:null},f.R8),E.bind(f.LINEAR,f.CLAMP_TO_EDGE),T.createColorAttachment(u,1),T.colorAttachment1.set(E.texture)),T.depthAttachment=new vE(u,T.framebuffer),this._sharedDepthStencil===void 0?(this._sharedDepthStencil=u.createRenderbuffer(u.gl.DEPTH_STENCIL,v[0],v[1]),this._stencilRef=0,T.depthAttachment.set(this._sharedDepthStencil),u.clear({stencil:0})):T.depthAttachment.set(this._sharedDepthStencil),u.extTextureFilterAnisotropic&&f.texParameterf(f.TEXTURE_2D,u.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,u.extTextureFilterAnisotropicMax),{fb:T,tex:S,emissiveTex:E,dirty:!1}}_updateFBOs(u){if(this._emissiveTexture!==u){for(const f of this.pool)this._updateFBO(f,u);for(const f of this.proxySourceCache.renderCache)this._updateFBO(f,u);this._emissiveTexture=u}}_updateFBO(u,f){const v=u.fb,S=this.painter.context,T=S.gl,E=this.drapeBufferSize;if(f){const L=new a.T(S,{width:E[0],height:E[1],data:null},T.R8);L.bind(T.LINEAR,T.CLAMP_TO_EDGE),u.emissiveTex=L,v.createColorAttachment(S,1),v.colorAttachment1.set(L.texture)}else u.emissiveTex=void 0,v.removeColorAttachment(S,1);u.dirty=!0}_initFBOPool(){for(;this.pool.length{const f=this._style._mergedLayers[u],v=f.isHidden(this.painter.transform.zoom);return f.type==="hillshade"||f.type==="custom"?!v&&f.shouldRedrape():!v&&f.hasTransition()})}_clearLineLayersFromRenderCache(){let u=!1;for(const v of this._style.getSources())if(v instanceof zp){u=!0;break}if(!u)return;const f={};for(let v=0;vB>L.end)||a.w("fill-extrusion with flood lighting and/or ground ambient occlusion should be moved to be on top of all draped layers.")}this._drapedRenderBatches=v}_setupRenderCache(u){const f=this.proxySourceCache;if(this._shouldDisableRenderCache()||this.invalidateRenderCache){if(this.invalidateRenderCache=!1,f.renderCache.length>f.renderCachePool.length){const E=Object.values(f.proxyCachedFBO);f.proxyCachedFBO={};for(let L=0;L=0;E--){const L=v[E];if(f.getTileByID(L.key),f.proxyCachedFBO[L.key]!==void 0){const B=u[L.key],q=this.proxyToSource[L.key];let G=0;for(const ee in q){const J=q[ee],re=B[ee];if(!re||re.length!==J.length||J.some((oe,se)=>oe!==re[se]||S[ee]&&S[ee].hasOwnProperty(oe.key))){G=-1;break}++G}for(const ee in f.proxyCachedFBO[L.key])f.renderCache[f.proxyCachedFBO[L.key][ee]].dirty=G<0||G!==Object.values(B).length}}const T=[...this._drapedRenderBatches];T.sort((E,L)=>L.end-L.start-(E.end-E.start));for(const E of T)for(const L of v){if(f.proxyCachedFBO[L.key])continue;let B=f.renderCachePool.pop();B===void 0&&f.renderCache.length<50&&(B=f.renderCache.length,f.renderCache.push(this._createFBO())),B!==void 0&&(f.proxyCachedFBO[L.key]={},f.proxyCachedFBO[L.key][E.start]=B,f.renderCache[B].dirty=!0)}this._tilesDirty={}}_setupStencil(u,f,v,S){if(!S||!this._sourceTilesOverlap[S.id])return void(this._overlapStencilType&&(this._overlapStencilType=!1));const T=this.painter.context,E=T.gl;if(f.length<=1)return void(this._overlapStencilType=!1);let L;if(v.isTileClipped())L=f.length,this._overlapStencilMode.test={func:E.EQUAL,mask:255},this._overlapStencilType="Clip";else{if(!(f[0].overscaledZ>f[f.length-1].overscaledZ))return void(this._overlapStencilType=!1);L=1,this._overlapStencilMode.test={func:E.GREATER,mask:255},this._overlapStencilType="Mask"}this._stencilRef+L>255&&(T.clear({stencil:0}),this._stencilRef=0),this._stencilRef+=L,this._overlapStencilMode.ref=this._stencilRef,v.isTileClipped()&&this._renderTileClippingMasks(f,this._overlapStencilMode.ref)}clipOrMaskOverlapStencilType(){return this._overlapStencilType==="Clip"||this._overlapStencilType==="Mask"}stencilModeForRTTOverlap(u){return this.renderingToTexture&&this._overlapStencilType?(this._overlapStencilType==="Clip"&&(this._overlapStencilMode.ref=this.painter._tileClippingMaskIDs[u.key]),this._overlapStencilMode):_n.disabled}_renderTileClippingMasks(u,f){const v=this.painter,S=this.painter.context,T=S.gl;v._tileClippingMaskIDs={},S.setColorMode(En.disabled),S.setDepthMode(Wr.disabled);const E=v.getOrCreateProgram("clippingMask");for(const L of u){const B=v._tileClippingMaskIDs[L.key]=--f;E.draw(v,T.TRIANGLES,Wr.disabled,new _n({func:T.ALWAYS,mask:0},B,255,T.KEEP,T.KEEP,T.REPLACE),En.disabled,vn.disabled,Qx(L.projMatrix),"$clipping",v.tileExtentBuffer,v.quadTriangleIndexBuffer,v.tileExtentSegments)}}pointCoordinate(u){const f=this.painter.transform;if(u.x<0||u.x>f.width||u.y<0||u.y>f.height)return null;const v=[u.x,u.y,1,1];a.aC(v,v,f.pixelMatrixInverse),a.cK(v,v,1/v[3]),v[0]/=f.worldSize,v[1]/=f.worldSize;const S=f._camera.position,T=a.cf(1,f.center.lat),E=[S[0],S[1],S[2]/T,0],L=a.da([],v.slice(0,3),E);a.aw(L,L);const B=this.raycast(E,L,this._exaggeration);return B!==null&&B?(a.bH(E,E,L,B),E[3]=E[2],E[2]*=T,E):null}_setupProxiedCoordsForOrtho(u,f,v){if(u.getSource()instanceof a.aU)return this._setupProxiedCoordsForImageSource(u,f,v);this._findCoveringTileCache[u.id]=this._findCoveringTileCache[u.id]||{};const S=this.proxiedCoords[u.id]=[],T=this.proxyCoords;for(let B=0;BG.overscaledZ-q.overscaledZ)}_setupProxiedCoordsForImageSource(u,f,v){if(!u.getSource().loaded())return;const S=this.proxiedCoords[u.id]=[],T=this.proxyCoords,E=u.getSource(),L=E.tileID;if(!L)return;const B=new a.P(L.x,L.y)._div(1<(ee.min.x=Math.min(ee.min.x,J.x-B.x),ee.min.y=Math.min(ee.min.y,J.y-B.y),ee.max.x=Math.max(ee.max.x,J.x-B.x),ee.max.y=Math.max(ee.max.y,J.y-B.y),ee),{min:new a.P(Number.MAX_VALUE,Number.MAX_VALUE),max:new a.P(-Number.MAX_VALUE,-Number.MAX_VALUE)}),G=(ee,J)=>{const re=ee.wrap+ee.canonical.x/(1<me+q.max.x||oe+sefe+q.max.y};for(let ee=0;eeE.key===f.tileID.key);if(T)return T}if(f.tileID.key!==u.key){const T=u.canonical.z-f.tileID.canonical.z;let E,L,B;S=a.bC();const q=f.tileID.wrap-u.wrap<0?(E=a.al>>T,L=E*((f.tileID.canonical.x<=ee){const J=u.canonical.z-ee;f.getSource().reparseOverscaled?(L=Math.max(u.canonical.z+2,f.transform.tileZoom),E=new a.aQ(L,u.wrap,ee,u.canonical.x>>J,u.canonical.y>>J)):J!==0&&(L=ee,E=new a.aQ(L,u.wrap,ee,u.canonical.x>>J,u.canonical.y>>J))}E.key!==u.key&&(q.push(E.key),v=f.getTile(E))}const G=ee=>{q.forEach(J=>{S[J]=ee}),q.length=0};for(L-=1;L>=B&&(!v||!v.hasData());L--){v&&G(v.tileID.key);const ee=E.calculateScaledKey(L);if(v=f.getTileByID(ee),v&&v.hasData())break;const J=S[ee];if(J===null)break;J===void 0?q.push(ee):v=f.getTileByID(J)}return G(v?v.tileID.key:null),v&&v.hasData()?v:null}findDEMTileFor(u){return this.enabled?this._findTileCoveringTileID(u,this.sourceCache):null}prepareDrawTile(){this.renderedToTile=!0}_clearRenderCacheForTile(u,f){let v=this._tilesDirty[u];v||(v=this._tilesDirty[u]={}),v[f.key]=!0}}function Ng(x,u,f){const v=function(L,B,q){const G=a.bJ(B,L),ee=a.bJ(q,[.2126,.7152,.0722]),J=(oe,se,me)=>(1-me)*oe+me*se,re=J(1-.3*Math.min(ee,1),1,Math.min(G+1,1));return J(.92,1,Math.asin(a.aA(B[2],-1,1))/Math.PI+.5)*re}(x,[0,0,1],u),S=[0,0,0];a.c5(S,f.slice(0,3),v);const T=[0,0,0];a.c5(T,u.slice(0,3),x[2]);const E=[0,0,0];return a.d8(E,S,T),a.db(E)}const v4=["fill","fillOutline","fillPattern","line","linePattern","background","backgroundPattern","hillshade","raster"],_4=["stars","rainParticle","snowParticle","fillExtrusion","fillExtrusionGroundEffect","building","buildingBloom","elevatedStructures","model","symbol"];class _E{static cacheKey(u,f,v,S){const T=[f];S&&T.push(S.cacheKey);for(const E of v)u.usedDefines.has(E)&&T.push(E);return T.join("/")}constructor(u,f,v,S,T,E){const L=u.gl;this.program=L.createProgram(),this.configuration=S,this.name=f,this.fixedDefines=[...E];const B=`#version 300 es ${(S?S.defines():[]).concat(E.map(se=>`#define ${se}`)).join(` `)}`,q=[B,u4];for(const se of v.fragmentIncludes)q.push(Bf[se]);q.push(v.fragmentSource);const G=q.join(` `),ee=[B,uE];for(const se of v.vertexIncludes)ee.push(Bf[se]);this.forceManualRenderingForInstanceIDShaders=u.forceManualRenderingForInstanceIDShaders&&v.vertexSource.includes("gl_InstanceID"),this.forceManualRenderingForInstanceIDShaders&&ee.push("uniform int u_instanceID;"),ee.push(v.vertexSource);let J=ee.join(` `);this.forceManualRenderingForInstanceIDShaders&&(J=J.replaceAll("gl_InstanceID","u_instanceID"));const re=L.createShader(L.FRAGMENT_SHADER);if(L.isContextLost())return void(this.failedToCreate=!0);L.shaderSource(re,G),L.compileShader(re),L.attachShader(this.program,re);const oe=L.createShader(L.VERTEX_SHADER);L.isContextLost()?this.failedToCreate=!0:(L.shaderSource(oe,J),L.compileShader(oe),L.attachShader(this.program,oe),this.attributes={},L.linkProgram(this.program),L.deleteShader(oe),L.deleteShader(re),this.fixedUniforms=T(u),this.fixedUniformsEntries=Object.entries(this.fixedUniforms),this.binderUniforms=S?S.getUniforms(u):[],this.forceManualRenderingForInstanceIDShaders&&(this.instancingUniforms=(se=>({u_instanceID:new a.ch(se)}))(u)),(E.includes("TERRAIN")||f.includes("symbol")||f.includes("circle"))&&(this.terrainUniforms=(se=>({u_dem:new a.ch(se),u_dem_prev:new a.ch(se),u_dem_tl:new a.ck(se),u_dem_scale:new a.cj(se),u_dem_tl_prev:new a.ck(se),u_dem_scale_prev:new a.cj(se),u_dem_size:new a.cj(se),u_dem_lerp:new a.cj(se),u_exaggeration:new a.cj(se),u_depth:new a.ch(se),u_depth_size_inv:new a.ck(se),u_depth_range_unpack:new a.ck(se),u_occluder_half_size:new a.cj(se),u_occlusion_depth_offset:new a.cj(se),u_meter_to_dem:new a.cj(se),u_label_plane_matrix_inv:new a.cl(se)}))(u)),E.includes("GLOBE")&&(this.globeUniforms=(se=>({u_tile_tl_up:new a.ci(se),u_tile_tr_up:new a.ci(se),u_tile_br_up:new a.ci(se),u_tile_bl_up:new a.ci(se),u_tile_up_scale:new a.cj(se)}))(u)),E.includes("FOG")&&(this.fogUniforms=(se=>({u_fog_matrix:new a.cl(se),u_fog_range:new a.ck(se),u_fog_color:new a.d3(se),u_fog_horizon_blend:new a.cj(se),u_fog_vertical_limit:new a.ck(se),u_fog_temporal_offset:new a.cj(se),u_frustum_tl:new a.ci(se),u_frustum_tr:new a.ci(se),u_frustum_br:new a.ci(se),u_frustum_bl:new a.ci(se),u_globe_pos:new a.ci(se),u_globe_radius:new a.cj(se),u_globe_transition:new a.cj(se),u_is_globe:new a.ch(se),u_viewport:new a.ck(se)}))(u)),E.includes("RENDER_CUTOFF")&&(this.cutoffUniforms=(se=>({u_cutoff_params:new a.d3(se)}))(u)),E.includes("LIGHTING_3D_MODE")&&(this.lightsUniforms=(se=>({u_lighting_ambient_color:new a.ci(se),u_lighting_directional_dir:new a.ci(se),u_lighting_directional_color:new a.ci(se),u_ground_radiance:new a.ci(se)}))(u)),E.includes("RENDER_SHADOWS")&&(this.shadowUniforms=(se=>({u_light_matrix_0:new a.cl(se),u_light_matrix_1:new a.cl(se),u_fade_range:new a.ck(se),u_shadow_normal_offset:new a.ci(se),u_shadow_intensity:new a.cj(se),u_shadow_texel_size:new a.cj(se),u_shadow_map_resolution:new a.cj(se),u_shadow_direction:new a.ci(se),u_shadow_bias:new a.ci(se),u_shadowmap_0:new a.ch(se),u_shadowmap_1:new a.ch(se)}))(u)))}getAttributeLocation(u,f){let v=this.attributes[f];return v===void 0&&(v=this.attributes[f]=u.getAttribLocation(this.program,f)),v}setTerrainUniformValues(u,f){if(!this.terrainUniforms)return;const v=this.terrainUniforms;if(!this.failedToCreate){u.program.set(this.program);for(const S in f)v[S]&&v[S].set(this.program,S,f[S])}}setGlobeUniformValues(u,f){if(!this.globeUniforms)return;const v=this.globeUniforms;if(!this.failedToCreate){u.program.set(this.program);for(const S in f)v[S]&&v[S].set(this.program,S,f[S])}}setFogUniformValues(u,f){if(!this.fogUniforms)return;const v=this.fogUniforms;if(!this.failedToCreate){u.program.set(this.program);for(const S in f)v[S].set(this.program,S,f[S])}}setCutoffUniformValues(u,f){if(!this.cutoffUniforms)return;const v=this.cutoffUniforms;if(!this.failedToCreate){u.program.set(this.program);for(const S in f)v[S].set(this.program,S,f[S])}}setLightsUniformValues(u,f){if(!this.lightsUniforms)return;const v=this.lightsUniforms;if(!this.failedToCreate){u.program.set(this.program);for(const S in f)v[S].set(this.program,S,f[S])}}setShadowUniformValues(u,f){if(this.failedToCreate||!this.shadowUniforms)return;const v=this.shadowUniforms;u.program.set(this.program);for(const S in f)v[S].set(this.program,S,f[S])}_drawDebugWireframe(u,f,v,S,T,E,L,B,q,G){const ee=u.options.wireframe;if(ee.terrain===!1&&ee.layers2D===!1&&ee.layers3D===!1)return;const J=u.context;if(!(!(!ee.terrain||this.name!=="terrainRaster"&&this.name!=="globeRaster")||!(!ee.layers2D||u._terrain&&u._terrain.renderingToTexture||!v4.includes(this.name))||!(!ee.layers3D||!_4.includes(this.name))))return;const re=J.gl,oe=u.wireframeDebugCache.getLinesFromTrianglesBuffer(u.frameCounter,T,J);if(!oe)return;const se=[...this.fixedDefines,"DEBUG_WIREFRAME"],me=u.getOrCreateProgram(this.name,{config:this.configuration,defines:se});J.program.set(me.program);const fe=(Te,Ze,$e)=>{if(Ze[Te]&&$e[Te])for(const He in Ze[Te])$e[Te][He]&&$e[Te][He].set($e.program,He,Ze[Te][He].current)};q&&q.setUniforms(me.program,J,me.binderUniforms,L,{zoom:B}),fe("fixedUniforms",this,me),fe("terrainUniforms",this,me),fe("globeUniforms",this,me),fe("fogUniforms",this,me),fe("lightsUniforms",this,me),fe("shadowUniforms",this,me),oe.bind(),J.setColorMode(new En([re.ONE,re.ONE_MINUS_SRC_ALPHA,re.ZERO,re.ONE],a.ao.transparent,[!0,!0,!0,!1])),J.setDepthMode(new Wr(f.func===re.LESS?re.LEQUAL:f.func,Wr.ReadOnly,f.range)),J.setStencilMode(_n.disabled);const Ne=3*E.primitiveLength*2,Ae=3*E.primitiveOffset*2*2;if(this.forceManualRenderingForInstanceIDShaders){const Te=G||1;for(let Ze=0;Ze1?re.drawElementsInstanced(re.LINES,Ne,re.UNSIGNED_SHORT,Ae,G):re.drawElements(re.LINES,Ne,re.UNSIGNED_SHORT,Ae);T.bind(),J.program.set(this.program),J.setDepthMode(f),J.setStencilMode(v),J.setColorMode(S)}checkUniforms(u,f,v){if(this.fixedDefines.includes(f)){for(const S of Object.keys(v))if(!v[S].initialized)throw new Error(`Program '${this.name}', from draw '${u}': uniform ${S} not set but required by ${f} being defined`)}}draw(u,f,v,S,T,E,L,B,q,G,ee,J,re,oe,se,me){const fe=u.context,Ne=fe.gl;if(this.failedToCreate)return;fe.program.set(this.program),fe.setDepthMode(v),fe.setStencilMode(S),fe.setColorMode(T),fe.setCullFace(E);for(const[ze,De]of this.fixedUniformsEntries)De.set(this.program,ze,L[ze]);oe&&oe.setUniforms(this.program,fe,this.binderUniforms,J,{zoom:re});const Ae={[Ne.POINTS]:1,[Ne.LINES]:2,[Ne.TRIANGLES]:3,[Ne.LINE_STRIP]:1}[f];this.checkUniforms(B,"RENDER_SHADOWS",this.shadowUniforms);const Te=se||[],Ze=oe?oe.getPaintVertexBuffers():[],$e=f===Ne.TRIANGLES&&G,He=me&&me>0?1:void 0;for(const ze of ee.get()){const De=ze.vaos||(ze.vaos={});if((De[B]||(De[B]=new d4)).bind(fe,this,q,Ze,G,ze.vertexOffset,Te,He),this.forceManualRenderingForInstanceIDShaders){const Qe=me||1;for(let ht=0;ht1?Ne.drawElementsInstanced(f,ze.primitiveLength*Ae,Ne.UNSIGNED_SHORT,ze.primitiveOffset*Ae*2,me):G?Ne.drawElements(f,ze.primitiveLength*Ae,Ne.UNSIGNED_SHORT,ze.primitiveOffset*Ae*2):Ne.drawArrays(f,ze.vertexOffset,ze.vertexLength);$e&&this._drawDebugWireframe(u,v,S,T,G,ze,J,re,oe,me)}}}function bE(x,u,f=0){const v=Math.pow(2,u.tileID.overscaledZ),S=u.tileSize*Math.pow(2,x.transform.tileZoom)/v,T=S*(u.tileID.canonical.x+u.tileID.wrap*v),E=S*u.tileID.canonical.y;return{u_image:0,u_texsize:u.imageAtlasTexture?u.imageAtlasTexture.size:[0,0],u_tile_units_to_pixels:1/a.ay(u,1,x.transform.tileZoom),u_pixel_coord_upper:[T>>16,E>>16],u_pixel_coord_lower:[65535&T,65535&E],u_pattern_transition:f}}const K0={terrain:0,flat:1},b4=a.bC(),Z0=(x,u,f,v,S,T,E,L,B,q,G,ee,J,re,oe,se,me,fe)=>{const Ne=u.style.light,Ae=Ne.properties.get("position"),Te=[Ae.x,Ae.y,Ae.z],Ze=a.dO();Ne.properties.get("anchor")==="viewport"&&(a.dP(Ze,-u.transform.angle),a.dQ(Te,Te,Ze));const $e=Ne.properties.get("color").toPremultipliedRenderColor(null),He=u.transform,ze={u_matrix:x,u_lightpos:Te,u_lightintensity:Ne.properties.get("intensity"),u_lightcolor:[$e.r,$e.g,$e.b],u_vertical_gradient:+f,u_opacity:v,u_tile_id:[0,0,0],u_zoom_transition:0,u_inv_rot_matrix:b4,u_merc_center:[0,0],u_up_dir:[0,0,0],u_height_lift:0,u_height_type:K0[q],u_base_type:K0[G],u_ao:S,u_edge_radius:T,u_width_scale:E,u_flood_light_color:oe,u_vertical_scale:se,u_flood_light_intensity:me,u_ground_shadow_factor:fe};return He.projection.name==="globe"&&(ze.u_tile_id=[L.canonical.x,L.canonical.y,1<({u_matrix:x,u_edge_radius:u,u_width_scale:f,u_vertical_scale:v,u_height_type:K0[S],u_base_type:K0[T]}),wE=(x,u,f,v,S,T,E,L,B,q,G,ee,J,re,oe,se,me,fe)=>{const Ne=Z0(x,u,f,v,S,T,E,L,q,G,ee,J,re,oe,se,me,1,[0,0,0]),Ae={u_height_factor:-Math.pow(2,L.overscaledZ)/B.tileSize/8};return Object.assign(Ne,bE(u,B,fe),Ae)},Cg=(x,u,f,v,S,T,E,L,B,q,G)=>({u_matrix:u,u_opacity:f,u_ao_pass:v?1:0,u_meter_to_tile:S,u_ao:T,u_flood_light_intensity:E,u_flood_light_color:L,u_attenuation:B,u_edge_radius:q,u_fb:0,u_fb_size:G,u_dynamic_offset:1}),LS=(x,u,f)=>({u_matrix:x,u_emissive_strength:u,u_ground_shadow_factor:f}),FS=(x,u,f,v,S,T=0)=>Object.assign(LS(x,u,S),bE(f,v,T)),jE=(x,u,f,v)=>({u_matrix:x,u_world:f,u_emissive_strength:u,u_ground_shadow_factor:v}),zS=(x,u,f,v,S,T,E=0)=>Object.assign(FS(x,u,f,v,T,E),{u_world:S}),Uf=(x,u)=>({u_matrix:x,u_ground_shadow_factor:u}),Zp=(x,u,f,v,S)=>({u_matrix:x,u_camera_pos:[u[0],u[1],u[2]],u_depth_bias:f,u_height_scale:v,u_reset_depth:S}),Y0=(x,u,f,v,S,T,E,L,B)=>({u_matrix:x,u_normal_matrix:u,u_opacity:f,u_faux_facade_ao_intensity:v,u_camera_pos:S,u_tile_to_meter:T,u_facade_emissive_chance:E,u_flood_light_color:L,u_flood_light_intensity:B}),SE=x=>({u_matrix:x}),Vf=x=>({u_matrix:x}),BS=(x,u,f,v,S,T,E,L)=>{const B=a.al/T.tileSize;return{u_matrix:x,u_inv_rot_matrix:u,u_camera_to_center_distance:f.getCameraToCenterDistance(L),u_extrude_scale:[f.pixelsToGLUnits[0]/B,f.pixelsToGLUnits[1]/B],u_zoom_transition:v,u_tile_id:E,u_merc_center:S}},ev=(x,u,f=1)=>({u_matrix:x,u_color:u,u_overlay:0,u_overlay_scale:f}),NE=a.bC(),CE=(x,u,f,v,S,T,E)=>{const L=x.transform,B=L.projection.name==="globe",q=B?a.dR(L.zoom,u.canonical)*L._pixelsPerMercatorPixel:a.ay(f,1,T),G={u_matrix:u.projMatrix,u_extrude_scale:q,u_intensity:E,u_inv_rot_matrix:NE,u_merc_center:[0,0],u_tile_id:[0,0,0],u_zoom_transition:0,u_up_dir:[0,0,0]};if(B){G.u_inv_rot_matrix=v,G.u_merc_center=S,G.u_tile_id=[u.canonical.x,u.canonical.y,1<({u_matrix:x,u_normalize_matrix:u,u_globe_matrix:f,u_merc_matrix:v,u_grid_matrix:S,u_tl_parent:T,u_scale_parent:q,u_fade_t:G.mix,u_opacity:G.opacity*ee.paint.get("raster-opacity"),u_image0:0,u_image1:1,u_brightness_low:ee.paint.get("raster-brightness-min"),u_brightness_high:ee.paint.get("raster-brightness-max"),u_saturation_factor:a.dT(ee.paint.get("raster-saturation")),u_contrast_factor:a.dS(ee.paint.get("raster-contrast")),u_spin_weights:TE(ee.paint.get("raster-hue-rotate")),u_perspective_transform:J,u_raster_elevation:re,u_zoom_transition:E,u_merc_center:L,u_cutoff_params:B,u_colorization_mix:X0(a.dU,se,fe),u_colorization_offset:Q0(a.dU,me,fe),u_color_ramp:oe,u_texture_offset:[Ae/(Ne+2*Ae),Ne/(Ne+2*Ae)],u_texture_res:[Ne+2*Ae,Ne+2*Ae],u_emissive_strength:Te});function TE(x){x*=Math.PI/180;const u=Math.sin(x),f=Math.cos(x);return[(2*f+1)/3,(-Math.sqrt(3)*u-f+1)/3,(Math.sqrt(3)*u-f+1)/3]}const Dd=.05,w4=(x,u,f,v,S,T,E,L,B,q,G,ee)=>({u_matrix:x,u_normalize_matrix:u,u_globe_matrix:f,u_merc_matrix:v,u_grid_matrix:S,u_tl_parent:T,u_scale_parent:q,u_fade_t:G.mix,u_opacity:G.opacity,u_image0:0,u_image1:1,u_raster_elevation:ee,u_zoom_transition:E,u_merc_center:L,u_cutoff_params:B}),j4=(x,u,f,v,S,T,E,L,B,q)=>({u_particle_texture:x,u_particle_texture_side_len:u,u_tile_offset:f,u_velocity:v,u_color_ramp:T,u_velocity_res:S,u_max_speed:E,u_uv_offset:L,u_data_scale:[255*B[0],255*B[1]],u_data_offset:q,u_particle_pos_scale:1.1,u_particle_pos_offset:[Dd,Dd]}),EE=(x,u,f,v,S,T,E,L,B,q)=>({u_particle_texture:x,u_particle_texture_side_len:u,u_velocity:f,u_velocity_res:v,u_max_speed:S,u_speed_factor:T,u_reset_rate:E,u_rand_seed:Math.random(),u_uv_offset:L,u_data_scale:[255*B[0],255*B[1]],u_data_offset:q,u_particle_pos_scale:1.1,u_particle_pos_offset:[Dd,Dd]}),AE=a.bC(),J0=(x,u,f,v,S,T,E,L,B,q,G,ee,J,re,oe,se,me,fe,Ne,Ae,Te,Ze,$e,He)=>{const ze=S.transform,De={u_is_size_zoom_constant:+(x==="constant"||x==="source"),u_is_size_feature_constant:+(x==="constant"||x==="camera"),u_size_t:u?u.uSizeT:0,u_size:u?u.uSize:0,u_camera_to_center_distance:ze.getCameraToCenterDistance(Ne),u_rotate_symbol:+f,u_aspect_ratio:ze.width/ze.height,u_fade_change:S.options.fadeDuration?S.symbolFadeChange:1,u_matrix:T,u_label_plane_matrix:E,u_coord_matrix:L,u_is_text:+q,u_elevation_from_sea:B?1:0,u_pitch_with_map:+v,u_texsize:G,u_texsize_icon:ee,u_texture:0,u_texture_icon:1,u_tile_id:[0,0,0],u_zoom_transition:0,u_inv_rot_matrix:AE,u_merc_center:[0,0],u_camera_forward:[0,0,0],u_ecef_origin:[0,0,0],u_tile_matrix:AE,u_up_vector:[0,-1,0],u_color_adj_mat:Ze,u_icon_transition:$e||0,u_gamma_scale:v?S.transform.getCameraToCenterDistance(Ne)*Math.cos(S.terrain?0:S.transform._pitch):1,u_device_pixel_ratio:a.o.devicePixelRatio,u_is_halo:1,u_scale_factor:He||1,u_ground_shadow_factor:Ae,u_inv_matrix:a.bl(a.bC(),E),u_normal_scale:Te,u_lutTexture:_o.LUT};return Ne.name==="globe"&&(De.u_tile_id=[re.canonical.x,re.canonical.y,1<({u_matrix:x,u_emissive_strength:u,u_opacity:f,u_color:v}),qf=(x,u,f,v,S,T,E,L,B)=>Object.assign(function(q,G,ee,J,re,oe){const{width:se,height:me}=J.imageManager.getPixelSize(G),fe=Math.pow(2,oe.tileID.overscaledZ),Ne=oe.tileSize*Math.pow(2,J.transform.tileZoom)/fe,Ae=Ne*(oe.tileID.canonical.x+oe.tileID.wrap*fe),Te=Ne*oe.tileID.canonical.y;return{u_image:0,u_pattern_tl:ee.tl,u_pattern_br:ee.br,u_texsize:[se,me],u_pattern_size:ee.displaySize,u_pattern_units_to_pixels:re?[J.transform.width,-1*J.transform.height]:[1/a.ay(oe,1,J.transform.tileZoom),1/a.ay(oe,1,J.transform.tileZoom)],u_pixel_coord_upper:[Ae>>16,Te>>16],u_pixel_coord_lower:[65535&Ae,65535&Te]}}(0,T,E,v,L,B),{u_matrix:x,u_emissive_strength:u,u_opacity:f}),kg=new Float32Array(a.bA([])),Yp=(x,u,f,v,S,T,E,L,B,q,G,ee,J,re=[0,0,0],oe,se,me)=>{const fe=S.style.light,Ne=fe.properties.get("position"),Ae=[-Ne.x,-Ne.y,Ne.z],Te=a.dO();fe.properties.get("anchor")==="viewport"&&(a.dP(Te,-S.transform.angle),a.dQ(Ae,Ae,Te));const Ze=G.alphaMode==="MASK",$e=fe.properties.get("color").toNonPremultipliedRenderColor(null),He=J.paint.get("model-ambient-occlusion-intensity"),ze=J.paint.get("model-color").constantOr(a.ao.white).toNonPremultipliedRenderColor(null);return ze.a=J.paint.get("model-color-mix-intensity").constantOr(0),me&&(ze.r=me[0],ze.g=me[1],ze.b=me[2],ze.a=me[3]),se&&(ze.r=se.color.r,ze.g=se.color.g,ze.b=se.color.b,ze.a=se.colorMix,ee=se.emissionStrength,T*=se.opacity),{u_matrix:x,u_lighting_matrix:u,u_normal_matrix:f,u_node_matrix:v||kg,u_lightpos:Ae,u_lightintensity:fe.properties.get("intensity"),u_lightcolor:[$e.r,$e.g,$e.b],u_camera_pos:re,u_opacity:T,u_baseTextureIsAlpha:0,u_alphaMask:+Ze,u_alphaCutoff:G.alphaCutoff,u_baseColorFactor:E.toNonPremultipliedRenderColor(null).toArray01(),u_emissiveFactor:L.toNonPremultipliedRenderColor(null).toArray01(),u_metallicFactor:B,u_roughnessFactor:q,u_baseColorTexture:_o.BaseColor,u_metallicRoughnessTexture:_o.MetallicRoughness,u_normalTexture:_o.Normal,u_occlusionTexture:_o.Occlusion,u_emissionTexture:_o.Emission,u_lutTexture:_o.LUT,u_color_mix:ze.toArray01(),u_aoIntensity:He,u_emissive_strength:ee,u_occlusionTextureTransform:oe||[0,0,0,0]}},$S=(x,u=kg,f=kg)=>({u_matrix:x,u_instance:u,u_node_matrix:f}),eb={fillExtrusion:x=>({u_matrix:new a.cl(x),u_lightpos:new a.ci(x),u_lightintensity:new a.cj(x),u_lightcolor:new a.ci(x),u_vertical_gradient:new a.cj(x),u_opacity:new a.cj(x),u_edge_radius:new a.cj(x),u_width_scale:new a.cj(x),u_ao:new a.ck(x),u_height_type:new a.ch(x),u_base_type:new a.ch(x),u_tile_id:new a.ci(x),u_zoom_transition:new a.cj(x),u_inv_rot_matrix:new a.cl(x),u_merc_center:new a.ck(x),u_up_dir:new a.ci(x),u_height_lift:new a.cj(x),u_flood_light_color:new a.ci(x),u_vertical_scale:new a.cj(x),u_flood_light_intensity:new a.cj(x),u_ground_shadow_factor:new a.ci(x)}),fillExtrusionDepth:x=>({u_matrix:new a.cl(x),u_edge_radius:new a.cj(x),u_width_scale:new a.cj(x),u_vertical_scale:new a.cj(x),u_height_type:new a.ch(x),u_base_type:new a.ch(x)}),fillExtrusionPattern:x=>({u_matrix:new a.cl(x),u_lightpos:new a.ci(x),u_lightintensity:new a.cj(x),u_lightcolor:new a.ci(x),u_vertical_gradient:new a.cj(x),u_height_factor:new a.cj(x),u_edge_radius:new a.cj(x),u_width_scale:new a.cj(x),u_ao:new a.ck(x),u_height_type:new a.ch(x),u_base_type:new a.ch(x),u_tile_id:new a.ci(x),u_zoom_transition:new a.cj(x),u_inv_rot_matrix:new a.cl(x),u_merc_center:new a.ck(x),u_up_dir:new a.ci(x),u_height_lift:new a.cj(x),u_image:new a.ch(x),u_texsize:new a.ck(x),u_pixel_coord_upper:new a.ck(x),u_pixel_coord_lower:new a.ck(x),u_tile_units_to_pixels:new a.cj(x),u_opacity:new a.cj(x),u_pattern_transition:new a.cj(x)}),fillExtrusionGroundEffect:x=>({u_matrix:new a.cl(x),u_opacity:new a.cj(x),u_ao_pass:new a.cj(x),u_meter_to_tile:new a.cj(x),u_ao:new a.ck(x),u_flood_light_intensity:new a.cj(x),u_flood_light_color:new a.ci(x),u_attenuation:new a.cj(x),u_edge_radius:new a.cj(x),u_fb:new a.ch(x),u_fb_size:new a.cj(x),u_dynamic_offset:new a.cj(x)}),fill:x=>({u_matrix:new a.cl(x),u_emissive_strength:new a.cj(x),u_ground_shadow_factor:new a.ci(x)}),fillPattern:x=>({u_matrix:new a.cl(x),u_emissive_strength:new a.cj(x),u_image:new a.ch(x),u_texsize:new a.ck(x),u_pixel_coord_upper:new a.ck(x),u_pixel_coord_lower:new a.ck(x),u_tile_units_to_pixels:new a.cj(x),u_ground_shadow_factor:new a.ci(x),u_pattern_transition:new a.cj(x)}),fillOutline:x=>({u_matrix:new a.cl(x),u_emissive_strength:new a.cj(x),u_world:new a.ck(x),u_ground_shadow_factor:new a.ci(x)}),fillOutlinePattern:x=>({u_matrix:new a.cl(x),u_emissive_strength:new a.cj(x),u_world:new a.ck(x),u_image:new a.ch(x),u_texsize:new a.ck(x),u_pixel_coord_upper:new a.ck(x),u_pixel_coord_lower:new a.ck(x),u_tile_units_to_pixels:new a.cj(x),u_ground_shadow_factor:new a.ci(x),u_pattern_transition:new a.cj(x)}),building:x=>({u_matrix:new a.cl(x),u_normal_matrix:new a.cl(x),u_opacity:new a.cj(x),u_faux_facade_ao_intensity:new a.cj(x),u_camera_pos:new a.ci(x),u_tile_to_meter:new a.cj(x),u_facade_emissive_chance:new a.cj(x),u_flood_light_color:new a.ci(x),u_flood_light_intensity:new a.cj(x)}),buildingBloom:x=>({u_matrix:new a.cl(x)}),buildingDepth:x=>({u_matrix:new a.cl(x)}),elevatedStructuresDepth:x=>({u_matrix:new a.cl(x),u_depth_bias:new a.cj(x)}),elevatedStructures:x=>({u_matrix:new a.cl(x),u_ground_shadow_factor:new a.ci(x)}),elevatedStructuresDepthReconstruct:x=>({u_matrix:new a.cl(x),u_camera_pos:new a.ci(x),u_depth_bias:new a.cj(x),u_height_scale:new a.cj(x),u_reset_depth:new a.cj(x)}),circle:a.dY,collisionBox:x=>({u_matrix:new a.cl(x),u_inv_rot_matrix:new a.cl(x),u_camera_to_center_distance:new a.cj(x),u_extrude_scale:new a.ck(x),u_zoom_transition:new a.cj(x),u_merc_center:new a.ck(x),u_tile_id:new a.ci(x)}),collisionCircle:x=>({u_matrix:new a.cl(x),u_inv_matrix:new a.cl(x),u_camera_to_center_distance:new a.cj(x),u_viewport_size:new a.ck(x)}),debug:x=>({u_color:new a.dB(x),u_matrix:new a.cl(x),u_overlay:new a.ch(x),u_overlay_scale:new a.cj(x)}),clippingMask:x=>({u_matrix:new a.cl(x)}),heatmap:x=>({u_extrude_scale:new a.cj(x),u_intensity:new a.cj(x),u_matrix:new a.cl(x),u_inv_rot_matrix:new a.cl(x),u_merc_center:new a.ck(x),u_tile_id:new a.ci(x),u_zoom_transition:new a.cj(x),u_up_dir:new a.ci(x)}),heatmapTexture:x=>({u_image:new a.ch(x),u_color_ramp:new a.ch(x),u_opacity:new a.cj(x)}),hillshade:x=>({u_matrix:new a.cl(x),u_image:new a.ch(x),u_latrange:new a.ck(x),u_light:new a.ck(x),u_shadow:new a.dB(x),u_highlight:new a.dB(x),u_emissive_strength:new a.cj(x),u_accent:new a.dB(x)}),hillshadePrepare:x=>({u_matrix:new a.cl(x),u_image:new a.ch(x),u_dimension:new a.ck(x),u_zoom:new a.cj(x)}),line:a.dX,linePattern:a.dW,raster:x=>({u_matrix:new a.cl(x),u_normalize_matrix:new a.cl(x),u_globe_matrix:new a.cl(x),u_merc_matrix:new a.cl(x),u_grid_matrix:new a.dC(x),u_tl_parent:new a.ck(x),u_scale_parent:new a.cj(x),u_fade_t:new a.cj(x),u_opacity:new a.cj(x),u_image0:new a.ch(x),u_image1:new a.ch(x),u_brightness_low:new a.cj(x),u_brightness_high:new a.cj(x),u_saturation_factor:new a.cj(x),u_contrast_factor:new a.cj(x),u_spin_weights:new a.ci(x),u_perspective_transform:new a.ck(x),u_raster_elevation:new a.cj(x),u_zoom_transition:new a.cj(x),u_merc_center:new a.ck(x),u_cutoff_params:new a.d3(x),u_colorization_mix:new a.d3(x),u_colorization_offset:new a.cj(x),u_color_ramp:new a.ch(x),u_texture_offset:new a.ck(x),u_texture_res:new a.ck(x),u_emissive_strength:new a.cj(x)}),rasterParticle:x=>({u_matrix:new a.cl(x),u_normalize_matrix:new a.cl(x),u_globe_matrix:new a.cl(x),u_merc_matrix:new a.cl(x),u_grid_matrix:new a.dC(x),u_tl_parent:new a.ck(x),u_scale_parent:new a.cj(x),u_fade_t:new a.cj(x),u_opacity:new a.cj(x),u_image0:new a.ch(x),u_image1:new a.ch(x),u_raster_elevation:new a.cj(x),u_zoom_transition:new a.cj(x),u_merc_center:new a.ck(x),u_cutoff_params:new a.d3(x)}),rasterParticleTexture:x=>({u_texture:new a.ch(x),u_opacity:new a.cj(x)}),rasterParticleDraw:x=>({u_particle_texture:new a.ch(x),u_particle_texture_side_len:new a.cj(x),u_tile_offset:new a.ck(x),u_velocity:new a.ch(x),u_color_ramp:new a.ch(x),u_velocity_res:new a.ck(x),u_max_speed:new a.cj(x),u_uv_offset:new a.ck(x),u_data_scale:new a.ck(x),u_data_offset:new a.cj(x),u_particle_pos_scale:new a.cj(x),u_particle_pos_offset:new a.ck(x)}),rasterParticleUpdate:x=>({u_particle_texture:new a.ch(x),u_particle_texture_side_len:new a.cj(x),u_velocity:new a.ch(x),u_velocity_res:new a.ck(x),u_max_speed:new a.cj(x),u_speed_factor:new a.cj(x),u_reset_rate:new a.cj(x),u_rand_seed:new a.cj(x),u_uv_offset:new a.ck(x),u_data_scale:new a.ck(x),u_data_offset:new a.cj(x),u_particle_pos_scale:new a.cj(x),u_particle_pos_offset:new a.ck(x)}),symbol:x=>({u_is_size_zoom_constant:new a.ch(x),u_is_size_feature_constant:new a.ch(x),u_size_t:new a.cj(x),u_size:new a.cj(x),u_camera_to_center_distance:new a.cj(x),u_rotate_symbol:new a.ch(x),u_aspect_ratio:new a.cj(x),u_fade_change:new a.cj(x),u_matrix:new a.cl(x),u_label_plane_matrix:new a.cl(x),u_coord_matrix:new a.cl(x),u_is_text:new a.ch(x),u_elevation_from_sea:new a.ch(x),u_pitch_with_map:new a.ch(x),u_texsize:new a.ck(x),u_texsize_icon:new a.ck(x),u_texture:new a.ch(x),u_texture_icon:new a.ch(x),u_gamma_scale:new a.cj(x),u_device_pixel_ratio:new a.cj(x),u_tile_id:new a.ci(x),u_zoom_transition:new a.cj(x),u_inv_rot_matrix:new a.cl(x),u_merc_center:new a.ck(x),u_camera_forward:new a.ci(x),u_tile_matrix:new a.cl(x),u_up_vector:new a.ci(x),u_ecef_origin:new a.ci(x),u_is_halo:new a.ch(x),u_icon_transition:new a.cj(x),u_color_adj_mat:new a.cl(x),u_scale_factor:new a.cj(x),u_ground_shadow_factor:new a.ci(x),u_inv_matrix:new a.cl(x),u_normal_scale:new a.cj(x),u_lutTexture:new a.ch(x)}),background:x=>({u_matrix:new a.cl(x),u_emissive_strength:new a.cj(x),u_opacity:new a.cj(x),u_color:new a.dB(x)}),backgroundPattern:x=>({u_matrix:new a.cl(x),u_emissive_strength:new a.cj(x),u_opacity:new a.cj(x),u_image:new a.ch(x),u_pattern_tl:new a.ck(x),u_pattern_br:new a.ck(x),u_texsize:new a.ck(x),u_pattern_size:new a.ck(x),u_pixel_coord_upper:new a.ck(x),u_pixel_coord_lower:new a.ck(x),u_pattern_units_to_pixels:new a.ck(x)}),terrainRaster:x=>({u_matrix:new a.cl(x),u_image0:new a.ch(x),u_image1:new a.ch(x),u_skirt_height:new a.cj(x),u_ground_shadow_factor:new a.ci(x),u_emissive_texture_available:new a.cj(x)}),skybox:x=>({u_matrix:new a.cl(x),u_sun_direction:new a.ci(x),u_cubemap:new a.ch(x),u_opacity:new a.cj(x),u_temporal_offset:new a.cj(x)}),skyboxGradient:x=>({u_matrix:new a.cl(x),u_color_ramp:new a.ch(x),u_center_direction:new a.ci(x),u_radius:new a.cj(x),u_opacity:new a.cj(x),u_temporal_offset:new a.cj(x)}),skyboxCapture:x=>({u_matrix_3f:new a.dC(x),u_sun_direction:new a.ci(x),u_sun_intensity:new a.cj(x),u_color_tint_r:new a.d3(x),u_color_tint_m:new a.d3(x),u_luminance:new a.cj(x)}),globeRaster:x=>({u_proj_matrix:new a.cl(x),u_globe_matrix:new a.cl(x),u_normalize_matrix:new a.cl(x),u_merc_matrix:new a.cl(x),u_zoom_transition:new a.cj(x),u_merc_center:new a.ck(x),u_image0:new a.ch(x),u_image1:new a.ch(x),u_grid_matrix:new a.dC(x),u_skirt_height:new a.cj(x),u_far_z_cutoff:new a.cj(x),u_frustum_tl:new a.ci(x),u_frustum_tr:new a.ci(x),u_frustum_br:new a.ci(x),u_frustum_bl:new a.ci(x),u_globe_pos:new a.ci(x),u_globe_radius:new a.cj(x),u_viewport:new a.ck(x),u_emissive_texture_available:new a.cj(x)}),globeAtmosphere:x=>({u_frustum_tl:new a.ci(x),u_frustum_tr:new a.ci(x),u_frustum_br:new a.ci(x),u_frustum_bl:new a.ci(x),u_horizon:new a.cj(x),u_transition:new a.cj(x),u_fadeout_range:new a.cj(x),u_atmosphere_fog_color:new a.d3(x),u_high_color:new a.d3(x),u_space_color:new a.d3(x),u_temporal_offset:new a.cj(x),u_horizon_angle:new a.cj(x)}),model:x=>({u_matrix:new a.cl(x),u_lighting_matrix:new a.cl(x),u_normal_matrix:new a.cl(x),u_node_matrix:new a.cl(x),u_lightpos:new a.ci(x),u_lightintensity:new a.cj(x),u_lightcolor:new a.ci(x),u_camera_pos:new a.ci(x),u_opacity:new a.cj(x),u_baseColorFactor:new a.d3(x),u_emissiveFactor:new a.d3(x),u_metallicFactor:new a.cj(x),u_roughnessFactor:new a.cj(x),u_baseTextureIsAlpha:new a.ch(x),u_alphaMask:new a.ch(x),u_alphaCutoff:new a.cj(x),u_baseColorTexture:new a.ch(x),u_metallicRoughnessTexture:new a.ch(x),u_normalTexture:new a.ch(x),u_occlusionTexture:new a.ch(x),u_emissionTexture:new a.ch(x),u_lutTexture:new a.ch(x),u_color_mix:new a.d3(x),u_aoIntensity:new a.cj(x),u_emissive_strength:new a.cj(x),u_occlusionTextureTransform:new a.d3(x)}),modelDepth:x=>({u_matrix:new a.cl(x),u_instance:new a.cl(x),u_node_matrix:new a.cl(x)}),groundShadow:x=>({u_matrix:new a.cl(x),u_ground_shadow_factor:new a.ci(x)}),stars:x=>({u_matrix:new a.cl(x),u_up:new a.ci(x),u_right:new a.ci(x),u_intensity_multiplier:new a.cj(x)}),snowParticle:x=>({u_modelview:new a.cl(x),u_projection:new a.cl(x),u_time:new a.cj(x),u_cam_pos:new a.ci(x),u_velocityConeAperture:new a.cj(x),u_velocity:new a.cj(x),u_horizontalOscillationRadius:new a.cj(x),u_horizontalOscillationRate:new a.cj(x),u_boxSize:new a.cj(x),u_billboardSize:new a.cj(x),u_simpleShapeParameters:new a.ck(x),u_screenSize:new a.ck(x),u_thinningCenterPos:new a.ck(x),u_thinningShape:new a.ci(x),u_thinningAffectedRatio:new a.cj(x),u_thinningParticleOffset:new a.cj(x),u_particleColor:new a.d3(x),u_direction:new a.ci(x)}),rainParticle:x=>({u_modelview:new a.cl(x),u_projection:new a.cl(x),u_time:new a.cj(x),u_cam_pos:new a.ci(x),u_texScreen:new a.ch(x),u_velocityConeAperture:new a.cj(x),u_velocity:new a.cj(x),u_boxSize:new a.cj(x),u_rainDropletSize:new a.ck(x),u_distortionStrength:new a.cj(x),u_rainDirection:new a.ci(x),u_color:new a.d3(x),u_screenSize:new a.ck(x),u_thinningCenterPos:new a.ck(x),u_thinningShape:new a.ci(x),u_thinningAffectedRatio:new a.cj(x),u_thinningParticleOffset:new a.cj(x),u_shapeDirectionalPower:new a.cj(x),u_shapeNormalPower:new a.cj(x),u_mode:new a.cj(x)}),vignette:x=>({u_vignetteShape:new a.ci(x),u_vignetteColor:new a.d3(x)}),occlusion:x=>({u_matrix:new a.cl(x),u_anchorPos:new a.ci(x),u_screenSizePx:new a.ck(x),u_occluderSizePx:new a.ck(x),u_color:new a.d3(x)})};class Qu{constructor(u,f,v,S){this.id=Qu.uniqueIdxCounter,Qu.uniqueIdxCounter++,this.context=u;const T=u.gl;this.buffer=T.createBuffer(),this.dynamicDraw=!!v,this.context.unbindVAO(),u.bindElementBuffer.set(this.buffer),T.bufferData(T.ELEMENT_ARRAY_BUFFER,f.arrayBuffer,this.dynamicDraw?T.DYNAMIC_DRAW:T.STATIC_DRAW),this.dynamicDraw||S||f.destroy()}bind(){this.context.bindElementBuffer.set(this.buffer)}updateData(u){this.id=Qu.uniqueIdxCounter,Qu.uniqueIdxCounter++;const f=this.context.gl;this.context.unbindVAO(),this.bind(),f.bufferSubData(f.ELEMENT_ARRAY_BUFFER,0,u.arrayBuffer)}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer)}}Qu.uniqueIdxCounter=0;const US={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"};class PE{constructor(u,f,v,S,T,E){this.length=f.length,this.attributes=v,this.itemSize=f.bytesPerElement,this.dynamicDraw=S,this.instanceCount=E,this.context=u;const L=u.gl;this.buffer=L.createBuffer(),u.bindVertexBuffer.set(this.buffer),L.bufferData(L.ARRAY_BUFFER,f.arrayBuffer,this.dynamicDraw?L.DYNAMIC_DRAW:L.STATIC_DRAW),this.dynamicDraw||T||f.destroy()}bind(){this.context.bindVertexBuffer.set(this.buffer)}updateData(u){const f=this.context.gl;this.bind(),f.bufferSubData(f.ARRAY_BUFFER,0,u.arrayBuffer)}enableAttributes(u,f){for(let v=0;v0&&u.vertexAttribDivisor(T,v)}}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer)}}class IE{constructor(u,f,v,S,T){this.context=u,this.width=f,this.height=v;const E=this.framebuffer=u.gl.createFramebuffer();S>0&&(this.colorAttachment0=new V0(u,E,0)),S>1&&(this.colorAttachment1=new V0(u,E,1)),T&&(this.depthAttachmentType=T,this.depthAttachment=T==="renderbuffer"?new jg(u,E):new Yx(u,E))}createColorAttachment(u,f){f===0?this.colorAttachment0=new V0(u,this.framebuffer,0):f===1&&(this.colorAttachment1=new V0(u,this.framebuffer,1))}removeColorAttachment(u,f){const v=this.context.gl;let S;f===0?(S=this.colorAttachment0.get(),this.colorAttachment0=void 0):f===1&&(S=this.colorAttachment1.get(),this.colorAttachment1=void 0),S&&v.deleteTexture(S)}destroy(){const u=this.context.gl;if(this.colorAttachment0){const f=this.colorAttachment0.get();f&&u.deleteTexture(f)}if(this.colorAttachment1){const f=this.colorAttachment1.get();f&&u.deleteTexture(f)}if(this.depthAttachment&&this.depthAttachmentType)if(this.depthAttachmentType==="renderbuffer"){const f=this.depthAttachment.get();f&&u.deleteRenderbuffer(f)}else{const f=this.depthAttachment.get();f&&u.deleteTexture(f)}u.deleteFramebuffer(this.framebuffer)}}class Tg{constructor(u,f){this.gl=u,this.clearColor=new m4(this),this.clearDepth=new dE(this),this.clearStencil=new SS(this),this.colorMask=new F0(this),this.depthMask=new NS(this),this.stencilMask=new Kp(this),this.stencilFunc=new vg(this),this.stencilOp=new Kx(this),this.stencilTest=new _g(this),this.depthRange=new hE(this),this.depthTest=new CS(this),this.depthFunc=new fE(this),this.blend=new bg(this),this.blendFunc=new z0(this),this.blendColor=new B0(this),this.blendEquation=new kS(this),this.cullFace=new $0(this),this.cullFaceSide=new Zx(this),this.frontFace=new pE(this),this.program=new mE(this),this.activeTexture=new gE(this),this.viewport=new wg(this),this.bindFramebuffer=new yE(this),this.bindRenderbuffer=new g4(this),this.bindTexture=new y4(this),this.bindVertexBuffer=new x4(this),this.bindElementBuffer=new TS(this),this.bindVertexArrayOES=new ES(this),this.pixelStoreUnpack=new AS(this),this.pixelStoreUnpackPremultiplyAlpha=new PS(this),this.pixelStoreUnpackFlipY=new xE(this),this.options=f?Object.assign({},f):{},this.options.extTextureFilterAnisotropicForceOff||(this.extTextureFilterAnisotropic=u.getExtension("EXT_texture_filter_anisotropic")||u.getExtension("MOZ_EXT_texture_filter_anisotropic")||u.getExtension("WEBKIT_EXT_texture_filter_anisotropic"),this.extTextureFilterAnisotropic&&(this.extTextureFilterAnisotropicMax=u.getParameter(this.extTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT))),this.extDebugRendererInfo=u.getExtension("WEBGL_debug_renderer_info"),this.extDebugRendererInfo&&(this.renderer=u.getParameter(this.extDebugRendererInfo.UNMASKED_RENDERER_WEBGL),this.vendor=u.getParameter(this.extDebugRendererInfo.UNMASKED_VENDOR_WEBGL)),this.forceManualRenderingForInstanceIDShaders=f&&!!f.forceManualRenderingForInstanceIDShaders||this.renderer&&this.renderer.indexOf("PowerVR")!==-1,this.options.extTextureFloatLinearForceOff||(this.extTextureFloatLinear=u.getExtension("OES_texture_float_linear")),this.extRenderToTextureHalfFloat=u.getExtension("EXT_color_buffer_half_float"),this.extTimerQuery=u.getExtension("EXT_disjoint_timer_query_webgl2"),this.maxTextureSize=u.getParameter(u.MAX_TEXTURE_SIZE),this.extBlendFuncExtended=u.getExtension("WEBGL_blend_func_extended")}setDefault(){this.unbindVAO(),this.clearColor.setDefault(),this.clearDepth.setDefault(),this.clearStencil.setDefault(),this.colorMask.setDefault(),this.depthMask.setDefault(),this.stencilMask.setDefault(),this.stencilFunc.setDefault(),this.stencilOp.setDefault(),this.stencilTest.setDefault(),this.depthRange.setDefault(),this.depthTest.setDefault(),this.depthFunc.setDefault(),this.blend.setDefault(),this.blendFunc.setDefault(),this.blendColor.setDefault(),this.blendEquation.setDefault(),this.cullFace.setDefault(),this.cullFaceSide.setDefault(),this.frontFace.setDefault(),this.program.setDefault(),this.activeTexture.setDefault(),this.bindFramebuffer.setDefault(),this.pixelStoreUnpack.setDefault(),this.pixelStoreUnpackPremultiplyAlpha.setDefault(),this.pixelStoreUnpackFlipY.setDefault()}setDirty(){this.clearColor.dirty=!0,this.clearDepth.dirty=!0,this.clearStencil.dirty=!0,this.colorMask.dirty=!0,this.depthMask.dirty=!0,this.stencilMask.dirty=!0,this.stencilFunc.dirty=!0,this.stencilOp.dirty=!0,this.stencilTest.dirty=!0,this.depthRange.dirty=!0,this.depthTest.dirty=!0,this.depthFunc.dirty=!0,this.blend.dirty=!0,this.blendFunc.dirty=!0,this.blendColor.dirty=!0,this.blendEquation.dirty=!0,this.cullFace.dirty=!0,this.cullFaceSide.dirty=!0,this.frontFace.dirty=!0,this.program.dirty=!0,this.activeTexture.dirty=!0,this.viewport.dirty=!0,this.bindFramebuffer.dirty=!0,this.bindRenderbuffer.dirty=!0,this.bindTexture.dirty=!0,this.bindVertexBuffer.dirty=!0,this.bindElementBuffer.dirty=!0,this.bindVertexArrayOES.dirty=!0,this.pixelStoreUnpack.dirty=!0,this.pixelStoreUnpackPremultiplyAlpha.dirty=!0,this.pixelStoreUnpackFlipY.dirty=!0}createIndexBuffer(u,f,v){return new Qu(this,u,f,v)}createVertexBuffer(u,f,v,S,T){return new PE(this,u,f,v,S,T)}createRenderbuffer(u,f,v){const S=this.gl,T=S.createRenderbuffer();return this.bindRenderbuffer.set(T),S.renderbufferStorage(S.RENDERBUFFER,u,f,v),this.bindRenderbuffer.set(null),T}createFramebuffer(u,f,v,S){return new IE(this,u,f,v,S)}clear({color:u,depth:f,stencil:v,colorMask:S}){const T=this.gl;let E=0;u&&(E|=T.COLOR_BUFFER_BIT,this.clearColor.set(u.toNonPremultipliedRenderColor(null)),this.colorMask.set(S||[!0,!0,!0,!0])),f!==void 0&&(E|=T.DEPTH_BUFFER_BIT,this.depthRange.set([0,1]),this.clearDepth.set(f),this.depthMask.set(!0)),v!==void 0&&(E|=T.STENCIL_BUFFER_BIT,this.clearStencil.set(v),this.stencilMask.set(255)),T.clear(E)}setCullFace(u){u.enable===!1?this.cullFace.set(!1):(this.cullFace.set(!0),this.cullFaceSide.set(u.mode),this.frontFace.set(u.frontFace))}setDepthMode(u){u.func!==this.gl.ALWAYS||u.mask?(this.depthTest.set(!0),this.depthFunc.set(u.func),this.depthMask.set(u.mask),this.depthRange.set(u.range)):this.depthTest.set(!1)}setStencilMode(u){u.test.func!==this.gl.ALWAYS||u.mask?(this.stencilTest.set(!0),this.stencilMask.set(u.mask),this.stencilOp.set([u.fail,u.depthFail,u.pass]),this.stencilFunc.set({func:u.test.func,ref:u.ref,mask:u.test.mask})):this.stencilTest.set(!1)}setColorMode(u){a.by(u.blendFunction,En.Replace)?this.blend.set(!1):(this.blend.set(!0),this.blendFunc.set(u.blendFunction),this.blendColor.set(u.blendColor),u.blendEquation?this.blendEquation.set(u.blendEquation):this.blendEquation.setDefault()),this.colorMask.set(u.mask)}unbindVAO(){this.bindVertexArrayOES.set(null)}}let Xp;function Lr(x,u,f,v,S,T,E){const L=x.context,B=L.gl,q=x.transform,G=[a.aF(q.center.lng),a.aJ(q.center.lat)],ee=f.layout.get("symbol-placement"),J=f.layout.get("text-variable-anchor"),re=f.layout.get("icon-rotation-alignment")==="map",oe=f.layout.get("text-rotation-alignment")==="map",se=ee!=="point",me=[];let fe=0,Ne=0;for(let De=0;De0){const Tr=a.bC(),Mr=fr;a.cP(Tr,ot.placementInvProjMatrix,q.glCoordMatrix),a.cP(Tr,Tr,ot.placementViewportMatrix),me.push({circleArray:Ur,circleOffset:Ne,transform:Mr,invTransform:Tr,projection:ot.getProjection()}),fe+=Ur.length/4,Ne=fe}if(!lr)continue;x.terrain&&x.terrain.setupElevationDraw(ht,Pr);const Fr=Zt?[Qe.canonical.x,Qe.canonical.y,1<=0&&(re[Ae.associatedIconIndex]={x:ot,y:Tt,z:At,angle:Mt})}else Zu($e,ee)}if(q){J.clear();const Ne=x.icon.placedSymbolArray;for(let Ae=0;Ae{let ms=[0,0,0];if(Ls){const Pn=x.style.directionalLight,Ti=x.style.ambientLight;Pn&&Ti&&(ms=kh(x.style,Pn,Ti))}return ms},Cs=Ls=>{De.depthOcclusionForSymbolsAndCircles&&(f.hasOcclusionOpacityProperties||x.terrain)&&(Ls.push("DEPTH_D24"),Ls.push("DEPTH_OCCLUSION"))},Sn=Ls=>{f.lut&&!$e&&(f.lut.texture||(f.lut.texture=new a.d$(x.context,f.lut.image,[f.lut.image.height,f.lut.image.height,f.lut.image.height],He.gl.RGBA8)),He.activeTexture.set(He.gl.TEXTURE0+_o.LUT),f.lut.texture&&f.lut.texture.bind(He.gl.LINEAR,He.gl.CLAMP_TO_EDGE),Ls.push("APPLY_LUT_ON_GPU"))},Ds=()=>{const Ls=Qe&&f.layout.get("symbol-placement")!=="point",ms=[];Cs(ms),Sn(ms);const Pn=Ls||Cn,Ti=lr.elevationType==="road",ua=x.shadowRenderer,Wi=Ti&&ot&&!!ua&&ua.enabled,ci=qr(Wi),Ll=Ti&&ot&&!x.terrain?wt:or,Uo=f.paint.get("icon-image-cross-fade");x.terrainRenderModeElevated()&&ot&&ms.push("PITCH_WITH_MAP_TERRAIN"),Ur&&(ms.push("PROJECTION_GLOBE_VIEW"),Pn&&ms.push("PROJECTED_POS_ON_VIEWPORT")),Uo>0&&lr.hasAnySecondaryIcon&&ms.push("ICON_TRANSITION"),!lr.icon.zOffsetVertexBuffer||Ti&&x.terrain||ms.push("Z_OFFSET"),fe===0&&Ne===0&&Ae===0&&Te===1||ms.push("COLOR_ADJUSTMENT"),lr.sdfIcons&&ms.push("RENDER_SDF"),Wi&&ms.push("RENDER_SHADOWS","DEPTH_TEXTURE","NORMAL_OFFSET"),Ti&&ot&&!x.terrain&&lr.icon.orientationVertexBuffer&&ms.push("ELEVATED_ROADS");const Ba=lr.icon.programConfigurations.get(f.id),nl=x.getOrCreateProgram("symbol",{config:Ba,defines:ms}),sl=fr.imageAtlasTexture?fr.imageAtlasTexture.size:[0,0],To=lr.iconSizeData,Hc=a.bK(To,De.zoom),Cu=ot||!De.isOrthographic,oc=vl(Tr,fr.tileID.canonical,ot,Qe,De,lr.getProjection(),Mr),ra=Fx(Tr,fr.tileID.canonical,ot,Qe,De,lr.getProjection(),Mr),ma=x.translatePosMatrix(ra,fr,L,q,!0),ui=x.translatePosMatrix(Tr,fr,L,q),wa=Pn?rv:oc,Ji=Qe&&!ot&&!Ls;let Gi=yr;!kt&&!De.mercatorFromTransition||Qe||(Gi=Eh(De));const ku=Ur?Gi:yr,mv=f.getColorAdjustmentMatrix(fe,Ne,Ae,Te),td=J0(To.kind,Hc,Ji,ot,x,ui,wa,ma,Ze,!1,sl,[0,0],0,Pr,Fr,st,as,ku,lr.getProjection(),ci,Is,mv,Uo,null),gv=fr.imageAtlasTexture?fr.imageAtlasTexture:null,Lg=f.layout.get("icon-size").constantOr(0)!==1||lr.iconsNeedLinear,$d=lr.sdfIcons||x.options.rotating||x.options.zooming||Lg||Cu?ze.LINEAR:ze.NEAREST,Fh=lr.sdfIcons&&f.paint.get("icon-halo-width").constantOr(1)!==0,Fg=x.terrain&&ot&&Ls?a.bl(a.bC(),oc):rv;if(Ls&&lr.icon){const Yf=a.bV.getAtTileOffsetFunc(Pr,De.center.lat,De.worldSize,lr.getProjection()),zh=w0(Tr,fr.tileID.canonical,ot,Qe,De,lr.getProjection(),Mr),rd=f.layout.get("icon-size-scale-range"),Bh=a.aA(x.scaleFactor,rd[0],rd[1]);rE(lr,Tr,x,!1,zh,ra,ot,se,Yf,Pr,Bh)}return{program:nl,buffers:lr.icon,uniformValues:td,atlasTexture:gv,atlasTextureIcon:null,atlasInterpolation:$d,atlasInterpolationIcon:null,isSDF:lr.sdfIcons,hasHalo:Fh,depthMode:Ll,tile:fr,renderWithShadows:Wi,labelPlaneMatrixInv:Fg}},Ys=()=>{const Ls=ht&&f.layout.get("symbol-placement")!=="point",ms=[],Pn=Ls||Mt||Cn,Ti=lr.elevationType==="road",ua=x.shadowRenderer,Wi=Ti&&Tt&&!!ua&&ua.enabled,ci=qr(Wi),Ll=Ti&&Tt&&!x.terrain?wt:or;x.terrainRenderModeElevated()&&Tt&&ms.push("PITCH_WITH_MAP_TERRAIN"),Ur&&(ms.push("PROJECTION_GLOBE_VIEW"),Pn&&ms.push("PROJECTED_POS_ON_VIEWPORT")),!lr.text.zOffsetVertexBuffer||Ti&&x.terrain||ms.push("Z_OFFSET"),lr.iconsInText&&ms.push("RENDER_TEXT_AND_SYMBOL"),ms.push("RENDER_SDF"),Wi&&ms.push("RENDER_SHADOWS","DEPTH_TEXTURE","NORMAL_OFFSET"),Ti&&Tt&&!x.terrain&&lr.text.orientationVertexBuffer&&ms.push("ELEVATED_ROADS"),Cs(ms);const Uo=lr.text.programConfigurations.get(f.id),Ba=x.getOrCreateProgram("symbol",{config:Uo,defines:ms});let nl,sl=[0,0],To=null;const Hc=lr.textSizeData;lr.iconsInText&&(sl=fr.imageAtlasTexture?fr.imageAtlasTexture.size:[0,0],To=fr.imageAtlasTexture?fr.imageAtlasTexture:null,nl=Tt||!De.isOrthographic||x.options.rotating||x.options.zooming||Hc.kind==="composite"||Hc.kind==="camera"?ze.LINEAR:ze.NEAREST);const Cu=fr.glyphAtlasTexture?fr.glyphAtlasTexture.size:[0,0],oc=f.layout.get("text-size-scale-range"),ra=a.aA(x.scaleFactor,oc[0],oc[1]),ma=a.bK(Hc,De.zoom,ra),ui=vl(Tr,fr.tileID.canonical,Tt,ht,De,lr.getProjection(),Mr),wa=Fx(Tr,fr.tileID.canonical,Tt,ht,De,lr.getProjection(),Mr),Ji=x.translatePosMatrix(wa,fr,B,G,!0),Gi=x.translatePosMatrix(Tr,fr,B,G),ku=Pn?rv:ui,mv=ht&&!Tt&&!Ls;let td=yr;!kt&&!De.mercatorFromTransition||ht||(td=Eh(De));const gv=J0(Hc.kind,ma,mv,Tt,x,Gi,ku,Ji,Ze,!0,Cu,sl,0,Pr,Fr,st,as,Ur?td:yr,lr.getProjection(),ci,Is,null,null,ra),Lg=fr.glyphAtlasTexture?fr.glyphAtlasTexture:null,$d=ze.LINEAR,Fh=f.paint.get("text-halo-width").constantOr(1)!==0,Fg=x.terrain&&Tt&&Ls?a.bl(a.bC(),ui):rv;if(Ls&&lr.text){const Yf=a.bV.getAtTileOffsetFunc(Pr,De.center.lat,De.worldSize,lr.getProjection()),zh=w0(Tr,fr.tileID.canonical,Tt,ht,De,lr.getProjection(),Mr);rE(lr,Tr,x,!0,zh,wa,Tt,me,Yf,Pr,ra)}return{program:Ba,buffers:lr.text,uniformValues:gv,atlasTexture:Lg,atlasTextureIcon:To,atlasInterpolation:$d,atlasInterpolationIcon:nl,isSDF:!0,hasHalo:Fh,depthMode:Ll,tile:fr,renderWithShadows:Wi,labelPlaneMatrixInv:Fg}},Vs=lr.icon.segments.get().length,ws=lr.text.segments.get().length,An=Vs&&!E.onlyText?Ds():null,Rs=ws&&!E.onlyIcons?Ys():null,Qi=f.paint.get("icon-opacity").constantOr(1),Li=f.paint.get("text-opacity").constantOr(1);if(At&&lr.canOverlap){Bt=!0;const Ls=Qi&&!E.onlyText?lr.icon.segments.get():[],ms=Li&&!E.onlyIcons?lr.text.segments.get():[];for(const Pn of Ls)Zt.push({segments:new a.bg([Pn]),sortKey:Pn.sortKey,state:An});for(const Pn of ms)Zt.push({segments:new a.bg([Pn]),sortKey:Pn.sortKey,state:Rs})}else E.onlyText||Zt.push({segments:Qi?lr.icon.segments:new a.bg([]),sortKey:0,state:An}),E.onlyIcons||Zt.push({segments:Li?lr.text.segments:new a.bg([]),sortKey:0,state:Rs})}Bt&&Zt.sort((Pr,fr)=>Pr.sortKey-fr.sortKey);for(const Pr of Zt){const fr=Pr.state;if(fr)if(x.terrain?x.terrain.setupElevationDraw(fr.tile,fr.program,{useDepthForOcclusion:De.depthOcclusionForSymbolsAndCircles,labelPlaneMatrixInv:fr.labelPlaneMatrixInv}):x.setupDepthForOcclusion(De.depthOcclusionForSymbolsAndCircles,fr.program),He.activeTexture.set(ze.TEXTURE0),fr.atlasTexture&&fr.atlasTexture.bind(fr.atlasInterpolation,ze.CLAMP_TO_EDGE,!0),fr.atlasTextureIcon&&(He.activeTexture.set(ze.TEXTURE1),fr.atlasTextureIcon&&fr.atlasTextureIcon.bind(fr.atlasInterpolationIcon,ze.CLAMP_TO_EDGE,!0)),fr.renderWithShadows&&x.shadowRenderer.setupShadows(fr.tile.tileID.toUnwrapped(),fr.program,"vector-tile"),x.uploadCommonLightUniforms(x.context,fr.program),fr.hasHalo){const lr=fr.uniformValues;lr.u_is_halo=1,VS(fr.buffers,Pr.segments,f,x,fr.program,fr.depthMode,S,T,lr,2),lr.u_is_halo=0}else{if(fr.isSDF){const lr=fr.uniformValues;fr.hasHalo&&(lr.u_is_halo=1,VS(fr.buffers,Pr.segments,f,x,fr.program,fr.depthMode,S,T,lr,1)),lr.u_is_halo=0}VS(fr.buffers,Pr.segments,f,x,fr.program,fr.depthMode,S,T,fr.uniformValues,1)}}}function VS(x,u,f,v,S,T,E,L,B,q){const G=[x.dynamicLayoutVertexBuffer,x.opacityVertexBuffer,x.iconTransitioningVertexBuffer,x.globeExtVertexBuffer,x.zOffsetVertexBuffer,x.orientationVertexBuffer];S.draw(v,v.context.gl.TRIANGLES,T,E,L,vn.disabled,B,f.id,x.layoutVertexBuffer,x.indexBuffer,u,f.paint,v.transform.zoom,x.programConfigurations.get(f.id),G,q)}function ME(x,u){const f=1<=Xu?1:re.pitch/Xu))),2*oe}(x.transform),q=x.transform.getFreeCameraOptions().position,G="elevatedStructuresDepthReconstruct",ee=x.getOrCreateProgram(G,{defines:["DEPTH_RECONSTRUCTION"]}),J=x.getOrCreateProgram(G);for(const re of v){const oe=u.getTile(re),se=oe.getBucket(f);if(!se)continue;const me=se.elevatedStructures;if(!me)continue;const fe=se.elevationBufferData.heightRange,Ne=ME(re.toUnwrapped(),q),Ae=x.translatePosMatrix(re.projMatrix,oe,f.paint.get("fill-translate"),f.paint.get("fill-translate-anchor"));let Te,Ze,$e,He;if(S==="initialize"){if(!fe||fe.min>=1||me.depthSegments.segments[0].primitiveLength===0)continue;Te=Zp(Ae,Ne,B,1,0),Ze=E,$e=me.depthSegments,He=ee}else if(S==="reset"){if(!fe||fe.min>=0||me.maskSegments.segments[0].primitiveLength===0)continue;Te=Zp(Ae,Ne,0,0,1),Ze=L,$e=me.maskSegments,He=ee}else if(S==="geometry"){if(me.depthSegments.segments[0].primitiveLength===0)continue;Te=Zp(Ae,Ne,B,1,0),Ze=E,$e=me.depthSegments,He=J}He.draw(x,T.TRIANGLES,Ze,_n.disabled,En.disabled,vn.disabled,Te,f.id,me.vertexBuffer,me.indexBuffer,$e,f.paint,x.transform.zoom)}}function rb(x,u,f,v){const{painter:S,sourceCache:T,layer:E,coords:L,colorMode:B,elevationType:q,terrainEnabled:G,pass:ee}=x,J=S.context.gl,re=E.paint.get("fill-pattern"),oe=E.paint.get("fill-pattern-cross-fade"),se=re.constantOr(null);let me=q;q!=="road"||u&&!G||(me="none");const fe=me==="road",Ne=x.painter.shadowRenderer,Ae=fe&&!!Ne&&Ne.enabled,Te=new Wr(S.context.gl.LEQUAL,Wr.ReadOnly,S.depthRangeFor3D);let Ze=[0,0,0];if(Ae){const De=S.style.directionalLight,Qe=S.style.ambientLight;De&&Qe&&(Ze=kh(S.style,De,Qe))}const $e=re&&re.constantOr(1),He=S.terrain&&S.terrain.renderingToTexture,ze=(De,Qe)=>{let ht,ot,Tt,At,Bt;Qe?(ht=$e&&!E.getPaintProperty("fill-outline-color")?"fillOutlinePattern":"fillOutline",Tt=J.LINES):(ht=$e?"fillPattern":"fill",Tt=J.TRIANGLES);for(const or of L){const wt=T.getTile(or);if($e&&!wt.patternsLoaded())continue;const st=wt.getBucket(E);if(!st)continue;const Mt=u?st.elevationBufferData:st.bufferData;if(Mt.isEmpty())continue;S.prepareDrawTile();const kt=Mt.programConfigurations.get(E.id),Zt=S.isTileAffectedByFog(or),yr=[],Pr=[];fe&&(yr.push("ELEVATED_ROADS"),Pr.push(Mt.elevatedLayoutVertexBuffer)),Ae&&yr.push("RENDER_SHADOWS","DEPTH_TEXTURE","NORMAL_OFFSET"),He&&f&&yr.push("USE_MRT1"),$e&&(S.context.activeTexture.set(J.TEXTURE0),wt.imageAtlasTexture&&wt.imageAtlasTexture.bind(J.LINEAR,J.CLAMP_TO_EDGE),kt.updatePaintBuffers());let fr=!1;if(se&&wt.imageAtlas){const Mr=wt.imageAtlas,tn=a.e3.from(se),Cn=tn.getPrimary().scaleSelf(a.o.devicePixelRatio).toString(),as=tn.getSecondary(),Is=Mr.patternPositions.get(Cn),qr=as?Mr.patternPositions.get(as.scaleSelf(a.o.devicePixelRatio).toString()):null;fr=!!Is&&!!qr,Is&&kt.setConstantPatternPositions(Is,qr)}oe>0&&(fr||kt.getPatternTransitionVertexBuffer("fill-pattern"))&&yr.push("FILL_PATTERN_TRANSITION");const lr=S.getOrCreateProgram(ht,{config:kt,overrideFog:Zt,defines:yr}),Ur=S.translatePosMatrix(or.projMatrix,wt,E.paint.get("fill-translate"),E.paint.get("fill-translate-anchor"));Ae&&Ne.setupShadows(wt.tileID.toUnwrapped(),lr,"vector-tile");const Fr=E.paint.get("fill-emissive-strength");if(Qe){At=Mt.lineIndexBuffer,Bt=Mt.lineSegments;const Mr=S.terrain&&S.terrain.renderingToTexture?S.terrain.drapeBufferSize:[J.drawingBufferWidth,J.drawingBufferHeight];ot=ht==="fillOutlinePattern"&&$e?zS(Ur,Fr,S,wt,Mr,Ze,oe):jE(Ur,Fr,Mr,Ze)}else At=Mt.indexBuffer,Bt=Mt.triangleSegments,ot=$e?FS(Ur,Fr,S,wt,Ze,oe):LS(Ur,Fr,Ze);S.uploadCommonUniforms(S.context,lr,or.toUnwrapped());let Tr=De;(q==="road"&&!G||q==="offset")&&(Tr=Te),lr.draw(S,Tt,Tr,v||S.stencilModeForClipping(or),B,vn.disabled,ot,E.id,Mt.layoutVertexBuffer,At,Bt,E.paint,S.transform.zoom,kt,Pr)}};S.renderPass===ee&&ze(S.depthModeForSublayer(1,S.renderPass==="opaque"?Wr.ReadWrite:Wr.ReadOnly),!1),me==="none"&&S.renderPass==="translucent"&&E.paint.get("fill-antialias")&&ze(S.depthModeForSublayer(E.getPaintProperty("fill-outline-color")?2:0,Wr.ReadOnly),!0)}function nb(x,u,f,v,S,T,E,L){f.resetLayerRenderingStats(x);const B=x.context,q=B.gl,G=x.transform,ee=f.paint.get("fill-extrusion-pattern"),J=f.paint.get("fill-extrusion-pattern-cross-fade"),re=ee.constantOr(null),oe=ee.constantOr(1),se=f.paint.get("fill-extrusion-opacity"),me=x.style.enable3dLights(),fe=f.paint.get(me&&!oe?"fill-extrusion-ambient-occlusion-wall-radius":"fill-extrusion-ambient-occlusion-radius"),Ne=[f.paint.get("fill-extrusion-ambient-occlusion-intensity"),fe],Ae=f.layout.get("fill-extrusion-edge-radius"),Te=Ae>0&&!f.paint.get("fill-extrusion-rounded-roof"),Ze=Te?0:Ae,$e=G.projection.name==="globe"?a.eb():0,He=G.projection.name==="globe",ze=He?a.aj(G.zoom):0,De=[a.aF(G.center.lng),a.aJ(G.center.lat)],Qe=f.paint.get("fill-extrusion-flood-light-color-use-theme").constantOr("default")==="none",ht=f.paint.get("fill-extrusion-flood-light-color").toNonPremultipliedRenderColor(Qe?null:f.lut).toArray01().slice(0,3),ot=f.paint.get("fill-extrusion-flood-light-intensity"),Tt=f.paint.get("fill-extrusion-vertical-scale"),At=f.paint.get("fill-extrusion-line-width").constantOr(1)!==0,Bt=f.paint.get("fill-extrusion-height-alignment"),or=f.paint.get("fill-extrusion-base-alignment"),wt=Df(x,f.paint.get("fill-extrusion-cutoff-fade-range")),st=[];let Mt;He&&st.push("PROJECTION_GLOBE_VIEW"),Ne[0]>0&&st.push("FAUX_AO"),Te&&st.push("ZERO_ROOF_RADIUS"),L&&st.push("HAS_CENTROID"),ot>0&&st.push("FLOOD_LIGHT"),wt.shouldRenderCutoff&&st.push("RENDER_CUTOFF"),At&&st.push("RENDER_WALL_MODE");const kt=x.renderPass==="shadow",Zt=x.shadowRenderer,yr=kt&&!!Zt,Pr=kt?vn.disabled:vn.backCCW;x.shadowRenderer&&(x.shadowRenderer.useNormalOffset=!0);let fr=[0,0,0];if(Zt){const Fr=x.style.directionalLight,Tr=x.style.ambientLight;Fr&&Tr&&(fr=kh(x.style,Fr,Tr)),kt||(st.push("RENDER_SHADOWS","DEPTH_TEXTURE"),Zt.useNormalOffset&&st.push("NORMAL_OFFSET")),Mt=st.concat(["SHADOWS_SINGLE_CASCADE"])}const lr=yr?"fillExtrusionDepth":oe?"fillExtrusionPattern":"fillExtrusion",Ur=f.getLayerRenderingStats();for(const Fr of v){const Tr=u.getTile(Fr),Mr=Tr.getBucket(f);if(!Mr||Mr.projection.name!==G.projection.name)continue;let tn=!1;Zt&&(tn=Zt.getMaxCascadeForTile(Fr.toUnwrapped())===0);const Cn=x.isTileAffectedByFog(Fr),as=Mr.programConfigurations.get(f.id);let Is=!1;if(re&&Tr.imageAtlas){const ws=Tr.imageAtlas,An=a.e3.from(re),Rs=An.getPrimary().scaleSelf(a.o.devicePixelRatio).toString(),Qi=An.getSecondary(),Li=ws.patternPositions.get(Rs),Ls=Qi?ws.patternPositions.get(Qi.scaleSelf(a.o.devicePixelRatio).toString()):null;Is=!!Li&&!!Ls,Li&&as.setConstantPatternPositions(Li,Ls)}J>0&&(Is||as.getPatternTransitionVertexBuffer("fill-extrusion-pattern"))&&st.push("FILL_EXTRUSION_PATTERN_TRANSITION");const qr=x.getOrCreateProgram(lr,{config:as,defines:tn?Mt:st,overrideFog:Cn});if(x.terrain&&x.terrain.setupElevationDraw(Tr,qr,{useMeterToDem:!0}),!Mr.centroidVertexBuffer){const ws=qr.getAttributeLocation(q,"a_centroid_pos");ws!==-1&&q.vertexAttrib2f(ws,0,0)}!kt&&Zt&&Zt.setupShadows(Tr.tileID.toUnwrapped(),qr,"vector-tile"),oe&&(x.context.activeTexture.set(q.TEXTURE0),Tr.imageAtlasTexture&&Tr.imageAtlasTexture.bind(q.LINEAR,q.CLAMP_TO_EDGE),as.updatePaintBuffers());const Cs=f.paint.get("fill-extrusion-vertical-gradient"),Sn=1/Mr.tileToMeter;let Ds;if(kt&&Zt){if(Ph(Tr.tileID,Mr.maxHeight,x))continue;const ws=Zt.calculateShadowPassMatrixFromTile(Tr.tileID.toUnwrapped());Ds=DS(ws,Ze,Sn,Tt,Bt,or)}else{const ws=x.translatePosMatrix(Fr.expandedProjMatrix,Tr,f.paint.get("fill-extrusion-translate"),f.paint.get("fill-extrusion-translate-anchor")),An=G.projection.createInversionMatrix(G,Fr.canonical);Ds=oe?wE(ws,x,Cs,se,Ne,Ze,Sn,Fr,Tr,$e,Bt,or,ze,De,An,ht,Tt,J):Z0(ws,x,Cs,se,Ne,Ze,Sn,Fr,$e,Bt,or,ze,De,An,ht,Tt,ot,fr)}x.uploadCommonUniforms(B,qr,Fr.toUnwrapped(),null,wt);let Ys=Mr.segments;if(G.projection.name==="mercator"&&!kt&&(Ys=Mr.getVisibleSegments(Tr.tileID,x.terrain,x.transform.getFrustum(0)),!Ys.get().length))continue;if(Ur)if(kt)for(const ws of Ys.get())Ur.numRenderedVerticesInShadowPass+=ws.primitiveLength;else for(const ws of Ys.get())Ur.numRenderedVerticesInTransparentPass+=ws.primitiveLength;const Vs=[];(x.terrain||L)&&Vs.push(Mr.centroidVertexBuffer),He&&Vs.push(Mr.layoutVertexExtBuffer),At&&Vs.push(Mr.wallVertexBuffer),qr.draw(x,B.gl.TRIANGLES,S,T,E,Pr,Ds,f.id,Mr.layoutVertexBuffer,Mr.indexBuffer,Ys,f.paint,x.transform.zoom,as,Vs)}x.shadowRenderer&&(x.shadowRenderer.useNormalOffset=!1)}class qS{constructor(){this.translate=[0,0],this.translateAnchor="map",this.edgeRadius=0,this.cutoffFadeRange=0}}function Ah(x,u,f,v,S,T,E,L,B,q,G,ee,J,re,oe,se,me,fe,Ne,Ae){const Te=u.context,Ze=Te.gl,$e=u.transform,He=u.transform.zoom,ze=[],De=x.translate,Qe=x.translateAnchor,ht=x.edgeRadius,ot=Df(u,x.cutoffFadeRange);G==="clear"?(ze.push("CLEAR_SUBPASS"),Ae&&(ze.push("CLEAR_FROM_TEXTURE"),Te.activeTexture.set(Ze.TEXTURE0),Ae.bind(Ze.LINEAR,Ze.CLAMP_TO_EDGE))):G==="sdf"?ze.push("SDF_SUBPASS"):G==="emissive"&&(ze.push("USE_MRT1"),Te.activeTexture.set(Ze.TEXTURE0),Ae.bind(Ze.LINEAR,Ze.CLAMP_TO_EDGE)),fe&&ze.push("HAS_CENTROID"),ot.shouldRenderCutoff&&ze.push("RENDER_CUTOFF");const Tt=(At,Bt,or,wt,st)=>{let Mt=ze;Bt.groundRadiusBuffer!=null&&(Mt=ze.concat("HAS_ATTRIBUTE_a_flood_light_ground_radius"));const kt=Bt.programConfigurations.get(v.id),Zt=u.isTileAffectedByFog(At),yr=u.getOrCreateProgram("fillExtrusionGroundEffect",{config:kt,defines:Mt,overrideFog:Zt}),Pr=Cg(u,wt,ee,q,st,[J,re*st],oe,se,me,He>=17?0:ht*st,Ae?Ae.size[0]:0),fr=[];fe&&fr.push(Bt.hiddenByLandmarkVertexBuffer),Bt.groundRadiusBuffer!=null&&fr.push(Bt.groundRadiusBuffer),u.uploadCommonUniforms(Te,yr,At.toUnwrapped(),null,ot),yr.draw(u,Te.gl.TRIANGLES,T,E,L,B,Pr,v.id,Bt.vertexBuffer,Bt.indexBuffer,or,v.paint,He,kt,fr)};for(const At of S){const Bt=f.getTile(At),or=Bt.getBucket(v);if(!or||or.projection.name!==$e.projection.name||!or.groundEffect||or.groundEffect&&!or.groundEffect.hasData())continue;const wt=or.groundEffect,st=1/or.tileToMeter;{const Mt=u.translatePosMatrix(At.projMatrix,Bt,De,Qe),kt=wt.getDefaultSegment();Tt(At,wt,kt,Mt,st)}if(Ne)for(let Mt=0;Mt<4;Mt++){const kt=a.e9[Mt](At),Zt=f.getTile(kt);if(!Zt)continue;const yr=Zt.getBucket(v);if(!yr||yr.projection.name!==$e.projection.name||!yr.groundEffect||yr.groundEffect&&!yr.groundEffect.hasData())continue;const Pr=yr.groundEffect;let fr,lr;Mt===0?(fr=[-a.al,0,0],lr=1):Mt===1?(fr=[a.al,0,0],lr=0):Mt===2?(fr=[0,-a.al,0],lr=3):(fr=[0,a.al,0],lr=2);const Ur=Pr.regionSegments[lr];if(!Ur)continue;const Fr=new Float32Array(16);a.br(Fr,At.projMatrix,fr),Tt(At,Pr,Ur,u.translatePosMatrix(Fr,Bt,De,Qe),st)}}}function S4(x,u,f,v,S,T,E){v.centroidVertexArray.length===0&&v.createCentroidsBuffer();const L=T?T.findDEMTileFor(f):null;if(!(L&&L.dem||E))return;T&&L&&L.dem&&v.selfDEMTileTimestamp!==L.dem._timestamp&&(v.borderDoneWithNeighborZ=[-1,-1,-1,-1],v.selfDEMTileTimestamp=L.dem._timestamp);const B=fe=>new a.P(Math.ceil((fe+a.ed)*a.ee),0),q=fe=>{const Ne=u.getSource().minzoom,Ae=Ze=>{const $e=u.getTileByID(Ze);if($e&&$e.hasData())return $e.getBucket(S)},Te=[0,-1,1];for(const Ze of Te){if(fe.overscaledZ+Ze(G[0]=Math.min(fe.min.y,Ne.min.y),G[1]=Math.max(fe.max.y,Ne.max.y),G[2]=a.al-Ne.min.x>fe.max.x?Ne.min.x-a.al:fe.max.x,G),J=(fe,Ne)=>(G[0]=Math.min(fe.min.x,Ne.min.x),G[1]=Math.max(fe.max.x,Ne.max.x),G[2]=a.al-Ne.min.y>fe.max.y?Ne.min.y-a.al:fe.max.y,G),re=[(fe,Ne)=>ee(fe,Ne),(fe,Ne)=>ee(Ne,fe),(fe,Ne)=>J(fe,Ne),(fe,Ne)=>J(Ne,fe)],oe=(fe,Ne,Ae,Te,Ze,$e,He)=>{if(!T)return 0;const ze=[[$e?Ae:fe,$e?fe:Ae,0],[$e?Ae:Ne,$e?Ne:Ae,0]],De=He<0?a.al+He:He,Qe=[$e?De:(fe+Ne)/2,$e?(fe+Ne)/2:De,0];return Ae===0&&He<0||Ae!==0&&He>0?T.getForTilePoints(Ze,[Qe],!0,Te):ze.push(Qe),T.getForTilePoints(f,ze,!0,L),Math.max(ze[0][2],ze[1][2],Qe[2])/T.exaggeration()};for(let fe=0;fe<4;fe++){const Ne=v.borderFeatureIndices[fe];if(Ne.length===0)continue;const Ae=a.e9[fe](f),Te=q(Ae);if(!(Te&&Te instanceof a.ea))continue;const Ze=T?T.findDEMTileFor(Ae):null;if(!(Ze&&Ze.dem||E)||(T&&Ze&&Ze.dem&&v.borderDEMTileTimestamp[fe]!==Ze.dem._timestamp&&(v.borderDoneWithNeighborZ[fe]=-1,v.borderDEMTileTimestamp[fe]=Ze.dem._timestamp),v.borderDoneWithNeighborZ[fe]===Te.canonical.z))continue;Te.centroidVertexArray.length===0&&Te.createCentroidsBuffer();const $e=(fe<2?1:5)-fe,He=Te.borderDoneWithNeighborZ[$e]!==v.canonical.z,ze=Te.borderFeatureIndices[$e];let De=0;if(v.canonical.z!==Te.canonical.z){for(const Qe of Ne)v.showCentroid(v.featuresOnBorder[Qe]);if(He)for(const Qe of ze)Te.showCentroid(Te.featuresOnBorder[Qe]);v.borderDoneWithNeighborZ[fe]=Te.canonical.z,Te.borderDoneWithNeighborZ[$e]=v.canonical.z}for(const Qe of Ne){const ht=v.featuresOnBorder[Qe],ot=v.centroidData[ht.centroidDataIndex],Tt=ht.borders[fe];let At;for(;DeTt[0]+3||Bt[0]>Tt[0]-3)break;Te.showCentroid(At),De++}if(At&&DeTt[1]-3)&&(or++,++De!==ze.length);)At=Te.featuresOnBorder[ze[De]];At=Te.featuresOnBorder[ze[Bt]];let wt=!1;if(or>=1){const kt=At.borders[$e];Math.abs(Tt[0]-kt[0])<3&&Math.abs(Tt[1]-kt[1])<3&&(or=1,wt=!0,De=Bt+1)}else if(or===0){v.showCentroid(ht);continue}const st=Te.centroidData[At.centroidDataIndex];E&&wt&&(((se=ot).flags|(me=st).flags)&a.ec?(se.flags|=a.ec,me.flags|=a.ec):(se.flags&=~a.ec,me.flags&=~a.ec));const Mt=ht.intersectsCount()>1||At.intersectsCount()>1;if(or>1)De=Bt,ot.centroidXY=st.centroidXY=new a.P(0,0);else if(Ze&&Ze.dem&&!Mt){const kt=re[fe](ot,st),Zt=fe%2?a.al-1:0,yr=oe(kt[0],Math.min(a.al-1,kt[1]),Zt,Ze,Ae,fe<2,kt[2]);ot.centroidXY=st.centroidXY=B(yr)}else Mt?ot.centroidXY=st.centroidXY=new a.P(0,0):(ot.centroidXY=v.encodeBorderCentroid(ht),st.centroidXY=Te.encodeBorderCentroid(At));v.writeCentroidToBuffer(ot),Te.writeCentroidToBuffer(st)}else v.showCentroid(ht)}v.borderDoneWithNeighborZ[fe]=Te.canonical.z,Te.borderDoneWithNeighborZ[$e]=v.canonical.z}var se,me;(v.needsCentroidUpdate||!v.centroidVertexBuffer&&v.centroidVertexArray.length!==0)&&v.uploadCentroid(x)}const Sc=[1,0,0],HS=[0,1,0],Rl=[0,0,1];function Ph(x,u,f){const v=f.transform,S=f.shadowRenderer;if(!S)return!0;const T=x.toUnwrapped(),E=v.tileSize*S._cascades[f.currentShadowCascade].scale;let L=u;if(v.elevation){const se=v.elevation.getMinMaxForTile(x);se&&(L+=se.max)}const B=[...S.shadowDirection];B[2]=-B[2];const q=S.computeSimplifiedTileShadowVolume(T,L,E,B);if(!q)return!1;const G=[Sc,HS,Rl,B,[B[0],0,B[2]],[0,B[1],B[2]]],ee=v.projection.name==="globe",J=v.scaleZoom(E),re=a.cB.fromInvProjectionMatrix(v.invProjMatrix,v.worldSize,J,!ee),oe=S.getCurrentCascadeFrustum();return re.intersectsPrecise(q.vertices,q.planes,G)===0||oe.intersectsPrecise(q.vertices,q.planes,G)===0}function sv(x){const{painter:u,source:f,layer:v,coords:S}=x;let T=x.defines;const E=u.context,L=u.renderPass==="shadow",B=u.renderPass==="light-beam",q=u.shadowRenderer,G=a.ef(u.transform.center.lat,u.transform.zoom),ee=Df(u,v.paint.get("building-cutoff-fade-range"));ee.shouldRenderCutoff&&(T=T.concat("RENDER_CUTOFF")),x.floodLightIntensity>0&&(T=T.concat("FLOOD_LIGHT"));for(const J of S){const re=f.getTile(J),oe=re.getBucket(v);if(!oe)continue;q&&q.getMaxCascadeForTile(J.toUnwrapped())===0&&(T=T.concat("SHADOWS_SINGLE_CASCADE"));const se=oe.programConfigurations.get(v.id);let me,fe,Ne,Ae=u.translatePosMatrix(J.expandedProjMatrix,re,[0,0],"map");if(Ae=a.cS(a.bC(),Ae,[1,1,x.verticalScale]),L&&q){if(Ph(re.tileID,oe.maxHeight*G,u))continue;let Ze=q.calculateShadowPassMatrixFromTile(re.tileID.toUnwrapped());Ze=a.cS(a.bC(),Ze,[1,1,x.verticalScale]),Ne=Vf(Ze),me=fe=u.getOrCreateProgram("buildingDepth",{config:se,defines:T,overrideFog:!1})}else if(B)me=fe=u.getOrCreateProgram("buildingBloom",{config:se,defines:T,overrideFog:!1}),Ne=SE(Ae);else{const Ze=u.transform.calculatePosMatrix(J.toUnwrapped(),u.transform.worldSize);a.cS(Ze,Ze,[1,1,x.verticalScale]);const $e=a.bC();a.cS($e,Ze,[1,-1,1/G]),a.bl($e,$e),a.eg($e,$e);const He=u.transform.getFreeCameraOptions().position,ze=1<{if(B){const He=Ze.entranceBloom;$e.draw(u,E.gl.TRIANGLES,x.depthMode,_n.disabled,x.blendMode,vn.disabled,Ne,v.id,He.layoutVertexBuffer,He.indexBuffer,He.segmentsBucket,v.paint,u.transform.zoom,se,[He.layoutAttenuationBuffer,He.layoutColorBuffer])}else{const He=Ze.segmentsBucket;let ze=[Ze.layoutNormalBuffer,Ze.layoutCentroidBuffer,Ze.layoutColorBuffer,Ze.layoutFloodLightDataBuffer];Ze.layoutFacadePaintBuffer&&(ze=ze.concat([Ze.layoutFacadeDataBuffer,Ze.layoutFacadeVerticalRangeBuffer,Ze.layoutFacadePaintBuffer])),$e.draw(u,E.gl.TRIANGLES,x.depthMode,_n.disabled,x.blendMode,L?vn.disabled:vn.backCW,Ne,v.id,Ze.layoutVertexBuffer,Ze.indexBuffer,He,v.paint,u.transform.zoom,se,ze)}};u.uploadCommonUniforms(E,fe,J.toUnwrapped(),null,ee),oe.buildingWithoutFacade&&Te(oe.buildingWithoutFacade,fe),oe.buildingWithFacade&&(me!==fe&&u.uploadCommonUniforms(E,me,J.toUnwrapped(),null,ee),Te(oe.buildingWithFacade,me))}}function sb(x,u,f,v,S,T,E,L,B,q,G,ee,J){const re=x.context.gl,oe=x.depthModeForSublayer(1,Wr.ReadOnly,re.LEQUAL,!0),se=.1*(1-(me=G))+3*me;var me;const fe=x._showOverdrawInspector,Ne=ee,Ae=new qS;fe||Ah(Ae,x,u,f,v,oe,new _n({func:re.ALWAYS,mask:255},255,255,re.KEEP,re.KEEP,re.REPLACE),new En([re.ONE,re.ONE,re.ONE,re.ONE],a.ao.transparent,[!1,!1,!1,!0],re.MIN),vn.disabled,S,"sdf",T,E,L,B,q,se,Ne,!1);{const Te=fe?_n.disabled:new _n({func:re.EQUAL,mask:255},255,255,re.KEEP,re.DECR,re.DECR),Ze=fe?x.colorModeForRenderPass():new En([re.ONE_MINUS_DST_ALPHA,re.DST_ALPHA,re.ONE,re.ONE],a.ao.transparent,[!0,!0,!0,!0]);Ah(Ae,x,u,f,v,oe,Te,Ze,vn.disabled,S,"color",T,E,L,B,q,se,Ne,!1)}}function ib(x){return[x[0]*a.eh,x[1]*a.eh,x[2]*a.eh,0]}function iv(x,u,f,v,S,T,E,L,B){const q=v.getSource(),G=f.globeSharedBuffers;if(!G)return;let ee,J,re;if(u&&(ee=v.getTile(u)),q instanceof a.aU?(J=q.texture,re=a.dK(0,0,f.transform)):ee&&u&&(J=ee.texture,re=a.dK(u.canonical.z,u.canonical.x,f.transform)),!J||!re)return;x||(re=a.cS(a.bC(),re,[1,-1,1]));const oe=f.context,se=oe.gl,me=S.paint.get("raster-resampling")==="nearest"?se.NEAREST:se.LINEAR,fe=f.colorModeForDrapableLayerRenderPass(T),Ne=E.defines;Ne.push("GLOBE_POLES");const Ae=new Wr(se.LEQUAL,Wr.ReadWrite,f.depthRangeFor3D),Te=Float32Array.from(f.transform.expandedFarZProjMatrix),Ze=Float32Array.from(a.bk(a.dJ(new a.cD(0,0,0))));f.terrain&&f.terrain.prepareDrawTile(),oe.activeTexture.set(se.TEXTURE0),J.bind(me,se.CLAMP_TO_EDGE),oe.activeTexture.set(se.TEXTURE1),J.bind(me,se.CLAMP_TO_EDGE),"useMipmap"in J&&oe.extTextureFilterAnisotropic&&f.transform.pitch>20&&se.texParameterf(se.TEXTURE_2D,oe.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,oe.extTextureFilterAnisotropicMax);const[$e,He,ze,De]=u?G.getPoleBuffers(u.canonical.z,!1):G.getPoleBuffers(0,!0),Qe=S.paint.get("raster-elevation");let ht;x?(ht=$e,f.renderDefaultNorthPole=Qe!==0):(ht=He,f.renderDefaultSouthPole=Qe!==0);const ot=ib(E.mix),Tt=((Bt,or,wt,st,Mt,kt,Zt,yr,Pr,fr,lr,Ur,Fr)=>kE(Bt,or,wt,new Float32Array(16),new Float32Array(9),[0,0],st,[0,0],[0,0,0,0],1,{opacity:1,mix:0},kt,[0,0],yr,2,fr,lr,Ur,1,0,Fr))(Te,Ze,re,a.aj(f.transform.zoom),0,S,0,Qe,0,ot,E.offset,E.range,T),At=f.getOrCreateProgram("raster",{defines:Ne});f.uploadCommonUniforms(oe,At,null),At.draw(f,se.TRIANGLES,Ae,B,fe,L,Tt,S.id,ht,ze,De)}function OE(x){const u=x._nearZ,f=x.projection.farthestPixelDistance(x),v=f-u,S=.2*x.height,T=u+S;return[u,f,(T-S-u)/v,(T-u)/v]}function Ih(x,u,f,v){if(x)return u instanceof xl&&x instanceof x0?u.getTextureDescriptor(x,f,!0):{texture:x.texture,mix:ib(v.mix),offset:v.offset,buffer:0,tileSize:1}}var wi=a.ei([{name:"a_index",type:"Int16",components:1}]);class ab{constructor(u,f,v,S){const T={width:v[0],height:v[1],data:null},E=u.gl;this.targetColorTexture=new a.T(u,T,E.RGBA8,{useMipmap:!1}),this.backgroundColorTexture=new a.T(u,T,E.RGBA8,{useMipmap:!1}),this.context=u,this.updateParticleTexture(f,S),this.lastInvalidatedAt=0}updateParticleTexture(u,f){if(this.particleTextureDimension===f.width)return;(this.particleTexture0||this.particleTexture1||this.particleIndexBuffer||this.particleSegment)&&(this.particleTexture0.destroy(),this.particleTexture1.destroy(),this.particleIndexBuffer.destroy(),this.particleSegment.destroy());const v=this.context.gl,S=f.width*f.height;this.particleTexture0=new a.T(this.context,f,v.RGBA8,{premultiply:!1,useMipmap:!1}),this.particleTexture1=new a.T(this.context,f,v.RGBA8,{premultiply:!1,useMipmap:!1});const T=new a.ej;T.reserve(S);for(let E=0;E0){const ot=a.bj(f.canonical,B),Tt=a.el(ot);J=a.aB(new Float32Array(16),B.globeMatrix,Tt),a.aB(J,B.projMatrix,J)}const re=a.bC();re[12]+=2*S/(a.o.devicePixelRatio*B.width),re[13]+=2*T/(a.o.devicePixelRatio*B.height),a.aB(J,re,J);const oe=x.getOrCreateProgram("debug",{defines:ee}),se=u.getTileByID(f.key);x.terrain&&x.terrain.setupElevationDraw(se,oe);const me=Wr.disabled,fe=_n.disabled,Ne=x.colorModeForRenderPass(),Ae="$debug";L.activeTexture.set(q.TEXTURE0),x.emptyTexture.bind(q.LINEAR,q.CLAMP_TO_EDGE),G?se._makeGlobeTileDebugBuffers(x.context,B):se._makeDebugTileBoundsBuffers(x.context,B.projection);const Te=se._tileDebugBuffer||x.debugBuffer,Ze=se._tileDebugIndexBuffer||x.debugIndexBuffer,$e=se._tileDebugSegments||x.debugSegments;if(oe.draw(x,q.LINE_STRIP,me,fe,Ne,vn.disabled,ev(J,v.toPremultipliedRenderColor(null)),Ae,Te,Ze,$e,null,null,null,[se._globeTileDebugBorderBuffer]),E){const ot=se.latestRawTileData,Tt=Math.floor((ot&&ot.byteLength||0)/1024);let At=f.canonical.toString();f.overscaledZ!==f.canonical.z&&(At+=` => ${f.overscaledZ}`),At+=` ${se.state}`,At+=` ${Tt}kb`,function(Bt,or){Bt.initDebugOverlayCanvas();const wt=Bt.debugOverlayCanvas,st=Bt.context.gl,Mt=Bt.debugOverlayCanvas.getContext("2d");Mt.clearRect(0,0,wt.width,wt.height),Mt.shadowColor="white",Mt.shadowBlur=2,Mt.lineWidth=1.5,Mt.strokeStyle="white",Mt.textBaseline="top",Mt.font="bold 36px Open Sans, sans-serif",Mt.fillText(or,5,5),Mt.strokeText(or,5,5),Bt.debugOverlayTexture.update(wt),Bt.debugOverlayTexture.bind(st.LINEAR,st.CLAMP_TO_EDGE)}(x,At)}const He=u.getTile(f).tileSize,ze=512/Math.min(He,512)*(f.overscaledZ/B.zoom)*.5,De=se._tileDebugTextBuffer||x.debugBuffer,Qe=se._tileDebugTextIndexBuffer||x.quadTriangleIndexBuffer,ht=se._tileDebugTextSegments||x.debugSegments;oe.draw(x,q.TRIANGLES,me,fe,En.alphaBlended,vn.disabled,ev(J,a.ao.transparent.toPremultipliedRenderColor(null),ze),Ae,De,Qe,ht,null,null,null,[se._globeTileDebugTextBuffer])}function em(x,u,f,v){yt(x,0,u+f/2,x.transform.width,f,v)}function ta(x,u,f,v){yt(x,u-f/2,0,f,x.transform.height,v)}function yt(x,u,f,v,S,T){const E=x.context,L=E.gl;L.enable(L.SCISSOR_TEST),L.scissor(u*a.o.devicePixelRatio,f*a.o.devicePixelRatio,v*a.o.devicePixelRatio,S*a.o.devicePixelRatio),E.clear({color:T}),L.disable(L.SCISSOR_TEST)}const zE=a.ei([{name:"a_pos_3f",components:3,type:"Float32"}]),{members:ob}=zE;function Ld(x,u,f,v){x.emplaceBack(u,f,v)}class lb{constructor(u){this.vertexArray=new a.em,this.indices=new a.b0,Ld(this.vertexArray,-1,-1,1),Ld(this.vertexArray,1,-1,1),Ld(this.vertexArray,-1,1,1),Ld(this.vertexArray,1,1,1),Ld(this.vertexArray,-1,-1,-1),Ld(this.vertexArray,1,-1,-1),Ld(this.vertexArray,-1,1,-1),Ld(this.vertexArray,1,1,-1),this.indices.emplaceBack(5,1,3),this.indices.emplaceBack(3,7,5),this.indices.emplaceBack(6,2,0),this.indices.emplaceBack(0,4,6),this.indices.emplaceBack(2,6,7),this.indices.emplaceBack(7,3,2),this.indices.emplaceBack(5,4,0),this.indices.emplaceBack(0,1,5),this.indices.emplaceBack(0,2,3),this.indices.emplaceBack(3,1,0),this.indices.emplaceBack(7,6,4),this.indices.emplaceBack(4,5,7),this.vertexBuffer=u.createVertexBuffer(this.vertexArray,ob),this.indexBuffer=u.createIndexBuffer(this.indices),this.segment=a.bg.simpleSegment(0,0,36,12)}}function tm(x,u,f,v,S,T){const E=x.context.gl,L=u.paint.get("sky-atmosphere-color"),B=u.paint.get("sky-atmosphere-halo-color"),q=u.paint.get("sky-atmosphere-sun-intensity"),G=((ee,J,re,oe,se)=>({u_matrix_3f:ee,u_sun_direction:J,u_sun_intensity:re,u_color_tint_r:[oe.r,oe.g,oe.b,oe.a],u_color_tint_m:[se.r,se.g,se.b,se.a],u_luminance:5e-5}))(a.eo(a.dO(),v),S,q,L.toPremultipliedRenderColor(null),B.toPremultipliedRenderColor(null));E.framebufferTexture2D(E.FRAMEBUFFER,E.COLOR_ATTACHMENT0,E.TEXTURE_CUBE_MAP_POSITIVE_X+T,u.skyboxTexture,0),f.draw(x,E.TRIANGLES,Wr.disabled,_n.disabled,En.unblended,vn.frontCW,G,"skyboxCapture",u.skyboxGeometry.vertexBuffer,u.skyboxGeometry.indexBuffer,u.skyboxGeometry.segment)}const BE=a.ei([{type:"Float32",name:"a_pos",components:3},{type:"Float32",name:"a_uv",components:2}]);class Eg{constructor(u){const f=new a.ep;f.emplaceBack(-1,1,1,0,0),f.emplaceBack(1,1,1,1,0),f.emplaceBack(1,-1,1,1,1),f.emplaceBack(-1,-1,1,0,1);const v=new a.b0;v.emplaceBack(0,1,2),v.emplaceBack(2,3,0),this.vertexBuffer=u.createVertexBuffer(f,BE.members),this.indexBuffer=u.createIndexBuffer(v),this.segments=a.bg.simpleSegment(0,0,4,2)}destroy(){this.vertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy()}}const N4=a.ei([{type:"Float32",name:"a_pos_3f",components:3},{type:"Float32",name:"a_uv",components:2},{type:"Float32",name:"a_size_scale",components:1},{type:"Float32",name:"a_fade_opacity",components:1}]);class C4{constructor(){this.starsCount=16e3,this.sizeMultiplier=.15,this.sizeRange=100,this.intensityRange=200}}class $E{constructor(u){this.colorModeAlphaBlendedWriteRGB=new En([1,Md,1,Md],a.ao.transparent,[!0,!0,!0,!1]),this.colorModeWriteAlpha=new En([1,0,1,0],a.ao.transparent,[!1,!1,!1,!0]),this.params=new C4,this.updateNeeded=!0}update(u){const f=u.context;if(!this.atmosphereBuffer||this.updateNeeded){this.updateNeeded=!1,this.atmosphereBuffer=new Eg(f);const v=this.params.sizeRange,S=this.params.intensityRange,T=function(G){const ee=a.eq(30),J=[];for(let re=0;re{const ze=T.projection.name==="globe"?["PROJECTION_GLOBE_VIEW","FOG"]:["FOG"];He&&ze.push("ALPHA_PASS");const De=u.getOrCreateProgram("globeAtmosphere",{defines:ze}),Qe=((ot,Tt,At,Bt,or,wt,st,Mt,kt,Zt,yr,Pr)=>({u_frustum_tl:ot,u_frustum_tr:Tt,u_frustum_br:At,u_frustum_bl:Bt,u_horizon:or,u_transition:wt,u_fadeout_range:st,u_atmosphere_fog_color:Mt.toArray01(),u_high_color:kt.toArray01(),u_space_color:Zt.toArray01(),u_temporal_offset:yr,u_horizon_angle:Pr}))(T.frustumCorners.TL,T.frustumCorners.TR,T.frustumCorners.BR,T.frustumCorners.BL,T.frustumCorners.horizon,L,me,G,J,oe,Ne,Ze);u.uploadCommonUniforms(v,De);const ht=this.atmosphereBuffer;ht&&De.draw(u,S.TRIANGLES,E,_n.disabled,He?this.colorModeWriteAlpha:this.colorModeAlphaBlendedWriteRGB,vn.backCW,Qe,He?"atmosphere_glow_alpha":"atmosphere_glow",ht.vertexBuffer,ht.indexBuffer,ht.segments)};$e(!1),$e(!0)}drawStars(u,f){const v=a.aA(f.properties.get("star-intensity"),0,1);if(v===0)return;const S=u.context,T=S.gl,E=u.transform,L=u.getOrCreateProgram("stars"),B=a.c7([]);a.c9(B,B,-E._pitch),a.c8(B,B,-E.angle),a.c9(B,B,a.an(E._center.lat)),a.et(B,B,-a.an(E._center.lng));const q=a.cc(new Float32Array(16),B),G=a.aB([],E.starsProjMatrix,q),ee=a.eo([],q),J=a.eu([],ee),re=[0,1,0];a.dQ(re,re,J),a.c5(re,re,this.params.sizeMultiplier);const oe=[1,0,0];a.dQ(oe,oe,J),a.c5(oe,oe,this.params.sizeMultiplier);const se=(me=re,fe=oe,Ne=v,{u_matrix:Float32Array.from(G),u_up:me,u_right:fe,u_intensity_multiplier:Ne});var me,fe,Ne;u.uploadCommonUniforms(S,L),this.starsVx&&this.starsIdx&&L.draw(u,T.TRIANGLES,Wr.disabled,_n.disabled,this.colorModeAlphaBlendedWriteRGB,vn.disabled,se,"atmosphere_stars",this.starsVx,this.starsIdx,this.starsSegments)}}class cb{constructor(){this.visibleTiles=[]}updateBorders(u,f){const v=[],S=[],T=u._getRenderableCoordinates(!1,!0);for(const B of T){const q=u.getTile(B);if(!q.hasData())continue;const G=q.getBucket(f);G&&(G.isEmpty()||(v.push(B.key),S.push({bucket:G,tileID:B.canonical})))}let E=v.length!==this.visibleTiles.length;if(!E){v.sort();for(let B=0;BB.tileID.z-q.tileID.z||B.tileID.x-q.tileID.x||B.tileID.y-q.tileID.y);for(const B of S){const q=new Array,G=new Array,ee=B.bucket;for(const J of ee.featuresOnBorder)L.has(J.featureId)?G.push(J.footprintIndex):(L.add(J.featureId),q.push(J.footprintIndex));ee.updateFootprintHiddenFlags(q,a.ev,!1),ee.updateFootprintHiddenFlags(G,a.ev,!0)}}}function ub(x,u){const f=[...x],v=u.cameraWorldSizeForFog/u.worldSize,S=a.bA([]);return a.cS(S,S,[v,v,1]),a.aB(f,S,f),a.aB(f,u.worldToFogMatrix,f),f}function db(x,u,f,v,S){const T=f.material,E=v.context,{baseColorTexture:L,metallicRoughnessTexture:B}=T.pbrMetallicRoughness,{normalTexture:q,occlusionTexture:G,emissionTexture:ee}=T;function J(oe,se,me){if(oe&&(x.push(se),E.activeTexture.set(E.gl.TEXTURE0+me),oe.gfxTexture)){const{minFilter:fe,magFilter:Ne,wrapS:Ae,wrapT:Te}=oe.sampler;oe.gfxTexture.bindExtraParam(fe,Ne,Ae,Te)}}J(L,"HAS_TEXTURE_u_baseColorTexture",_o.BaseColor),J(B,"HAS_TEXTURE_u_metallicRoughnessTexture",_o.MetallicRoughness),J(q,"HAS_TEXTURE_u_normalTexture",_o.Normal),J(G,"HAS_TEXTURE_u_occlusionTexture",_o.Occlusion),J(ee,"HAS_TEXTURE_u_emissionTexture",_o.Emission),S&&(S.texture||(S.texture=new a.d$(v.context,S.image,[S.image.height,S.image.height,S.image.height],E.gl.RGBA8)),E.activeTexture.set(E.gl.TEXTURE0+_o.LUT),S.texture&&S.texture.bind(E.gl.LINEAR,E.gl.CLAMP_TO_EDGE),x.push("APPLY_LUT_ON_GPU")),f.texcoordBuffer&&(x.push("HAS_ATTRIBUTE_a_uv_2f"),u.push(f.texcoordBuffer)),f.colorBuffer&&(x.push(f.colorBuffer.itemSize===12?"HAS_ATTRIBUTE_a_color_3f":"HAS_ATTRIBUTE_a_color_4f"),u.push(f.colorBuffer)),f.normalBuffer&&(x.push("HAS_ATTRIBUTE_a_normal_3f"),u.push(f.normalBuffer)),f.pbrBuffer&&(x.push("HAS_ATTRIBUTE_a_pbr"),x.push("HAS_ATTRIBUTE_a_heightBasedEmissiveStrength"),u.push(f.pbrBuffer)),T.alphaMode!=="OPAQUE"&&T.alphaMode!=="MASK"||x.push("UNPREMULT_TEXTURE_IN_SHADER"),T.defined||x.push("DIFFUSE_SHADED");const re=v.shadowRenderer;re&&(x.push("RENDER_SHADOWS","DEPTH_TEXTURE"),re.useNormalOffset&&x.push("NORMAL_OFFSET"))}function hb(x,u,f,v,S,T){const E=x.modelOpacity,L=u.context,B=new Wr(u.context.gl.LEQUAL,x.isLightMesh?Wr.ReadOnly:Wr.ReadWrite,u.depthRangeFor3D),q=u.transform,G=x.mesh,ee=G.material,J=ee.pbrMetallicRoughness,re=u.style.fog;let oe;oe=u.transform.projection.zAxisUnit==="pixels"?[...x.nodeModelMatrix]:a.aB([],v.zScaleMatrix,x.nodeModelMatrix),a.aB(oe,v.negCameraPosMatrix,oe);const se=a.bl([],oe);a.eg(se,se);const me=f.paint.get("model-color-use-theme").constantOr("default")==="none",fe=f.paint.get("model-emissive-strength").constantOr(0),Ne=Yp(new Float32Array(x.worldViewProjection),new Float32Array(oe),new Float32Array(se),null,u,E,J.baseColorFactor,ee.emissiveFactor,J.metallicFactor,J.roughnessFactor,ee,fe,f,void 0,void 0,x.materialOverride,x.modelColor),Ae={defines:[]},Te=[],Ze=u.shadowRenderer;Ze&&(Ze.useNormalOffset=!1),db(Ae.defines,Te,G,u,me?null:f.lut);let $e=null;if(re){const De=ub(x.nodeModelMatrix,u.transform);if($e=new Float32Array(De),q.projection.name!=="globe"){const Qe=G.aabb.min,ht=G.aabb.max,[ot,Tt]=re.getOpacityForBounds(De,Qe[0],Qe[1],ht[0],ht[1]);Ae.overrideFog=ot>=Ut||Tt>=Ut}}const He=Df(u,f.paint.get("model-cutoff-fade-range"));He.shouldRenderCutoff&&Ae.defines.push("RENDER_CUTOFF");const ze=u.getOrCreateProgram("model",Ae);u.uploadCommonUniforms(L,ze,null,$e,He),u.renderPass!=="shadow"&&Ze&&Ze.setupShadowsFromMatrix(x.nodeModelMatrix,ze),ze.draw(u,L.gl.TRIANGLES,B,S,T,G.material.doubleSided?vn.disabled:vn.backCCW,Ne,f.id,G.vertexBuffer,G.indexBuffer,G.segments,f.paint,u.transform.zoom,void 0,Te)}function av(x,u){return x.style._importedAsBasemap?"basemap":u.scope}function rm(x,u,f,v,S,T,E,L,B,q){const G=x.transform,ee=!!u.isGeometryBloom&&u.isGeometryBloom;if(ee&&x.renderPass==="shadow")return;const J=G.projection.name==="globe"?a.eD(f,G):[...f];a.aB(J,J,u.globalMatrix);const re=a.aB([],v,J);if(u.meshes)for(const oe of u.meshes){const se=L.get(oe.material.name);if(se&&se.opacity<=0)continue;if(oe.material.alphaMode!=="BLEND"){E.push({mesh:oe,depth:0,modelIndex:S,worldViewProjection:re,nodeModelMatrix:J,isLightMesh:ee,materialOverride:se,modelOpacity:B,modelColor:q});continue}const me=a.af([],oe.centroid,re);!G.isOrthographic&&me[2]<=0||T.push({mesh:oe,depth:me[2],modelIndex:S,worldViewProjection:re,nodeModelMatrix:J,isLightMesh:ee,materialOverride:se,modelOpacity:B,modelColor:q})}if(u.children)for(const oe of u.children)rm(x,oe,f,v,S,T,E,L,B,q)}function Ju(x,u,f,v){const S=f.shadowRenderer;if(!S)return;const T=S.getShadowPassDepthMode(),E=S.getShadowPassColorMode(),L=S.calculateShadowPassMatrixFromMatrix(u),B=$S(L);f.getOrCreateProgram("modelDepth",{defines:f._shadowMapDebug?[]:["DEPTH_TEXTURE"]}).draw(f,f.context.gl.TRIANGLES,T,_n.disabled,E,vn.disabled,B,v.id,x.vertexBuffer,x.indexBuffer,x.segments,v.paint,f.transform.zoom,void 0,void 0)}function UE(x,u,f,v,S,T){for(const E of S){const L=Object.assign({},v);L.part=E;const B={type:"Unknown",id:u,properties:L},q={orientation:x.paint.get("model-rotation").evaluate(B,f)};T.set(E,q)}}function VE(x,u,f,v,S,T){for(const E of S){const L=Object.assign({},v);L.part=E;const B={type:"Unknown",id:u,properties:L},q={color:x.paint.get("model-color").evaluate(B,f),colorMix:x.paint.get("model-color-mix-intensity").evaluate(B,f),opacity:x.paint.get("model-opacity").evaluate(B,f),emissionStrength:x.paint.get("model-emissive-strength").evaluate(B,f)};T.set(E,q)}}function qE(x,u,f,v,S){let T=!1;for(const L of v)L.modelOpacity!==1&&(hb(L,x,u,S[L.modelIndex],_n.disabled,En.disabled),T=!0);for(const L of v)hb(L,x,u,S[L.modelIndex],L.modelOpacity!==1?x.stencilModeFor3D():_n.disabled,x.colorModeForRenderPass());T&&x.resetStencilClippingMasks();const E=En.additive;for(const L of f)hb(L,x,u,S[L.modelIndex],_n.disabled,L.isLightMesh?E:x.colorModeForRenderPass())}function HE(x,u,f){const v=u.updateZoomBasedPaintProperties(),S=function(T,E,L){let B,q,G,ee=T.terrain?T.terrain.exaggeration():0;if(T.terrain&&ee>0){const J=T.terrain,re=J.findDEMTileFor(L);re&&re.dem?B=a.eF.create(J,L,re):ee=0}if(ee===0&&(E.terrainElevationMin=0,E.terrainElevationMax=0),ee===E.validForExaggeration&&(ee===0||B&&B._demTile&&B._demTile.tileID===E.validForDEMTile.id&&B._dem._timestamp===E.validForDEMTile.timestamp))return!1;for(const J in E.instancesPerModel){const re=E.instancesPerModel[J];for(let oe=0;oeq&&(q=re.max)}const G=a.aA(v.x,T,E)-v.x,ee=a.aA(v.y,L,B)-v.y,J=a.cf(q,u.center.lat)-v.z;return u._zoomFromMercatorZ(Math.sqrt(G*G+ee*ee+J*J))}function WE(x,u,f,v,S,T,E){const L=x.context,B=x.renderPass==="shadow",q=x.shadowRenderer,G=B&&q?q.getShadowPassDepthMode():new Wr(L.gl.LEQUAL,Wr.ReadWrite,x.depthRangeFor3D),ee=x.isTileAffectedByFog(T),J=x.transform.projection.name==="globe";if(f.meshes)for(const re of f.meshes){const oe=J?[]:["MODEL_POSITION_ON_GPU"],se=[];let me,fe,Ne;const Ae=!J&&v.instancedDataArray.length>20;Ae&&oe.push("INSTANCED_ARRAYS");const Te=Df(x,u.paint.get("model-cutoff-fade-range"));if(Te.shouldRenderCutoff&&oe.push("RENDER_CUTOFF"),B&&q)me=x.getOrCreateProgram("modelDepth",{defines:oe}),fe=$S(E.shadowTileMatrix,E.shadowTileMatrix,Float32Array.from(f.globalMatrix)),Ne=q.getShadowPassColorMode();else{db(oe,se,re,x,u.paint.get("model-color-use-theme").constantOr("default")==="none"?null:u.lut),me=x.getOrCreateProgram("model",{defines:oe,overrideFog:ee});const $e=re.material,He=$e.pbrMetallicRoughness,ze=u.paint.get("model-opacity").constantOr(1),De=u.paint.get("model-emissive-strength").constantOr(0);fe=Yp(T.expandedProjMatrix,Float32Array.from(f.globalMatrix),new Float32Array(16),null,x,ze,He.baseColorFactor,$e.emissiveFactor,He.metallicFactor,He.roughnessFactor,$e,De,u,S),q&&(E.shadowUniformsInitialized?me.setShadowUniformValues(L,q.getShadowUniformValues()):(q.setupShadows(T.toUnwrapped(),me,"model-tile"),E.shadowUniformsInitialized=!0)),Ne=Te.shouldRenderCutoff||ze<1||$e.alphaMode!=="OPAQUE"?En.alphaBlended:En.unblended}x.uploadCommonUniforms(L,me,T.toUnwrapped(),null,Te);const Ze=re.material.doubleSided?vn.disabled:vn.backCCW;if(Ae)se.push(v.instancedDataBuffer),me.draw(x,L.gl.TRIANGLES,G,_n.disabled,Ne,Ze,fe,u.id,re.vertexBuffer,re.indexBuffer,re.segments,u.paint,x.transform.zoom,void 0,se,v.instancedDataArray.length);else{const $e=B?"u_instance":"u_normal_matrix";for(let He=0;HeB[1]?E:B,T[0]=f.max[0],E=a.aC(a.eG(),T,S),L=E[1]B[1]?E:B,T[1]=f.min[1],E=a.aC(a.eG(),T,S),L=E[1]B[1]?E:B;const q=a.aA(v[0],0,1),G=100*u.pixelsPerMeter*a.aA(v[1],0,1),ee=a.aA(v[2],0,1),J=a.eH(a.eG(),L,B,q),re=Math.tan(.5*u.fovX),oe=-J[2]*re;if(G===0)return J[1]<-Math.abs(oe)?ee:1;const se=(-Math.abs(oe)-J[1])/G,me=(Ne,Ae,Te)=>(1-Te)*Ne+Te*Ae,fe=a.aA(me(1,ee,se),ee,1);return me(1,fe,a.aA((u.pitch-20)/20,0,1))}class GE{}class Wf{constructor(){this._storage=new Map}getLinesFromTrianglesBuffer(u,f,v){{const ee=this._storage.get(f.id);if(ee)return ee.lastUsedFrameIdx=u,ee.buf}const S=v.gl,T=S.getBufferParameter(S.ELEMENT_ARRAY_BUFFER,S.BUFFER_SIZE),E=new ArrayBuffer(T),L=new Int16Array(E);S.getBufferSubData(S.ELEMENT_ARRAY_BUFFER,0,new Int16Array(E));const B=new a.eJ;for(let ee=0;ee30&&(v.buf.destroy(),this._storage.delete(f))}destroy(){for(const[u,f]of this._storage)f.buf.destroy(),this._storage.delete(u)}}class Ag{constructor(){this.occluderSize=30,this.depthOffset=-1e-4}}const Pg=a.ei([{type:"Float32",name:"a_pos_3f",components:3},{type:"Float32",name:"a_uv",components:2},{type:"Float32",name:"a_rainParticleData",components:4}]);class Mh{constructor(u){this.revealStart=11,this.revealRange=2}}const GS=a.ei([{type:"Float32",name:"a_pos_2f",components:2}]);class KS{destroy(){this.vignetteVx&&this.vignetteVx.destroy(),this.vignetteIdx&&this.vignetteIdx.destroy()}draw(u,f){const v=u.getOrCreateProgram("vignette");if(!this.vignetteVx||!this.vignetteIdx){const E=new a.eK,L=new a.b0;E.emplaceBack(-1,-1),E.emplaceBack(1,-1),E.emplaceBack(1,1),E.emplaceBack(-1,1),L.emplaceBack(0,1,2),L.emplaceBack(0,2,3),this.vignetteVx=u.context.createVertexBuffer(E,GS.members),this.vignetteIdx=u.context.createIndexBuffer(L)}const S=a.bg.simpleSegment(0,0,4,6);if(this.vignetteVx&&this.vignetteIdx){u.uploadCommonUniforms(u.context,v);const E={u_vignetteShape:(T={vignetteShape:[f.start,f.range,Math.pow(10,f.fadePower)],vignetteColor:[f.color.r,f.color.g,f.color.b,f.color.a*f.strength]}).vignetteShape,u_vignetteColor:T.vignetteColor};v.draw(u,u.context.gl.TRIANGLES,Wr.disabled,_n.disabled,En.alphaBlended,vn.disabled,E,"vignette",this.vignetteVx,this.vignetteIdx,S)}var T}}class ZS{constructor(){this._accumulatedOffsetX=0,this._accumulatedOffsetY=0,this._accumulatedElevation=0}update(u,f){const v=u.getFreeCameraOptions().position,S=v.toAltitude(),T=v.toLngLat(),E=a.an(T.lng),L=a.an(T.lat),B=u.pixelsPerMeter/f,q=E*a.eM,G=a.eM*Math.log(Math.tan(Math.PI/4+L/2));if(this._offsetXPrev===void 0)this._offsetXPrev=0,this._offsetYPrev=0,this._elevationPrev=0,this._accumulatedOffsetX=0,this._accumulatedOffsetY=0,this._accumulatedElevation=0;else{const ee=-this._offsetYPrev+G,J=-this._elevationPrev+S;this._accumulatedOffsetX+=(-this._offsetXPrev+q)*B,this._accumulatedOffsetY+=ee*B,this._accumulatedElevation+=J*B,this._offsetXPrev=q,this._offsetYPrev=G,this._elevationPrev=S}}getPosition(){return[this._accumulatedOffsetX,this._accumulatedOffsetY,this._accumulatedElevation]}}function fb(x,u){return[-(x[0]-Math.floor(x[0]/u)*u),-(x[1]-Math.floor(x[1]/u)*u),-(x[2]-Math.floor(x[2]/u)*u)]}function Vc(x){const u=a.eq(1323123451230),f=[];for(let v=0;v Rain"),this._vignetteParams={strength:1,start:.7,range:1,fadePower:.4,color:{r:.27,g:.27,b:.27,a:1}},this.particlesCount=16e3}update(u){const f=u.context;if(!this.particlesVx){const v=Vc(this.particlesCount),S=new a.eN,T=new a.b0;let E=0;const L=a.eq(1323123451230);for(let B=0;Bv)return;const S=ic(0,1,f.revealStart,f.revealStart+f.revealRange,v);if(!this.particlesVx||!this.particlesIdx)return;const T=structuredClone(this._params);let E=[-T.direction.x,T.direction.y,-100];a.aw(E,E);const L=structuredClone(this._vignetteParams);L.strength*=S,T.overrideStyleParameters||(T.intensity=u.style.rain.state.density,T.timeFactor=u.style.rain.state.intensity,T.color=structuredClone(u.style.rain.state.color),E=structuredClone(u.style.rain.state.direction),T.screenThinning.intensity=u.style.rain.state.centerThinning,T.dropletSizeX=u.style.rain.state.dropletSize[0],T.dropletSizeYScale=u.style.rain.state.dropletSize[1]/u.style.rain.state.dropletSize[0],T.distortionStrength=100*u.style.rain.state.distortionStrength,L.strength=1,L.color=structuredClone(u.style.rain.state.vignetteColor));const B=this.updateOnRender(u,T.timeFactor),q=u.context,G=q.gl,ee=u.transform;this.screenTexture&&this.screenTexture.size[0]===u.width&&this.screenTexture.size[1]===u.height||(this.screenTexture=new a.T(q,{width:u.width,height:u.height,data:null},G.RGBA8)),T.distortionStrength>0&&(q.activeTexture.set(G.TEXTURE0),this.screenTexture.bind(G.LINEAR,G.CLAMP_TO_EDGE),G.copyTexSubImage2D(G.TEXTURE_2D,0,0,0,0,0,u.width,u.height));const J=u.getOrCreateProgram("rainParticle");u.uploadCommonUniforms(q,J),q.activeTexture.set(G.TEXTURE0),this.screenTexture.bind(G.LINEAR,G.CLAMP_TO_EDGE);const re=[T.color.r,T.color.g,T.color.b,T.color.a],oe=(se,me)=>{const fe=fb(this._movement.getPosition(),se),Ne=T.dropletSizeX,Ae=T.dropletSizeX*T.dropletSizeYScale,Te=u.width/2,Ze=u.height/2,$e=ic(0,T.screenThinning.start,0,1,T.screenThinning.intensity),He=ic(.001,T.screenThinning.range,0,1,T.screenThinning.intensity),ze=ic(0,T.screenThinning.particleOffset,0,1,T.screenThinning.intensity),De=(Qe={modelview:B.modelviewMatrix,projection:B.projectionMatrix,time:this._accumulatedTimeFromStart,camPos:fe,velocityConeAperture:T.velocityConeAperture,velocity:T.velocity,boxSize:se,rainDropletSize:[Ne,Ae],distortionStrength:T.distortionStrength,rainDirection:E,color:re,screenSize:[ee.width,ee.height],thinningCenterPos:[Te,Ze],thinningShape:[$e,He,Math.pow(10,T.screenThinning.fadePower)],thinningAffectedRatio:T.screenThinning.affectedRatio,thinningParticleOffset:ze,shapeDirectionalPower:T.shapeDirPower,shapeNormalPower:T.shapeNormalPower,mode:me?0:1},{u_modelview:Float32Array.from(Qe.modelview),u_projection:Float32Array.from(Qe.projection),u_time:Qe.time,u_cam_pos:Qe.camPos,u_texScreen:0,u_velocityConeAperture:Qe.velocityConeAperture,u_velocity:Qe.velocity,u_boxSize:Qe.boxSize,u_rainDropletSize:Qe.rainDropletSize,u_distortionStrength:Qe.distortionStrength,u_rainDirection:Qe.rainDirection,u_color:Qe.color,u_screenSize:Qe.screenSize,u_thinningCenterPos:Qe.thinningCenterPos,u_thinningShape:Qe.thinningShape,u_thinningAffectedRatio:Qe.thinningAffectedRatio,u_thinningParticleOffset:Qe.thinningParticleOffset,u_shapeDirectionalPower:Qe.shapeDirectionalPower,u_shapeNormalPower:Qe.shapeNormalPower,u_mode:Qe.mode});var Qe;const ht=Math.round(T.intensity*this.particlesCount),ot=a.bg.simpleSegment(0,0,4*ht,2*ht);J.draw(u,G.TRIANGLES,Wr.disabled,_n.disabled,En.alphaBlended,vn.disabled,De,"rain_particles",this.particlesVx,this.particlesIdx,ot)};T.distortionStrength>0&&oe(T.boxSize,!0),oe(T.boxSize,!1),this._vignette.draw(u,L)}}const YS=a.ei([{type:"Float32",name:"a_pos_3f",components:3},{type:"Float32",name:"a_uv",components:2},{type:"Float32",name:"a_snowParticleData",components:4},{type:"Float32",name:"a_snowParticleDataHorizontalOscillation",components:2}]);class XS extends nm{constructor(u){super(2.25),this._params={overrideStyleParameters:!1,intensity:.85,timeFactor:.75,velocityConeAperture:70,velocity:40,horizontalOscillationRadius:4,horizontalOscillationRate:1.5,boxSize:2e3,billboardSize:2,shapeFadeStart:.27,shapeFadePower:.21,screenThinning:{intensity:.4,start:.15,range:1.4,fadePower:.24,affectedRatio:1,particleOffset:-.2},color:{r:1,g:1,b:1,a:1},direction:{x:-50,y:-35}},this._revealParams=new Mh("Precipitation > Snow"),this._vignetteParams={strength:.3,start:.78,range:.46,fadePower:.2,color:{r:1,g:1,b:1,a:1}},this.particlesCount=16e3}update(u){const f=u.context;if(!this.particlesVx){const v=Vc(this.particlesCount),S=new a.eO,T=new a.b0;let E=0;const L=a.eq(1323123451230);for(let B=0;BE)return;const L=ic(0,1,T.revealStart,T.revealStart+T.revealRange,E);S.strength*=L,f.overrideStyleParameters||(f.intensity=u.style.snow.state.density,f.timeFactor=u.style.snow.state.intensity,f.color=structuredClone(u.style.snow.state.color),v=structuredClone(u.style.snow.state.direction),f.screenThinning.intensity=u.style.snow.state.centerThinning,f.billboardSize=2.79*u.style.snow.state.flakeSize,S.strength=1,S.color=structuredClone(u.style.snow.state.vignetteColor));const B=this.updateOnRender(u,f.timeFactor);if(!this.particlesVx||!this.particlesIdx)return;const q=u.context,G=q.gl,ee=u.transform,J=u.getOrCreateProgram("snowParticle");u.uploadCommonUniforms(q,J),((re,oe,se)=>{const me=fb(this._movement.getPosition(),re),fe=ee.width/2,Ne=ee.height/2,Ae=ic(0,se.screenThinning.start,0,1,se.screenThinning.intensity),Te=ic(.001,se.screenThinning.range,0,1,se.screenThinning.intensity),Ze=ic(0,se.screenThinning.particleOffset,0,1,se.screenThinning.intensity),$e=(He={modelview:B.modelviewMatrix,projection:B.projectionMatrix,time:this._accumulatedTimeFromStart,camPos:me,velocityConeAperture:se.velocityConeAperture,velocity:se.velocity,horizontalOscillationRadius:se.horizontalOscillationRadius,horizontalOscillationRate:se.horizontalOscillationRate,boxSize:re,billboardSize:1*se.billboardSize,simpleShapeParameters:[se.shapeFadeStart,se.shapeFadePower],screenSize:[ee.width,ee.height],thinningCenterPos:[fe,Ne],thinningShape:[Ae,Te,Math.pow(10,se.screenThinning.fadePower)],thinningAffectedRatio:se.screenThinning.affectedRatio,thinningParticleOffset:Ze,color:[se.color.r,se.color.g,se.color.b,se.color.a],direction:v},{u_modelview:Float32Array.from(He.modelview),u_projection:Float32Array.from(He.projection),u_time:He.time,u_cam_pos:He.camPos,u_velocityConeAperture:He.velocityConeAperture,u_velocity:He.velocity,u_horizontalOscillationRadius:He.horizontalOscillationRadius,u_horizontalOscillationRate:He.horizontalOscillationRate,u_boxSize:He.boxSize,u_billboardSize:He.billboardSize,u_simpleShapeParameters:He.simpleShapeParameters,u_screenSize:He.screenSize,u_thinningCenterPos:He.thinningCenterPos,u_thinningShape:He.thinningShape,u_thinningAffectedRatio:He.thinningAffectedRatio,u_thinningParticleOffset:He.thinningParticleOffset,u_particleColor:He.color,u_direction:He.direction});var He;const ze=Math.round(se.intensity*this.particlesCount),De=a.bg.simpleSegment(0,0,4*ze,2*ze);this.particlesVx&&this.particlesIdx&&J.draw(u,G.TRIANGLES,Wr.disabled,_n.disabled,En.alphaBlended,vn.disabled,$e,"snow_particles",this.particlesVx,this.particlesIdx,De)})(f.boxSize,0,f),this._vignette.draw(u,S)}}const Gf={symbol:function(x,u,f,v,S){if(x.renderPass!=="translucent")return;const T=_n.disabled,E=x.colorModeForRenderPass(),L=f.layout.get("text-variable-anchor"),B=f.layout.get("text-size-scale-range"),q=a.aA(x.scaleFactor,B[0],B[1]);L&&function(J,re,oe,se,me,fe,Ne,Ae){const Te=re.transform,Ze=me==="map",$e=fe==="map";for(const He of J){const ze=se.getTile(He),De=ze.getBucket(oe);if(!De||!De.text||!De.text.segments.get().length)continue;const Qe=a.bK(De.textSizeData,Te.zoom,Ae),ht=Pd(He,De.getProjection(),Te),ot=Te.calculatePixelsToTileUnitsMatrix(ze),Tt=vl(ht,ze.tileID.canonical,$e,Ze,Te,De.getProjection(),ot),At=De.hasIconTextFit()&&De.hasIconData();Qe&&an(De,Ze,$e,Ne,Te,Tt,He,Math.pow(2,Te.zoom-ze.tileID.overscaledZ),Qe,At)}}(v,x,f,u,f.layout.get("text-rotation-alignment"),f.layout.get("text-pitch-alignment"),S,q);const G=f.paint.get("icon-opacity").constantOr(1)!==0,ee=f.paint.get("text-opacity").constantOr(1)!==0;f.layout.get("symbol-sort-key").constantOr(1)!==void 0&&(G||ee)?nv(x,u,f,v,T,E):(G&&nv(x,u,f,v,T,E,{onlyIcons:!0}),ee&&nv(x,u,f,v,T,E,{onlyText:!0})),u.map.showCollisionBoxes&&(Lr(x,u,f,v,f.paint.get("text-translate"),f.paint.get("text-translate-anchor"),!0),Lr(x,u,f,v,f.paint.get("icon-translate"),f.paint.get("icon-translate-anchor"),!1))},circle:function(x,u,f,v){if(x.renderPass!=="translucent")return;const S=f.paint.get("circle-opacity"),T=f.paint.get("circle-stroke-width"),E=f.paint.get("circle-stroke-opacity"),L=f.layout.get("circle-sort-key").constantOr(1)!==void 0,B=f.paint.get("circle-emissive-strength");if(S.constantOr(1)===0&&(T.constantOr(1)===0||E.constantOr(1)===0))return;const q=x.context,G=q.gl,ee=x.transform,J=!(!x.terrain||!x.terrain.enabled),re=f.layout.get("circle-elevation-reference"),oe=x.depthModeForSublayer(0,Wr.ReadOnly),se=new Wr(x.context.gl.LEQUAL,Wr.ReadOnly,x.depthRangeFor3D),me=re==="none"||J?oe:se,fe=_n.disabled,Ne=x.colorModeForDrapableLayerRenderPass(B),Ae=ee.projection.name==="globe",Te=[a.aF(ee.center.lng),a.aJ(ee.center.lat)],Ze=[];for(let He=0;HeHe.sortKey-ze.sortKey);const $e={useDepthForOcclusion:ee.depthOcclusionForSymbolsAndCircles};for(const He of Ze){const{programConfiguration:ze,program:De,layoutVertexBuffer:Qe,dynamicBuffers:ht,indexBuffer:ot,uniformValues:Tt,tile:At}=He.state,Bt=He.segments;x.terrain&&x.terrain.setupElevationDraw(At,De,$e),x.uploadCommonUniforms(q,De,At.tileID.toUnwrapped()),De.draw(x,G.TRIANGLES,me,fe,Ne,vn.disabled,Tt,f.id,Qe,ot,Bt,f.paint,ee.zoom,ze,ht)}},heatmap:function(x,u,f,v){if(f.paint.get("heatmap-opacity")!==0)if(x.renderPass==="offscreen"){const S=x.context,T=S.gl,E=_n.disabled,L=new En([T.ONE,T.ONE,T.ONE,T.ONE],a.ao.transparent,[!0,!0,!0,!0]);(function(re,oe,se,me){const fe=re.gl,Ne=oe.width*me,Ae=oe.height*me;re.activeTexture.set(fe.TEXTURE1),re.viewport.set([0,0,Ne,Ae]);let Te=se.heatmapFbo;if(!Te||Te&&(Te.width!==Ne||Te.height!==Ae)){Te&&Te.destroy();const Ze=fe.createTexture();fe.bindTexture(fe.TEXTURE_2D,Ze),fe.texParameteri(fe.TEXTURE_2D,fe.TEXTURE_WRAP_S,fe.CLAMP_TO_EDGE),fe.texParameteri(fe.TEXTURE_2D,fe.TEXTURE_WRAP_T,fe.CLAMP_TO_EDGE),fe.texParameteri(fe.TEXTURE_2D,fe.TEXTURE_MIN_FILTER,fe.LINEAR),fe.texParameteri(fe.TEXTURE_2D,fe.TEXTURE_MAG_FILTER,fe.LINEAR),Te=se.heatmapFbo=re.createFramebuffer(Ne,Ae,1,null),function($e,He,ze,De,Qe,ht){const ot=$e.gl;ot.texImage2D(ot.TEXTURE_2D,0,$e.extRenderToTextureHalfFloat?ot.RGBA16F:ot.RGBA,Qe,ht,0,ot.RGBA,$e.extRenderToTextureHalfFloat?ot.HALF_FLOAT:ot.UNSIGNED_BYTE,null),De.colorAttachment0.set(ze)}(re,0,Ze,Te,Ne,Ae)}else fe.bindTexture(fe.TEXTURE_2D,Te.colorAttachment0.get()),re.bindFramebuffer.set(Te.framebuffer)})(S,x,f,x.transform.projection.name==="globe"?.5:.25),S.clear({color:a.ao.transparent});const B=x.transform,q=B.projection.name==="globe",G=q?["PROJECTION_GLOBE_VIEW"]:[],ee=q?vn.frontCCW:vn.disabled,J=[a.aF(B.center.lng),a.aJ(B.center.lat)];for(let re=0;re({u_image:0,u_color_ramp:1,u_opacity:ee.paint.get("heatmap-opacity")}))(0,T),T.id,S.viewportBuffer,S.quadTriangleIndexBuffer,S.viewportSegments,T.paint,S.transform.zoom)}(x,f))},line:function(x,u,f,v){if(x.renderPass!=="translucent")return;const S=f.paint.get("line-opacity"),T=f.paint.get("line-width");if(S.constantOr(1)===0||T.constantOr(1)===0)return;const E=f.paint.get("line-emissive-strength").isConstant(),L=f.paint.get("line-emissive-strength").constantOr(0),B=f.paint.get("line-occlusion-opacity"),q=f.layout.get("line-elevation-reference"),G=f.layout.get("line-width-unit")==="meters",ee=q==="sea",J=!(!x.terrain||!x.terrain.enabled),re=x.context,oe=re.gl;if(f.hasElevatedBuckets&&x.transform.projection.name==="globe")return;const se=f.layout.get("line-cross-slope"),me=se!==void 0,fe=se<1,Ne=x.colorModeForDrapableLayerRenderPass(E?L:null),Ae=x.terrain&&x.terrain.renderingToTexture,Te=Ae?1:a.o.devicePixelRatio,Ze=f.paint.get("line-dasharray"),$e=Ze.constantOr(1),He=f.layout.get("line-cap"),ze=Ze.constantOr(null),De=He.constantOr(null),Qe=f.paint.get("line-pattern"),ht=Qe.constantOr(1),ot=f.paint.get("line-pattern-cross-fade"),Tt=Qe.constantOr(null),At=f.paint.get("line-opacity").constantOr(1);let Bt=!ht&&At!==1||x.depthOcclusion&&B>0&&B<1;const or=f.paint.get("line-gradient"),wt=ht?"linePattern":"line",st=a.e2(f);let Mt;if(Ae&&x.terrain&&x.terrain.clipOrMaskOverlapStencilType()&&(Bt=!1),B!==0&&x.depthOcclusion){const Pr=f.paint._values["line-opacity"];Pr&&Pr.value&&Pr.value.kind==="constant"?Mt=Pr.value:a.w(`Occlusion opacity for layer ${f.id} is supported only when line-opacity isn't data-driven.`)}T.value.kind!=="constant"&&T.value.isLineProgressConstant===!1&&st.push("VARIABLE_LINE_WIDTH"),Ae&&(x.emissiveMode!=="dual-source-blending"||E?x.emissiveMode==="mrt-fallback"&&st.push("USE_MRT1"):st.push("DUAL_SOURCE_BLENDING"));const kt=(Pr,fr,lr,Ur,Fr,Tr)=>{for(const Mr of Pr){const tn=u.getTile(Mr);if(ht&&!tn.patternsLoaded())continue;const Cn=tn.getBucket(f);if(!Cn||Cn.elevationType!=="none"&&!Fr||Cn.elevationType==="none"&&Fr)continue;x.prepareDrawTile();const as=[...fr],Is=x.shadowRenderer,qr=Cn.elevationType==="road"&&!!Is&&Is.enabled;let Cs=[0,0,0];if(qr){const Pn=x.style.directionalLight,Ti=x.style.ambientLight;Pn&&Ti&&(Cs=kh(x.style,Pn,Ti)),as.push("RENDER_SHADOWS","DEPTH_TEXTURE","NORMAL_OFFSET")}const Sn=Cn.programConfigurations.get(f.id);let Ds=!1;if(Tt&&tn.imageAtlas){const Pn=a.e3.from(Tt),Ti=Pn.getPrimary().scaleSelf(Te).toString(),ua=tn.imageAtlas.patternPositions.get(Ti),Wi=Pn.getSecondary(),ci=Wi?tn.imageAtlas.patternPositions.get(Wi.scaleSelf(Te).toString()):null;Ds=!!ua&&!!ci,ua&&Sn.setConstantPatternPositions(ua,ci)}ot>0&&(Ds||Sn.getPatternTransitionVertexBuffer("line-pattern"))&&as.push("LINE_PATTERN_TRANSITION");const Ys=x.isTileAffectedByFog(Mr),Vs=x.getOrCreateProgram(wt,{config:Sn,defines:as,overrideFog:Ys});if(!ht&&ze&&De&&tn.lineAtlas){const Pn=tn.lineAtlas.getDash(ze,De);Pn&&Sn.setConstantPatternPositions(Pn)}qr&&Is.setupShadows(tn.tileID.toUnwrapped(),Vs,"vector-tile");let[ws,An]=f.paint.get("line-trim-offset");(De==="round"||De==="square")&&ws!==An&&(ws===0&&(ws-=1),An===1&&(An+=1));const Rs=Ae?Mr.projMatrix:null,Qi=G?1/Cn.tileToMeter/a.ay(tn,1,x.transform.zoom):1,Li=G?1/Cn.tileToMeter/a.ay(tn,1,Math.floor(x.transform.zoom)):1,Ls=ht?a.e4(x,tn,f,Rs,Te,Qi,Li,[ws,An],Cs,ot):a.e5(x,tn,f,Rs,Cn.lineClipsArray.length,Te,Qi,Li,[ws,An],Cs);if(or){const Pn=Cn.gradients[f.id];let Ti=Pn.texture;if(f.gradientVersion!==Pn.version){let ua=256;if(f.stepInterpolant){const Wi=u.getSource().maxzoom,ci=Mr.canonical.z===Wi?Math.ceil(1<{Mt!=null&&(Mt.value=At*B),Vs.draw(x,oe.TRIANGLES,lr,Pn,Ne,vn.disabled,Ls,f.id,Cn.layoutVertexBuffer,Cn.indexBuffer,Cn.segments,f.paint,x.transform.zoom,Sn,[Cn.layoutVertexBuffer2,Cn.patternVertexBuffer,Cn.zOffsetVertexBuffer]),Mt!=null&&(Mt.value=At)};if(Bt&&!Fr){const Pn=x.stencilModeForClipping(Mr).ref;Pn===0&&Ae&&re.clear({stencil:0});const Ti={func:oe.EQUAL,mask:255};Ls.u_alpha_discard_threshold=.8,ms(new _n(Ti,Pn,255,oe.KEEP,oe.KEEP,oe.INVERT)),Ls.u_alpha_discard_threshold=0,ms(new _n(Ti,Pn,255,oe.KEEP,oe.KEEP,oe.KEEP))}else Ls.u_alpha_discard_threshold=Bt&&Fr&&Tr?.8:0,ms(Fr?Ur:x.stencilModeForClipping(Mr))}};let Zt=x.depthModeForSublayer(0,Wr.ReadOnly);const yr=new Wr(x.depthOcclusion?oe.GREATER:oe.LEQUAL,Wr.ReadOnly,x.depthRangeFor3D);if(f.hasNonElevatedBuckets){const Pr=!Ae&&x.terrain;B!==0&&Pr?a.w(`Occlusion opacity for layer ${f.id} is supported on terrain only if the layer has line-z-offset enabled.`):Pr?a.w(`Cannot render non-elevated lines in immediate mode when terrain is enabled. Layer: ${f.id}.`):kt(v,st,Zt,_n.disabled,!1,!0)}if(f.hasElevatedBuckets){q==="hd-road-markup"?J||(Zt=yr,st.push("ELEVATED_ROADS")):(st.push("ELEVATED"),Zt=yr,me&&st.push(fe?"CROSS_SLOPE_HORIZONTAL":"CROSS_SLOPE_VERTICAL"),ee&&st.push("ELEVATION_REFERENCE_SEA"));const Pr=Bt?x.stencilModeFor3D():_n.disabled;x.forceTerrainMode=!0,kt(v,st,Zt,Pr,!0,!0),Bt&&kt(v,st,Zt,Pr,!0,!1),x.forceTerrainMode=!1}Bt&&(x.resetStencilClippingMasks(),Ae&&re.clear({stencil:0})),B===0||x.depthOcclusion||Ae||x.layersWithOcclusionOpacity.push(x.currentLayer)},fill:function(x,u,f,v){const S=f.paint.get("fill-color"),T=f.paint.get("fill-opacity");if(T.constantOr(1)===0)return;const E=f.paint.get("fill-emissive-strength"),L=x.colorModeForDrapableLayerRenderPass(E),B=f.paint.get("fill-pattern"),q=x.opaquePassEnabledForLayer()&&!B.constantOr(1)&&S.constantOr(a.ao.transparent).a===1&&T.constantOr(0)===1?"opaque":"translucent";let G="none";f.layout.get("fill-elevation-reference")!=="none"?G="road":f.paint.get("fill-z-offset").constantOr(1)!==0&&(G="offset");const ee=!(!x.terrain||!x.terrain.enabled),J={painter:x,sourceCache:u,layer:f,coords:v,colorMode:L,elevationType:G,terrainEnabled:ee,pass:q};if(x.renderPass==="shadow")return void(x.shadowRenderer&&G==="road"&&!ee&&function(oe){const{painter:se,sourceCache:me,layer:fe,coords:Ne}=oe,Ae=se.context.gl,Te=oe.painter.shadowRenderer;for(const Ze of Ne){const $e=me.getTile(Ze),He=$e.getBucket(fe);if(!He)continue;const ze=He.elevatedStructures;if(!ze||!ze.shadowCasterSegments||ze.shadowCasterSegments.segments[0].primitiveLength===0)continue;se.prepareDrawTile();const De=He.bufferData.programConfigurations.get(fe.id),Qe=se.isTileAffectedByFog(Ze),ht=se.getOrCreateProgram("elevatedStructuresDepth",{config:De,overrideFog:Qe}),ot=Te.calculateShadowPassMatrixFromTile($e.tileID.toUnwrapped());se.uploadCommonUniforms(se.context,ht,Ze.toUnwrapped());const Tt={u_matrix:ot,u_depth_bias:0};ht.draw(se,Ae.TRIANGLES,Te.getShadowPassDepthMode(),_n.disabled,Te.getShadowPassColorMode(),vn.disabled,Tt,fe.id,ze.vertexBuffer,ze.indexBuffer,ze.shadowCasterSegments,fe.paint,se.transform.zoom,De)}}(J));const re=x.emissiveMode==="mrt-fallback";if(G!=="offset"){if(rb(J,!1,re),G==="road"){const oe=!ee&&x.renderPass==="translucent";oe&&tb(x,u,f,v,"geometry"),rb(J,!0,re,_n.disabled),oe&&function(se){const{painter:me,sourceCache:fe,layer:Ne,coords:Ae,colorMode:Te}=se,Ze=me.context.gl,$e=se.painter.shadowRenderer,He=!!$e&&$e.enabled,ze=new Wr(me.context.gl.LEQUAL,Wr.ReadOnly,me.depthRangeFor3D);let De=[0,0,0];if(He){const ht=me.style.directionalLight,ot=me.style.ambientLight;ht&&ot&&(De=kh(me.style,ht,ot))}const Qe=ht=>{for(const ot of Ae){const Tt=fe.getTile(ot),At=Tt.getBucket(Ne);if(!At)continue;const Bt=At.elevatedStructures;if(!Bt)continue;let or,wt;if(ht?(or=Bt.renderableBridgeSegments,wt=Bt.bridgeProgramConfigurations.get(Ne.id)):(or=Bt.renderableTunnelSegments,wt=Bt.tunnelProgramConfigurations.get(Ne.id)),!or||or.segments[0].primitiveLength===0)continue;wt.updatePaintBuffers(),me.prepareDrawTile();const st=me.isTileAffectedByFog(ot),Mt=[];He&&Mt.push("RENDER_SHADOWS","DEPTH_TEXTURE","NORMAL_OFFSET");const kt=me.getOrCreateProgram("elevatedStructures",{config:wt,overrideFog:st,defines:Mt}),Zt=me.translatePosMatrix(ot.projMatrix,Tt,Ne.paint.get("fill-translate"),Ne.paint.get("fill-translate-anchor"));He&&$e.setupShadows(Tt.tileID.toUnwrapped(),kt,"vector-tile");const yr=Uf(Zt,De);me.uploadCommonUniforms(me.context,kt,ot.toUnwrapped()),kt.draw(me,Ze.TRIANGLES,ze,_n.disabled,Te,vn.backCCW,yr,Ne.id,Bt.vertexBuffer,Bt.indexBuffer,or,Ne.paint,me.transform.zoom,wt,[Bt.vertexBufferNormal])}};Qe(!0),Qe(!1)}(J)}}else rb(J,!1,re,x.stencilModeFor3D())},"fill-extrusion":function(x,u,f,v){const S=f.paint.get("fill-extrusion-opacity"),T=x.context,E=T.gl,L=x.terrain,B=L&&L.renderingToTexture;if(S===0)return;const q=x.emissiveMode==="mrt-fallback",G=x.conflationActive&&x.style.isLayerClipped(f,u.getSource()),ee=x.style.order.indexOf(f.fqid);if(G&&function(J,re,oe,se,me){for(const fe of se){const Ne=re.getTile(fe).getBucket(oe);Ne&&(Ne.updateReplacement(fe,J.replacementSource,me),Ne.uploadCentroid(J.context))}}(x,u,f,v,ee),L||G)for(const J of v){const re=u.getTile(J).getBucket(f);re&&S4(x.context,u,J,re,f,L,G)}if(x.renderPass==="shadow"&&x.shadowRenderer){const J=x.shadowRenderer;if(L&&S<.65&&f._transitionablePaint._values["fill-extrusion-opacity"].value.expression instanceof a.ad)return;const re=J.getShadowPassDepthMode(),oe=J.getShadowPassColorMode();nb(x,u,f,v,re,_n.disabled,oe,G)}else if(x.renderPass==="translucent"){const J=!f.paint.get("fill-extrusion-pattern").constantOr(1),re=f.paint.get("fill-extrusion-color").constantOr(a.ao.white);if(!B&&re.a!==0){const oe=new Wr(x.context.gl.LEQUAL,Wr.ReadWrite,x.depthRangeFor3D);S===1&&J?nb(x,u,f,v,oe,_n.disabled,En.unblended,G):(nb(x,u,f,v,oe,_n.disabled,En.disabled,G),nb(x,u,f,v,oe,x.stencilModeFor3D(),x.colorModeForRenderPass(),G),x.resetStencilClippingMasks())}if(x.style.enable3dLights()&&J&&(!L&&x.transform.projection.name!=="globe"||B)){const oe=f.paint.get("fill-extrusion-opacity"),se=f.paint.get("fill-extrusion-ambient-occlusion-intensity"),me=f.paint.get("fill-extrusion-ambient-occlusion-ground-radius"),fe=f.paint.get("fill-extrusion-flood-light-intensity"),Ne=f.paint.get("fill-extrusion-flood-light-color-use-theme").constantOr("default")==="none",Ae=f.paint.get("fill-extrusion-flood-light-color").toNonPremultipliedRenderColor(Ne?null:f.lut).toArray01().slice(0,3),Te=se>0&&me>0,Ze=fe>0,$e=(De,Qe,ht)=>(1-ht)*De+ht*Qe,He=new qS;He.translate=f.paint.get("fill-extrusion-translate"),He.translateAnchor=f.paint.get("fill-extrusion-translate-anchor"),He.edgeRadius=f.layout.get("fill-extrusion-edge-radius"),He.cutoffFadeRange=f.paint.get("fill-extrusion-cutoff-fade-range");const ze=De=>{const Qe=x.depthModeForSublayer(1,Wr.ReadOnly,E.LEQUAL,!0),ht=f.paint.get(De?"fill-extrusion-ambient-occlusion-ground-attenuation":"fill-extrusion-flood-light-ground-attenuation"),ot=$e(.1,3,ht),Tt=x._showOverdrawInspector;if(!Tt){const At=new _n({func:E.ALWAYS,mask:255},255,255,E.KEEP,E.KEEP,E.REPLACE),Bt=new En([E.ONE,E.ONE,E.ONE,E.ONE],a.ao.transparent,[!1,!1,!1,!0],E.MIN);Ah(He,x,u,f,v,Qe,At,Bt,vn.disabled,De,"sdf",oe,se,me,fe,Ae,ot,G,!1)}{const At=Tt?_n.disabled:new _n({func:E.EQUAL,mask:255},255,255,E.KEEP,E.DECR,E.DECR),Bt=Tt?x.colorModeForRenderPass():new En([E.ONE_MINUS_DST_ALPHA,E.DST_ALPHA,E.ONE,E.ONE],a.ao.transparent,[!0,!0,!0,!0]);Ah(He,x,u,f,v,Qe,At,Bt,vn.disabled,De,"color",oe,se,me,fe,Ae,ot,G,!1)}};if(B){const De=()=>{const ht=L.drapeBufferSize[0],ot=L.drapeBufferSize[1];let Tt=L.framebufferCopyTexture;return Tt&&(!Tt||Tt.size[0]===ht&&Tt.size[1]===ot)||(Tt&&Tt.destroy(),Tt=L.framebufferCopyTexture=new a.T(T,new a.q({width:ht,height:ot}),E.RGBA8)),Tt.bind(E.LINEAR,E.CLAMP_TO_EDGE),E.copyTexSubImage2D(E.TEXTURE_2D,0,0,0,0,0,ht,ot),Tt},Qe=(ht,ot,Tt)=>{const At=x.depthModeForSublayer(1,Wr.ReadOnly,E.LEQUAL,!1),Bt=f.paint.get(ht?"fill-extrusion-ambient-occlusion-ground-attenuation":"fill-extrusion-flood-light-ground-attenuation"),or=$e(.1,3,Bt);{const wt=new En([E.ONE,E.ONE,E.ONE,E.ONE],a.ao.transparent,[!1,!1,!1,!0]);Ah(He,x,u,f,v,At,_n.disabled,wt,vn.disabled,ht,"clear",oe,se,me,fe,Ae,or,G,ot)}{const wt=new _n({func:E.ALWAYS,mask:255},255,255,E.KEEP,E.KEEP,E.REPLACE),st=new En([E.ONE,E.ONE,E.ONE,E.ONE],a.ao.transparent,[!1,!1,!1,!0],E.MIN);Ah(He,x,u,f,v,At,wt,st,vn.disabled,ht,"sdf",oe,se,me,fe,Ae,or,G,ot)}q&&!ht&&(Tt=De());{const wt=ht?E.ZERO:E.ONE_MINUS_DST_ALPHA,st=new _n({func:E.EQUAL,mask:255},255,255,E.KEEP,E.DECR,E.DECR),Mt=new En([wt,E.DST_ALPHA,E.ONE_MINUS_DST_ALPHA,E.ZERO],a.ao.transparent,[!0,!0,!0,!0]);Ah(He,x,u,f,v,At,st,Mt,vn.disabled,ht,"color",oe,se,me,fe,Ae,or,G,ot)}if(!q||ht){const wt=new En([E.ONE,E.ONE,E.ONE,ht?E.ZERO:E.ONE],a.ao.transparent,[!1,!1,!1,!0],ht?E.FUNC_ADD:E.MAX);Ah(He,x,u,f,v,At,_n.disabled,wt,vn.disabled,ht,"clear",oe,se,me,fe,Ae,or,G,ot,Tt)}else{E.drawBuffers([E.NONE,E.COLOR_ATTACHMENT1]);const wt=new _n({func:E.EQUAL,mask:255},254,255,E.KEEP,E.DECR,E.DECR),st=new En([E.ONE,E.ONE,E.ONE,E.ONE],a.ao.transparent,[!0,!1,!1,!1],E.MAX);Ah(He,x,u,f,v,At,wt,st,vn.disabled,ht,"emissive",oe,se,me,fe,Ae,or,G,ot,Tt),E.drawBuffers([E.COLOR_ATTACHMENT0])}};if(Te||Ze){let ht;x.prepareDrawTile(),q&&!Te||(ht=De()),Te&&Qe(!0,!1,ht),Ze&&Qe(!1,!0,ht)}}else Te&&ze(!0),Ze&&ze(!1),(Te||Ze)&&x.resetStencilClippingMasks()}}},building:function(x,u,f,v){x.currentLayer0&&T>0,q=!0;const G=f.paint.get("building-vertical-scale");if(G<=0)return;x.shadowRenderer||(q=!1);const ee=x.conflationActive&&x.style.isLayerClipped(f,u.getSource()),J=x.style.order.indexOf(f.fqid);if(function(re,oe,se,me,fe,Ne){for(const Ae of Ne){const Te=oe.getTile(Ae).getBucket(se);Te&&(fe&&Te.updateReplacement(Ae,re.replacementSource,me),Te.uploadUpdatedIndexBuffer(re.context))}}(x,u,f,J,ee,v),function(re,oe,se,me){for(const fe of me){const Ne=oe.getTile(fe).getBucket(se);Ne&&Ne.needsEvaluation()&&Ne.uploadUpdatedColorBuffer(re.context)}}(x,u,f,v),f.resetLayerRenderingStats(x),x.shadowRenderer&&(x.shadowRenderer.useNormalOffset=!0),x.renderPass==="shadow"&&x.shadowRenderer){const re=x.shadowRenderer,oe=[],se=re.getShadowPassDepthMode();sv({painter:x,source:u,layer:f,coords:v,defines:oe,blendMode:re.getShadowPassColorMode(),depthMode:se,opacity:L,verticalScale:G,facadeEmissiveChance:0,facadeAOIntensity:0,floodLightIntensity:0,floodLightColor:[0,0,0]})}else if(x.renderPass==="translucent"){let re=["HAS_ATTRIBUTE_a_part_color_emissive","LIGHTING_3D_MODE"];q&&(re=re.concat("RENDER_SHADOWS","DEPTH_TEXTURE")),x.shadowRenderer&&x.shadowRenderer.useNormalOffset&&(re=re.concat("NORMAL_OFFSET"));const oe=f.paint.get("building-facade-emissive-chance"),se=f.paint.get("building-ambient-occlusion-intensity"),me=f.paint.get("building-flood-light-intensity"),fe=f.paint.get("building-flood-light-color-use-theme").constantOr("default")==="none",Ne=f.paint.get("building-flood-light-color").toNonPremultipliedRenderColor(fe?null:f.lut).toArray01().slice(0,3),Ae=f.paint.get("building-flood-light-ground-attenuation"),Te=me>0,Ze=new Wr(x.context.gl.LEQUAL,Wr.ReadWrite,x.depthRangeFor3D);L<1&&sv({painter:x,source:u,layer:f,coords:v,defines:re,blendMode:En.disabled,depthMode:Ze,opacity:L,verticalScale:G,facadeEmissiveChance:oe,facadeAOIntensity:se,floodLightIntensity:me,floodLightColor:Ne,depthOnly:!0});const $e=x.colorModeForRenderPass();sv({painter:x,source:u,layer:f,coords:v,defines:re,blendMode:$e,depthMode:Ze,opacity:L,verticalScale:G,facadeEmissiveChance:oe,facadeAOIntensity:se,floodLightIntensity:me,floodLightColor:Ne}),B&&sb(x,u,f,v,!0,L,S,T,me,Ne,E,ee),Te&&sb(x,u,f,v,!1,L,S,T,me,Ne,Ae,ee)}else if(x.renderPass==="light-beam"){const re=["HAS_ATTRIBUTE_a_part_color_emissive","HAS_ATTRIBUTE_a_bloom_attenuation"],oe=new Wr(x.context.gl.LEQUAL,Wr.ReadOnly,x.depthRangeFor3D);sv({painter:x,source:u,layer:f,coords:v,defines:re,blendMode:En.alphaBlended,depthMode:oe,opacity:L,verticalScale:G,facadeEmissiveChance:0,facadeAOIntensity:0,floodLightIntensity:0,floodLightColor:[0,0,0]})}x.shadowRenderer&&(x.shadowRenderer.useNormalOffset=!1),x.resetStencilClippingMasks()},hillshade:function(x,u,f,v){if(x.renderPass!=="offscreen"&&x.renderPass!=="translucent"||x.style.disableElevatedTerrain)return;const S=x.context,T=x.terrain&&x.terrain.renderingToTexture,[E,L]=x.renderPass!=="translucent"||T?[{},v]:x.stencilConfigForOverlap(v);for(const B of L){const q=u.getTile(B);if(q.needsHillshadePrepare&&x.renderPass==="offscreen")p4(x,q,f);else if(x.renderPass==="translucent"){const G=x.depthModeForSublayer(0,Wr.ReadOnly),ee=f.paint.get("hillshade-emissive-strength"),J=x.colorModeForDrapableLayerRenderPass(ee),re=T&&x.terrain?x.terrain.stencilModeForRTTOverlap(B):E[B.overscaledZ];f4(x,B,q,f,G,re,J)}}S.viewport.set([0,0,x.width,x.height]),x.resetStencilClippingMasks()},raster:function(x,u,f,v,S,T){if(x.renderPass!=="translucent"||f.paint.get("raster-opacity")===0)return;const E=x.transform.projection.name==="globe",L=f.paint.get("raster-elevation")!==0,B=L&&E;if(x.renderElevatedRasterBackface&&!B)return;const q=x.context,G=q.gl,ee=u.getSource(),J=function($e,He,ze,De,Qe){const ht=He.paint.get("raster-color"),ot=$e.type==="raster-array",Tt=[],At=He.paint.get("raster-resampling"),Bt=He.paint.get("raster-color-mix");let or=He.paint.get("raster-color-range");const wt=[Bt[0],Bt[1],Bt[2],0],st=Bt[3];let Mt=At==="nearest"?De.NEAREST:De.LINEAR;if(ot&&(Tt.push("RASTER_ARRAY"),ht||Tt.push("RASTER_COLOR"),At==="linear"&&Tt.push("RASTER_ARRAY_LINEAR"),Mt=De.NEAREST,!or&&$e.rasterLayers)){const kt=$e.rasterLayers.find(({id:Zt})=>Zt===He.sourceLayer);kt&&kt.fields&&kt.fields.range&&(or=kt.fields.range)}if(or=or||[0,1],ht){Tt.push("RASTER_COLOR"),ze.activeTexture.set(De.TEXTURE2),He.updateColorRamp(or);let kt=He.colorRampTexture;kt||(kt=He.colorRampTexture=new a.T(ze,He.colorRamp,De.RGBA8)),kt.bind(De.LINEAR,De.CLAMP_TO_EDGE)}return Qe&&Tt.push("USE_MRT1"),{mix:wt,range:or,offset:st,defines:Tt,resampling:Mt}}(ee,f,q,G,x.terrain&&x.terrain.renderingToTexture&&x.emissiveMode==="mrt-fallback");if(ee instanceof a.aU&&!v.length&&!E)return;const re=f.paint.get("raster-emissive-strength"),oe=x.colorModeForDrapableLayerRenderPass(re),se=x.terrain&&x.terrain.renderingToTexture,me=!x.options.moving,fe=f.paint.get("raster-resampling")==="nearest"?G.NEAREST:G.LINEAR;if(ee instanceof a.aU&&!v.length&&(ee.onNorthPole||ee.onSouthPole)){const $e=L?x.stencilModeFor3D():_n.disabled;return void iv(!!ee.onNorthPole,null,x,u,f,re,J,vn.disabled,$e)}if(!v.length)return;const[Ne,Ae]=ee instanceof a.aU||se?[{},v]:x.stencilConfigForOverlap(v),Te=Ae[Ae.length-1].overscaledZ;B&&J.defines.push("PROJECTION_GLOBE_VIEW"),L&&J.defines.push("RENDER_CUTOFF");const Ze=($e,He,ze)=>{for(const De of $e){const Qe=De.toUnwrapped(),ht=u.getTile(De);if(se&&(!ht||!ht.hasData()))continue;q.activeTexture.set(G.TEXTURE0);const ot=Ih(ht,ee,f,J);if(!ot||!ot.texture)continue;const{texture:Tt,mix:At,offset:Bt,tileSize:or,buffer:wt}=ot;let st,Mt;se?(st=Wr.disabled,Mt=De.projMatrix):L?(st=new Wr(G.LEQUAL,Wr.ReadWrite,x.depthRangeFor3D),Mt=E?Float32Array.from(x.transform.expandedFarZProjMatrix):x.transform.calculateProjMatrix(Qe,me)):(st=x.depthModeForSublayer(De.overscaledZ-Te,f.paint.get("raster-opacity")===1?Wr.ReadWrite:Wr.ReadOnly,G.LESS),Mt=x.transform.calculateProjMatrix(Qe,me));const kt=x.terrain&&se?x.terrain.stencilModeForRTTOverlap(De):Ne[De.overscaledZ],Zt=T?0:f.paint.get("raster-fade-duration");ht.registerFadeDuration(Zt);const yr=u.findLoadedParent(De,0),Pr=Jx(ht,yr,u,x.transform,Zt);let fr,lr;!Pr.isFading&&ht.refreshedUponExpiration&&(ht.refreshedUponExpiration=!1),x.terrain&&x.terrain.prepareDrawTile(),q.activeTexture.set(G.TEXTURE0),Tt.bind(fe,G.CLAMP_TO_EDGE),q.activeTexture.set(G.TEXTURE1),yr?(yr.texture&&yr.texture.bind(fe,G.CLAMP_TO_EDGE),fr=Math.pow(2,yr.tileID.overscaledZ-ht.tileID.overscaledZ),lr=[ht.tileID.canonical.x*fr%1,ht.tileID.canonical.y*fr%1]):Tt.bind(fe,G.CLAMP_TO_EDGE),"useMipmap"in Tt&&q.extTextureFilterAnisotropic&&x.transform.pitch>20&&G.texParameterf(G.TEXTURE_2D,q.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,q.extTextureFilterAnisotropicMax);const Ur=x.transform;let Fr;const Tr=L?OE(Ur):[0,0,0,0];let Mr,tn,Cn,as,Is,qr=0;if(B&&ee instanceof a.aU&&ee.coordinates.length>3)Mr=Float32Array.from(a.bk(a.dJ(new a.cD(0,0,0)))),tn=Float32Array.from(Ur.globeMatrix),Cn=Float32Array.from(a.dF(Ur)),as=[a.aF(Ur.center.lng),a.aJ(Ur.center.lat)],Fr=ee.elevatedGlobePerspectiveTransform,Is=ee.elevatedGlobeGridMatrix||new Float32Array(9);else if(B){const Ys=a.dG(De.canonical);qr=a.dH(Ys.getCenter().lat),Mr=Float32Array.from(a.bk(a.dJ(De.canonical))),tn=Float32Array.from(Ur.globeMatrix),Cn=Float32Array.from(a.dF(Ur)),as=[a.aF(Ur.center.lng),a.aJ(Ur.center.lat)],Fr=[0,0],Is=Float32Array.from(a.dI(De.canonical,Ys,qr,Ur.worldSize/Ur._pixelsPerMercatorPixel))}else Fr=ee instanceof a.aU?ee.perspectiveTransform:[0,0],Mr=new Float32Array(16),tn=new Float32Array(9),Cn=new Float32Array(16),as=[0,0],Is=new Float32Array(9);const Cs=kE(Mt,Mr,tn,Cn,Is,lr||[0,0],a.aj(x.transform.zoom),as,Tr,fr||1,Pr,f,Fr,L?f.paint.get("raster-elevation"):0,2,At,Bt,J.range,or,wt,re),Sn=x.isTileAffectedByFog(De),Ds=x.getOrCreateProgram("raster",{defines:J.defines,overrideFog:Sn});if(x.uploadCommonUniforms(q,Ds,Qe),ee instanceof a.aU){const Ys=ee.elevatedGlobeVertexBuffer,Vs=ee.elevatedGlobeIndexBuffer;if(se||!E)ee.boundsBuffer&&ee.boundsSegments&&Ds.draw(x,G.TRIANGLES,st,_n.disabled,oe,vn.disabled,Cs,f.id,ee.boundsBuffer,x.quadTriangleIndexBuffer,ee.boundsSegments);else if(Ys&&Vs){const ws=Ur.zoom<=a.c_?ee.elevatedGlobeSegments:ee.getSegmentsForLongitude(Ur.center.lng);ws&&Ds.draw(x,G.TRIANGLES,st,_n.disabled,oe,He,Cs,f.id,Ys,Vs,ws)}}else if(B){st=new Wr(G.LEQUAL,Wr.ReadOnly,x.depthRangeFor3D);const Ys=x.globeSharedBuffers;if(Ys){const[Vs,ws,An]=Ys.getGridBuffers(qr,!1);Ds.draw(x,G.TRIANGLES,st,ze||kt,x.colorModeForRenderPass(),He,Cs,f.id,Vs,ws,An)}}else{const{tileBoundsBuffer:Ys,tileBoundsIndexBuffer:Vs,tileBoundsSegments:ws}=x.getTileBoundsBuffers(ht);Ds.draw(x,G.TRIANGLES,st,kt,oe,vn.disabled,Cs,f.id,Ys,Vs,ws)}}if(!(ee instanceof a.aU)&&B)for(const De of $e){const Qe=De.canonical.y===(1<>>16,2654435769),((De=Math.imul(De^De>>>16,2654435769))>>>0)/4294967296},ze=1/1.1;for(let De=0;Dea.e9[kt](Tt));wt.push(Tt);const st=Tt.canonical.x,Mt=Tt.canonical.y;for(const kt of wt){const Zt=Te.getTile(Qe?kt.wrapped():kt);if(!Zt)continue;const yr=Zt.rasterParticleState;if(!yr)continue;const Pr=kt.canonical.x+(1<He.tileID)),re&&(q.activeTexture.set(G.TEXTURE0),x.imageManager.bind(x.context,f.scope));const $e=[];if(x.terrain&&x.terrain.renderingToTexture&&x.emissiveMode==="mrt-fallback"&&$e.push("USE_MRT1"),B){const He=x.getOrCreateProgram(Ae,{overrideFog:!1,overrideRtt:!0,defines:$e}),ze=new Float32Array(a.bA([])),De=new a.aQ(0,0,0,0,0),Qe=re?qf(ze,L,E,x,0,f.scope,oe,B,{tileID:De,tileSize:J}):tv(ze,L,E,S.toPremultipliedRenderColor(T?null:f.lut));He.draw(x,G.TRIANGLES,fe,me,Ne,vn.disabled,Qe,f.id,x.viewportBuffer,x.quadTriangleIndexBuffer,x.viewportSegments)}else for(const He of Ze){const ze=x.isTileAffectedByFog(He),De=x.getOrCreateProgram(Ae,{overrideFog:ze,defines:$e}),Qe=He.toUnwrapped(),ht=v?He.projMatrix:x.transform.calculateProjMatrix(Qe);x.prepareDrawTile();const ot=u?u.getTile(He):Te?Te[He.key]:new Up(He,J,ee.zoom,x),Tt=re?qf(ht,L,E,x,0,f.scope,oe,B,{tileID:He,tileSize:J}):tv(ht,L,E,S.toPremultipliedRenderColor(T?null:f.lut));x.uploadCommonUniforms(q,De,Qe);const{tileBoundsBuffer:At,tileBoundsIndexBuffer:Bt,tileBoundsSegments:or}=x.getTileBoundsBuffers(ot);De.draw(x,G.TRIANGLES,fe,me,Ne,vn.disabled,Tt,f.id,At,Bt,or)}},sky:function(x,u,f){const v=x._atmosphere?a.aj(x.transform.zoom):1,S=f.paint.get("sky-opacity")*v;if(S===0)return;const T=x.context,E=f.paint.get("sky-type"),L=new Wr(T.gl.LEQUAL,Wr.ReadOnly,[0,1]),B=x.frameCounter/1e3%1;E==="atmosphere"?x.renderPass==="offscreen"?f.needsSkyboxCapture(x)&&(function(q,G,ee,J){const re=q.context,oe=re.gl;let se=G.skyboxFbo;if(!se){se=G.skyboxFbo=re.createFramebuffer(32,32,1,null),G.skyboxGeometry=new lb(re),G.skyboxTexture=re.gl.createTexture(),oe.bindTexture(oe.TEXTURE_CUBE_MAP,G.skyboxTexture),oe.texParameteri(oe.TEXTURE_CUBE_MAP,oe.TEXTURE_WRAP_S,oe.CLAMP_TO_EDGE),oe.texParameteri(oe.TEXTURE_CUBE_MAP,oe.TEXTURE_WRAP_T,oe.CLAMP_TO_EDGE),oe.texParameteri(oe.TEXTURE_CUBE_MAP,oe.TEXTURE_MIN_FILTER,oe.LINEAR),oe.texParameteri(oe.TEXTURE_CUBE_MAP,oe.TEXTURE_MAG_FILTER,oe.LINEAR);for(let Ae=0;Ae<6;++Ae)oe.texImage2D(oe.TEXTURE_CUBE_MAP_POSITIVE_X+Ae,0,oe.RGBA,32,32,0,oe.RGBA,oe.UNSIGNED_BYTE,null)}re.bindFramebuffer.set(se.framebuffer),re.viewport.set([0,0,32,32]);const me=G.getCenter(q,!0),fe=q.getOrCreateProgram("skyboxCapture"),Ne=new Float64Array(16);a.bA(Ne),a.en(Ne,Ne,.5*-Math.PI),tm(q,G,fe,Ne,me,0),a.bA(Ne),a.en(Ne,Ne,.5*Math.PI),tm(q,G,fe,Ne,me,1),a.bA(Ne),a.cU(Ne,Ne,.5*-Math.PI),tm(q,G,fe,Ne,me,2),a.bA(Ne),a.cU(Ne,Ne,.5*Math.PI),tm(q,G,fe,Ne,me,3),a.bA(Ne),tm(q,G,fe,Ne,me,4),a.bA(Ne),a.en(Ne,Ne,Math.PI),tm(q,G,fe,Ne,me,5),re.viewport.set([0,0,q.width,q.height])}(x,f),f.markSkyboxValid(x)):x.renderPass==="sky"&&function(q,G,ee,J,re){const oe=q.context,se=oe.gl,me=q.transform,fe=q.getOrCreateProgram("skybox");oe.activeTexture.set(se.TEXTURE0),se.bindTexture(se.TEXTURE_CUBE_MAP,G.skyboxTexture);const Ne=((Ae,Te,Ze,$e,He)=>({u_matrix:Ae,u_sun_direction:Te,u_cubemap:0,u_opacity:$e,u_temporal_offset:He}))(me.skyboxMatrix,G.getCenter(q,!1),0,J,re);q.uploadCommonUniforms(oe,fe),fe.draw(q,se.TRIANGLES,ee,_n.disabled,q.colorModeForRenderPass(),vn.backCW,Ne,"skybox",G.skyboxGeometry.vertexBuffer,G.skyboxGeometry.indexBuffer,G.skyboxGeometry.segment)}(x,f,L,S,B):E==="gradient"&&x.renderPass==="sky"&&function(q,G,ee,J,re){const oe=q.context,se=oe.gl,me=q.transform,fe=q.getOrCreateProgram("skyboxGradient");G.skyboxGeometry||(G.skyboxGeometry=new lb(oe)),oe.activeTexture.set(se.TEXTURE0);let Ne=G.colorRampTexture;Ne||(Ne=G.colorRampTexture=new a.T(oe,G.colorRamp,se.RGBA8)),Ne.bind(se.LINEAR,se.CLAMP_TO_EDGE);const Ae=((Te,Ze,$e,He,ze)=>({u_matrix:Te,u_color_ramp:0,u_center_direction:Ze,u_radius:a.an($e),u_opacity:He,u_temporal_offset:ze}))(me.skyboxMatrix,G.getCenter(q,!1),G.paint.get("sky-gradient-radius"),J,re);q.uploadCommonUniforms(oe,fe),fe.draw(q,se.TRIANGLES,ee,_n.disabled,q.colorModeForRenderPass(),vn.backCW,Ae,"skyboxGradient",G.skyboxGeometry.vertexBuffer,G.skyboxGeometry.indexBuffer,G.skyboxGeometry.segment)}(x,f,L,S,B)},custom:function(x,u,f,v){const S=x.context,T=f.implementation;if(!x.transform.projection.unsupportedLayers||!x.transform.projection.unsupportedLayers.includes("custom")||x.terrain&&(x.terrain.renderingToTexture||x.renderPass==="offscreen")&&f.isDraped(u)){if(x.renderPass==="offscreen"){const E=T.prerender;if(E){if(x.setCustomLayerDefaults(),S.setColorMode(x.colorModeForRenderPass()),x.transform.projection.name==="globe"){const L=x.transform.pointMerc;E.call(T,S.gl,x.transform.customLayerMatrix(),x.transform.getProjection(),x.transform.globeToMercatorMatrix(),a.aj(x.transform.zoom),[L.x,L.y],x.transform.pixelsPerMeterRatio)}else E.call(T,S.gl,x.transform.customLayerMatrix());S.setDirty(),x.setBaseState()}}else if(x.renderPass==="translucent"){if(x.terrain&&x.terrain.renderingToTexture){const L=T.renderToTile;if(L){const B=v[0].canonical,q={x:B.x+v[0].wrap*(T.wrapTileId?0:1<{q&&(q.useNormalOffset=!0,G||(q.enabled=!0))},J=u.getSource();if(x.renderPass==="light-beam"&&J.type!=="batched-model")return;if(J.type==="vector"||J.type==="geojson")return function(Te,Ze,$e,He,ze){const De=Te.transform,Qe=De.projection.name==="globe",ht=De.getFreeCameraOptions().position;if(!Te.modelManager)return;const ot=Te.modelManager;$e.modelManager=ot;const Tt=Te.shadowRenderer;if(!$e._unevaluatedLayout._values.hasOwnProperty("model-id"))return;const At=$e._unevaluatedLayout._values["model-id"],Bt=Object.assign({},$e.layout.get("model-id").parameters),or=Te.style.order.indexOf($e.fqid),wt=$e.paint.get("model-opacity").constantOr(1);for(const st of He){const Mt=Ze.getTile(st).getBucket($e);if(!Mt||Mt.projection.name!==De.projection.name)continue;const kt=Mt.getModelUris();if(kt&&!Mt.modelsRequested&&(ot.addModelsFromBucket(kt,ze),Mt.modelsRequested=!0),Qe)Bt.zoom=st.overscaledZ;else{const Tr=Dl(st,De);Bt.zoom=Tr}const Zt=At.possiblyEvaluate(Bt);if(HE(Te,Mt,st),Fd.shadowUniformsInitialized=!1,Fd.useSingleShadowCascade=!!Tt&&Tt.getMaxCascadeForTile(st.toUnwrapped())===0,Te.renderPass==="shadow"&&Tt){if(Te.currentShadowCascade===1&&Mt.isInsideFirstShadowMapFrustum)continue;const Tr=De.calculatePosMatrix(st.toUnwrapped(),De.worldSize);if(Fd.tileMatrix.set(Tr),Fd.shadowTileMatrix=Float32Array.from(Tt.calculateShadowPassMatrixFromMatrix(Tr)),Fd.aabb.min=[0,0,0],Fd.aabb.max[0]=Fd.aabb.max[1]=a.al,Fd.aabb.max[2]=0,k4(Mt,Fd,Te,$e.scope))continue}const yr=1<0&&Te.style.isLayerClipped($e,Ze.getSource())&&Mt.updateReplacement(st,Te.replacementSource,or,$e.scope)&&(Mt.uploaded=!1,Mt.upload(Te.context));let fr=0;const lr=new Array,Ur=new Array,Fr=new Array;for(let Tr in Mt.instancesPerModel){const Mr=Mt.instancesPerModel[Tr];Mr.features.length>0&&!Qe&&(Tr=Zt.evaluate(Mr.features[0].feature,{}));const tn=ot.getModel(Tr,ze);if(tn||ot.hasURLBeenRequested(Tr)||Mt.modelUris.includes(Tr)||(Mt.modelUris.push(Tr),Mt.modelsRequested=!1),tn&&tn.uploaded)if(Qe){const Cn=a.c5([],[ht.x,ht.y,ht.z],Te.transform.worldSize);a.ew(Cn,Cn);for(let as=0;as0&&Cs.elevationUpdate(Tr.terrain,as,qr,tn.source),Cs.needsReEvaluation(Tr,Is,tn)&&Cs.evaluate(tn))}})(Te,Ze,$e,He),function(){let Tr,Mr,tn;lr?(Tr=He.length-1,Mr=-1,tn=-1):(Tr=0,Mr=He.length,tn=1);const Cn=new Float64Array(16),as=a.cA(),Is=new a.P(0,0);for(let qr=Tr;qr!==Mr;qr+=tn){const Cs=He[qr],Sn=Ze.getTile(Cs).getBucket($e);if(!Sn||!Sn.uploaded)continue;let Ds=!1;ht&&(Ds=ht.getMaxCascadeForTile(Cs.toUnwrapped())===0);const Ys=De.calculatePosMatrix(Cs.toUnwrapped(),De.worldSize),Vs=Sn.modelTraits;!yr&&lr&&(a.bl(Cn,Ys),a.af(as,Tt,Cn),Is.x=as[0],Is.y=as[1]);const ws=[];Sn.setFilter($e.filter);for(const An of Sn.getNodesInfo()){if(An.hiddenByReplacement||!An.node.meshes)continue;const Rs=An.node;let Qi=0;Te.terrain&&Rs.elevation&&(Qi=Rs.elevation*Te.terrain.exaggeration());const Li=(()=>{const nl=An.aabb;return Zt.min=[...nl.min],Zt.max=[...nl.max],Zt.min[2]+=Qi,Zt.max[2]+=Qi,a.af(Zt.min,Zt.min,Ys),a.af(Zt.max,Zt.max,Ys),Zt})(),Ls=An.evaluatedScale;if(Ls[0]<=1&&Ls[1]<=1&&Ls[2]<=1&&Li.intersects(Pr)===0)continue;if(!yr&&lr){const nl=.16666666666666666;An.cameraCollisionOpacity=Tt[0]>Li.min[0]&&Tt[0]Li.min[1]&&Tt[1]!lr||An.opacity===1&&Rs.opacity===1?An.depthRs.depth?-1:1);for(const An of ws){const Rs=An.nodeInfo,Qi=Rs.node;let Li=a.aB([],wt,An.tileModelMatrix);a.aB(Li,Bt,Li);const Ls=a.bl([],Li);a.eg(Ls,Ls),a.cS(Ls,Ls,ov),Li=a.aB(Li,Li,Qi.globalMatrix);const ms=Te.renderPass==="light-beam",Pn=$e.paint.get("model-color-use-theme").constantOr("default")==="none",Ti=Vs&a.eI.HasMapboxMeshFeatures,ua=Ti?0:Rs.evaluatedRMEA[0][2];for(let Wi=0;Wi=Ut||Gi>=Ut}}const To=ci.material;let Hc;To.occlusionTexture&&To.occlusionTexture.offsetScale&&(Hc=To.occlusionTexture.offsetScale,Ba.defines.push("OCCLUSION_TEXTURE_TRANSFORM"));const Cu=Te.getOrCreateProgram("model",Ba);!yr&&ht&&ht.setupShadowsFromMatrix(An.tileModelMatrix,Cu,ht.useNormalOffset),Te.uploadCommonUniforms(ze,Cu,null,sl);const oc=To.pbrMetallicRoughness;oc.metallicFactor=.9,oc.roughnessFactor=.5;const ra=Yp(new Float32Array(Uo),new Float32Array(Li),new Float32Array(Ls),new Float32Array(Qi.globalMatrix),Te,An.opacity,oc.baseColorFactor,To.emissiveFactor,oc.metallicFactor,oc.roughnessFactor,To,ua,$e,[0,0,0],Hc);!Ll&&(Rs.hasTranslucentParts||An.opacity<1)&&Cu.draw(Te,ze.gl.TRIANGLES,Mt,_n.disabled,En.disabled,vn.backCCW,ra,$e.id,ci.vertexBuffer,ci.indexBuffer,ci.segments,$e.paint,Te.transform.zoom,void 0,nl),Cu.draw(Te,ze.gl.TRIANGLES,Ll?kt:Mt,_n.disabled,Ll||An.opacity<1||Rs.hasTranslucentParts?En.alphaBlended:En.unblended,vn.backCCW,ra,$e.id,ci.vertexBuffer,ci.indexBuffer,ci.segments,$e.paint,Te.transform.zoom,void 0,nl)}}}}()}(x,u,f,v),void ee();if(J.type!=="model")return;const re=J.getModels(),oe=[],se=x.transform.getFreeCameraOptions().position,me=a.c5([],[se.x,se.y,se.z],x.transform.worldSize);a.ew(me,me);const fe=[],Ne=[];let Ae=0;for(const Te of re){const Ze=u.getFeatureState("",Te.id),$e={type:"Unknown",id:Te.id,properties:Te.featureProperties},He=f.paint.get("model-rotation").evaluate($e,Ze),ze=f.paint.get("model-scale").evaluate($e,Ze),De=f.paint.get("model-translation").evaluate($e,Ze),Qe=f.paint.get("model-opacity").evaluate($e,Ze);UE(f,Te.id,Ze,Te.featureProperties,Te.nodeOverrideNames,Te.nodeOverrides),VE(f,Te.id,Ze,Te.featureProperties,Te.materialOverrideNames,Te.materialOverrides),Te.nodeOverrides.size>0&&Te.computeBoundsAndApplyParent(),Te.computeModelMatrix(x,He,ze,De,L,E,!1);const ht=a.bA([]),ot=a.ef(Te.position.lat,x.transform.zoom),Tt=a.bq([],[1,1,1/ot]);a.br(ht,ht,me),oe.push({zScaleMatrix:Tt,negCameraPosMatrix:ht});for(const At of Te.nodes)rm(x,At,Te.matrix,x.transform.expandedFarZProjMatrix,Ae,fe,Ne,Te.materialOverrides,Qe);Ae++}if(fe.sort((Te,Ze)=>Ze.depth-Te.depth),x.renderPass!=="shadow")qE(x,f,fe,Ne,oe),ee();else{for(const Te of Ne)Ju(Te.mesh,Te.nodeModelMatrix,x,f);for(const Te of fe)Ju(Te.mesh,Te.nodeModelMatrix,x,f);ee()}}},mb={line:function(x,u,f){if(x.hasElevatedBuckets=!1,x.hasNonElevatedBuckets=!1,x._unevaluatedLayout.getValue("line-elevation-reference")!==void 0||x._unevaluatedLayout.getValue("line-z-offset")!==void 0){if(u){const v=u.getVisibleCoordinates();for(const S of v){const T=u.getTile(S).getBucket(x);if(T&&(T.elevationType!=="none"?x.hasElevatedBuckets=!0:x.hasNonElevatedBuckets=!0,x.hasElevatedBuckets&&x.hasNonElevatedBuckets))break}}}else x.hasNonElevatedBuckets=!0},model:function(x,u,f){const v=u.getSource();if(!v.loaded())return;if(v.type==="vector"||v.type==="geojson")return void(f.modelManager&&f.modelManager.upload(f,av(f,x)));if(v.type==="batched-model"||v.type!=="model")return;const S=v.getModels();for(const T of S)T.upload(f.context)},raster:function(x,u,f){const v=u.getSource();if(!(v instanceof xl&&v.loaded()))return;const S=x.sourceLayer||v.rasterLayerIds&&v.rasterLayerIds[0];if(!S)return;const T=x.paint.get("raster-array-band")||v.getInitialBand(S);if(T==null)return;const E=u.getIds().map(L=>u.getTileByID(L));for(const L of E)L.updateNeeded(x.id,T)&&v.prepareTile(L,S,x.id,T)},"raster-particle":function(x,u,f){const v=u.getSource();if(!(v instanceof xl&&v.loaded()))return;const S=x.sourceLayer||v.rasterLayerIds&&v.rasterLayerIds[0];if(!S)return;const T=x.paint.get("raster-particle-array-band")||v.getInitialBand(S);if(T==null)return;const E=u.getIds().map(L=>u.getTileByID(L));for(const L of E)L.updateNeeded(x.id,T)&&v.prepareTile(L,S,x.id,T)}},qc={fill:tb},gb={fill:function(x,u,f,v){if(!f.layout||f.layout.get("fill-elevation-reference")==="none"||f.paint.get("fill-opacity").constantOr(1)===0)return;const S=x.context.gl,T=new Wr(S.LEQUAL,Wr.ReadOnly,x.depthRangeFor3D),E=new _n({func:S.ALWAYS,mask:255},255,255,S.KEEP,S.KEEP,S.REPLACE),L=x.transform.getFreeCameraOptions().position,B=x.getOrCreateProgram("elevatedStructuresDepthReconstruct");for(const q of v){const G=u.getTile(q),ee=G.getBucket(f);if(!ee)continue;const J=ee.elevatedStructures;if(!J||J.depthSegments.segments[0].primitiveLength===0)continue;const re=ME(q.toUnwrapped(),L),oe=x.translatePosMatrix(q.projMatrix,G,f.paint.get("fill-translate"),f.paint.get("fill-translate-anchor")),se=Zp(oe,re,0,1,0);B.draw(x,S.TRIANGLES,T,E,En.disabled,vn.disabled,se,f.id,J.vertexBuffer,J.indexBuffer,J.depthSegments,f.paint,x.transform.zoom)}}};class yb{constructor(u,f,v,S,T){this.context=new Tg(u,f),this.transform=v,this._tileTextures={},this.frameCopies=[],this.loadTimeStamps=[],this._timeStamp=a.o.now(),this._averageFPS=0,this._fpsHistory=[],this._dt=0,this._debugParams={forceEnablePrecipitation:!1,showTerrainProxyTiles:!1,fpsWindow:30,continousRedraw:!1,enabledLayers:{}};const E=["fill","line","symbol","circle","heatmap","fill-extrusion","building","raster","raster-particle","hillshade","model","background","sky"];for(const B of E)this._debugParams.enabledLayers[B]=!0;for(const B of E);this.occlusionParams=new Ag,this.setup(),this.numSublayers=jc.maxUnderzooming+jc.maxOverzooming+1,this.depthEpsilon=1/Math.pow(2,16),this.deferredRenderGpuTimeQueries=[],this.gpuTimers={},this.frameCounter=0,this._backgroundTiles={},this.conflationActive=!1,this.replacementSource=new a.eP,this.longestCutoffRange=0,this.minCutoffZoom=0,this._fogVisible=!1,this._cachedTileFogOpacities={},this._shadowRenderer=new gg(this),this._wireframeDebugCache=new Wf,this.renderDefaultNorthPole=!0,this.renderDefaultSouthPole=!0,this.layersWithOcclusionOpacity=[];const L=new a.q({width:1,height:1},Uint8Array.of(0,0,0,0));this.emptyDepthTexture=new a.T(this.context,L,u.RGBA8),this._clippingActiveLastFrame=!1,this.scaleFactor=S,this.worldview=T,this._forceEmissiveMode=!1,this.emissiveMode="constant"}updateTerrain(u,f){const v=!!u&&!!u.terrain&&this.transform.projection.supportsTerrain;if(!(v||this._terrain&&this._terrain.enabled))return;this._terrain||(this._terrain=new RS(this,u));const S=this._terrain;this.transform.elevation=v?S:null,S.update(u,this.transform,f),this.transform.elevation&&!S.enabled&&(this.transform.elevation=null)}_updateFog(u){const f=u.fog;if(!f||this.transform.projection.name==="globe"||f.getOpacity(this.transform.pitch)<1||f.properties.get("horizon-blend")<.03)return void(this.transform.fogCullDistSq=null);const[v,S]=f.getFovAdjustedRange(this.transform._fov);if(v>S)return void(this.transform.fogCullDistSq=null);const T=v+.78*(S-v);this.transform.fogCullDistSq=T*T}get terrain(){return this.transform._terrainEnabled()&&this._terrain&&this._terrain.enabled||this._forceTerrainMode?this._terrain:null}get forceTerrainMode(){return this._forceTerrainMode}set forceTerrainMode(u){u&&!this._terrain&&(this._terrain=new RS(this,this.style)),this._forceTerrainMode=u}get shadowRenderer(){return this._shadowRenderer&&this._shadowRenderer.enabled?this._shadowRenderer:null}get wireframeDebugCache(){return this._wireframeDebugCache}resize(u,f){if(this.width=u*a.o.devicePixelRatio,this.height=f*a.o.devicePixelRatio,this.context.viewport.set([0,0,this.width,this.height]),this.style)for(const v of this.style.order)this.style._mergedLayers[v].resize()}setup(){const u=this.context,f=new a.bd;f.emplaceBack(0,0),f.emplaceBack(a.al,0),f.emplaceBack(0,a.al),f.emplaceBack(a.al,a.al),this.tileExtentBuffer=u.createVertexBuffer(f,a.bf.members),this.tileExtentSegments=a.bg.simpleSegment(0,0,4,2);const v=new a.bd;v.emplaceBack(0,0),v.emplaceBack(a.al,0),v.emplaceBack(0,a.al),v.emplaceBack(a.al,a.al),this.debugBuffer=u.createVertexBuffer(v,a.bf.members),this.debugSegments=a.bg.simpleSegment(0,0,4,5);const S=new a.bd;S.emplaceBack(-1,-1),S.emplaceBack(1,-1),S.emplaceBack(-1,1),S.emplaceBack(1,1),this.viewportBuffer=u.createVertexBuffer(S,a.bf.members),this.viewportSegments=a.bg.simpleSegment(0,0,4,2);const T=new a.b1;T.emplaceBack(0,0,0,0),T.emplaceBack(a.al,0,a.al,0),T.emplaceBack(0,a.al,0,a.al),T.emplaceBack(a.al,a.al,a.al,a.al),this.mercatorBoundsBuffer=u.createVertexBuffer(T,a.bi.members),this.mercatorBoundsSegments=a.bg.simpleSegment(0,0,4,2);const E=new a.b0;E.emplaceBack(0,1,2),E.emplaceBack(2,1,3),this.quadTriangleIndexBuffer=u.createIndexBuffer(E);const L=new a.be;for(const q of[0,1,3,2,0])L.emplaceBack(q);this.debugIndexBuffer=u.createIndexBuffer(L),this.emptyTexture=new a.T(u,new a.q({width:1,height:1},Uint8Array.of(0,0,0,0)),u.gl.RGBA8),this.identityMat=a.bC();const B=this.context.gl;this.stencilClearMode=new _n({func:B.ALWAYS,mask:0},0,255,B.ZERO,B.ZERO,B.ZERO),this.loadTimeStamps.push(performance.now())}getMercatorTileBoundsBuffers(){return{tileBoundsBuffer:this.mercatorBoundsBuffer,tileBoundsIndexBuffer:this.quadTriangleIndexBuffer,tileBoundsSegments:this.mercatorBoundsSegments}}getTileBoundsBuffers(u){return u._makeTileBoundsBuffers(this.context,this.transform.projection),u._tileBoundsBuffer?{tileBoundsBuffer:u._tileBoundsBuffer,tileBoundsIndexBuffer:u._tileBoundsIndexBuffer,tileBoundsSegments:u._tileBoundsSegments}:this.getMercatorTileBoundsBuffers()}clearStencil(){const u=this.context.gl;this.nextStencilID=1,this.currentStencilSource=void 0,this._tileClippingMaskIDs={},this.getOrCreateProgram("clippingMask").draw(this,u.TRIANGLES,Wr.disabled,this.stencilClearMode,En.disabled,vn.disabled,Qx(this.identityMat),"$clipping",this.viewportBuffer,this.quadTriangleIndexBuffer,this.viewportSegments)}resetStencilClippingMasks(){this.terrain||(this.currentStencilSource=void 0,this._tileClippingMaskIDs={})}_renderTileClippingMasks(u,f,v){if(!f||this.currentStencilSource===f.id||!u.isTileClipped()||!v||v.length===0)return;if(this._tileClippingMaskIDs&&!this.terrain){let L=!1;for(const B of v)if(this._tileClippingMaskIDs[B.key]===void 0){L=!0;break}if(!L)return}this.currentStencilSource=f.id;const S=this.context,T=S.gl;this.nextStencilID+v.length>256&&this.clearStencil(),S.setColorMode(En.disabled),S.setDepthMode(Wr.disabled);const E=this.getOrCreateProgram("clippingMask");this._tileClippingMaskIDs={};for(const L of v){const B=f.getTile(L),q=this._tileClippingMaskIDs[L.key]=this.nextStencilID++,{tileBoundsBuffer:G,tileBoundsIndexBuffer:ee,tileBoundsSegments:J}=this.getTileBoundsBuffers(B);E.draw(this,T.TRIANGLES,Wr.disabled,new _n({func:T.ALWAYS,mask:0},q,255,T.KEEP,T.KEEP,T.REPLACE),En.disabled,vn.disabled,Qx(L.projMatrix),"$clipping",G,ee,J)}}stencilModeFor3D(){this.currentStencilSource=void 0,this.nextStencilID+1>256&&this.clearStencil();const u=this.nextStencilID++,f=this.context.gl;return new _n({func:f.NOTEQUAL,mask:255},u,255,f.KEEP,f.KEEP,f.REPLACE)}stencilModeForClipping(u){if(this.terrain)return this.terrain.stencilModeForRTTOverlap(u);const f=this.context.gl;return new _n({func:f.EQUAL,mask:255},this._tileClippingMaskIDs[u.key],0,f.KEEP,f.KEEP,f.REPLACE)}stencilConfigForOverlap(u){const f=this.context.gl,v=u.sort((E,L)=>L.overscaledZ-E.overscaledZ),S=v[v.length-1].overscaledZ,T=v[0].overscaledZ-S+1;if(T>1){this.currentStencilSource=void 0,this.nextStencilID+T>256&&this.clearStencil();const E={};for(let L=0;Lthis._debugParams.fpsWindow&&this._fpsHistory.splice(0,this._fpsHistory.length-this._debugParams.fpsWindow),this._averageFPS=Math.round(this._fpsHistory.reduce((u,f)=>u+f/this._fpsHistory.length,0))}render(u,f){const v=a.o.now();this._dt=v-this._timeStamp,this._timeStamp=v,this._wireframeDebugCache.update(this.frameCounter),this._debugParams.continousRedraw=u.map.repaint,this.style=u,this.options=f;const S=this.style._mergedLayers,T=!(!this.terrain||!this.terrain.enabled),E=()=>this.style._getOrder(T).filter(wt=>{const st=S[wt];return!(st.type in this._debugParams.enabledLayers)||this._debugParams.enabledLayers[st.type]});let L=E(),B=!1,q=!1,G=null,ee=0,J=!1;for(const wt of L){const st=S[wt];st.visibility!=="none"&&(st.type==="circle"?B=!0:st.type==="building"?(G=st,++ee):st.type==="symbol"&&(st.hasOcclusionOpacityProperties?q=!0:B=!0))}this.updateEmissiveMode();let re=L.map(wt=>S[wt]);const oe=this.style._mergedSourceCaches;this.imageManager=u.imageManager,this.modelManager=u.modelManager,this.symbolFadeChange=u.placement.symbolFadeChange(a.o.now()),this.imageManager.beginFrame();for(const wt in oe){const st=oe[wt];st.used&&(st.prepare(this.context),st.getSource().usedInConflation&&++ee)}let se=!1;for(const wt of re)wt.isHidden(this.transform.zoom)||(wt.type==="clip"&&(se=!0),this.prepareLayer(wt));const me={},fe={},Ne={},Ae={},Te={};for(const wt in oe){const st=oe[wt];me[wt]=st.getVisibleCoordinates(),fe[wt]=me[wt].slice().reverse(),Ne[wt]=st.getVisibleCoordinates(!0).reverse(),Ae[wt]=st.getShadowCasterCoordinates(),Te[wt]=st.sortCoordinatesByDistance(me[wt])}const Ze=wt=>{const st=this.style.getLayerSourceCache(wt);return st&&st.used?st.getSource():null};if(ee||se||this._clippingActiveLastFrame){const wt=[],st=[];let Mt=0;for(const kt of re)this.isSourceForClippingOrConflation(kt,Ze(kt))&&(wt.push(kt),st.push(Mt)),Mt++;if(wt&&(se||wt.length>1)||this._clippingActiveLastFrame){se=!1;const kt=[];for(let Zt=0;Zt0){const kt=Ze(st);kt&&(this.minCutoffZoom=Math.max(kt.minzoom,this.minCutoffZoom)),st.minzoom&&(this.minCutoffZoom=Math.max(st.minzoom,this.minCutoffZoom))}st.is3D(T)&&(this.opaquePassCutoff===1/0&&(this.opaquePassCutoff=wt),this._lastOcclusionLayer=wt)}const $e=this.style&&this.style.fog;$e?(this._fogVisible=$e.getOpacity(this.transform.pitch)!==0,this._fogVisible&&this.transform.projection.name!=="globe"&&(this._fogVisible=$e.isVisibleOnFrustum(this.transform.cameraFrustum))):this._fogVisible=!1,this._cachedTileFogOpacities={},this.terrain&&(this.terrain.updateTileBinding(Ne),this.opaquePassCutoff=0,L=E(),re=L.map(wt=>S[wt]));const He=this._shadowRenderer;if(He){He.updateShadowParameters(this.transform,this.style.directionalLight);for(const wt in oe)for(const st of me[wt]){let Mt={min:0,max:0};this.terrain&&(Mt=this.terrain.getMinMaxForTile(st)||Mt),He.addShadowReceiver(st.toUnwrapped(),Mt.min,Mt.max)}}this.transform.projection.name!=="globe"||this.globeSharedBuffers||(this.globeSharedBuffers=new a.eR(this.context)),this.style.fog&&this.transform.projection.supportsFog?(this._atmosphere||(this._atmosphere=new $E(this)),this._atmosphere.update(this)):this._atmosphere&&(this._atmosphere.destroy(),this._atmosphere=void 0);const ze=this._debugParams.forceEnablePrecipitation||!(!this.style||!this.style.snow),De=this._debugParams.forceEnablePrecipitation||!(!this.style||!this.style.rain);if(ze&&!this._snow&&(this._snow=new XS(this)),!ze&&this._snow&&(this._snow.destroy(),delete this._snow),De&&!this._rain&&(this._rain=new pb(this)),!De&&this._rain&&(this._rain.destroy(),delete this._rain),this._snow&&this._snow.update(this),this._rain&&this._rain.update(this),G){this.buildingTileBorderManager||(this.buildingTileBorderManager=new cb);const wt=this.style.getLayerSourceCache(G);this.buildingTileBorderManager.updateBorders(wt,G)}if(!Ht.has(this.context.gl))return;this.renderPass="offscreen";for(const wt of re){const st=u.getLayerSourceCache(wt);if(!wt.hasOffscreenPass()||wt.isHidden(this.transform.zoom))continue;const Mt=st?fe[st.id]:void 0;(wt.type==="custom"||wt.type==="raster"||wt.type==="raster-particle"||wt.isSky()||Mt&&Mt.length)&&this.renderLayer(this,st,wt,Mt)}this.depthRangeFor3D=[0,1-(re.length+2)*this.numSublayers*this.depthEpsilon],this._shadowRenderer&&(this.renderPass="shadow",this._shadowRenderer.drawShadowPass(this.style,Ae)),this.context.bindFramebuffer.set(null),this.context.viewport.set([0,0,this.width,this.height]);const Qe=this.transform.projection.name==="globe"||this.transform.isHorizonVisible(),ht=(()=>{if(f.showOverdrawInspector)return a.ao.black;const wt=this.style.fog;if(wt&&this.transform.projection.supportsFog){const st=this.style.getLut(wt.scope);if(!Qe){const Mt=wt.properties.get("color-use-theme")==="none",kt=wt.properties.get("color").toNonPremultipliedRenderColor(Mt?null:st).toArray01();return new a.ao(...kt)}if(Qe){const Mt=wt.properties.get("space-color-use-theme")==="none",kt=wt.properties.get("space-color").toNonPremultipliedRenderColor(Mt?null:st).toArray01();return new a.ao(...kt)}}return a.ao.transparent})();if(this.context.clear({color:ht,depth:1}),this.clearStencil(),this._showOverdrawInspector=f.showOverdrawInspector,this.renderPass="opaque",this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&Qe&&this._atmosphere.drawStars(this,this.style.fog),!this.terrain)for(this.currentLayer=L.length-1;this.currentLayer>=0;this.currentLayer--){const wt=re[this.currentLayer],st=u.getLayerSourceCache(wt);if(wt.isSky())continue;const Mt=st?(wt.is3D(T)?Te:fe)[st.id]:void 0;this._renderTileClippingMasks(wt,st,Mt),this.renderLayer(this,st,wt,Mt)}if(this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&Qe&&this._atmosphere.drawAtmosphereGlow(this,this.style.fog),this.renderPass="sky",(!this._atmosphere||a.aj(this.transform.zoom)>0)&&(this.transform.projection.name==="globe"||this.transform.isHorizonVisible()))for(this.currentLayer=0;this.currentLayer{for(this.currentLayer=0;this.currentLayer0&&wt.hasShadowPass()&&--Tt==0){{this.clearStencil(),this.resetStencilClippingMasks();const Mt=this.currentLayer;for(this.currentLayer=0;this.currentLayer=this._lastOcclusionLayer&&this.layersWithOcclusionOpacity.length>0){const Mt=this.currentLayer;this.depthOcclusion=!0;for(const kt of this.layersWithOcclusionOpacity){this.currentLayer=kt;const Zt=re[this.currentLayer],yr=u.getLayerSourceCache(Zt),Pr=yr?fe[yr.id]:void 0;this.terrain||this._renderTileClippingMasks(Zt,yr,yr?me[yr.id]:void 0),this.renderLayer(this,yr,Zt,Pr)}this.depthOcclusion=!1,this.currentLayer=Mt,this.renderPass="translucent",this.layersWithOcclusionOpacity=[]}++this.currentLayer}}if(this.terrain&&this.terrain.postRender(),this._snow&&this._snow.draw(this),this._rain&&this._rain.draw(this),this.options.showTileBoundaries||this.options.showQueryGeometry||this.options.showTileAABBs){let wt=null;re.forEach(st=>{const Mt=u.getLayerSourceCache(st);Mt&&!st.isHidden(this.transform.zoom)&&Mt.getVisibleCoordinates().length&&(!wt||wt.getSource().maxzoom0?f.pop():null}terrainRenderModeElevated(){return this.style&&!!this.style.getTerrain()&&!!this.terrain&&!this.terrain.renderingToTexture||this.forceTerrainMode}linearFloatFilteringSupported(){return this.context.extTextureFloatLinear!=null}currentGlobalDefines(u,f,v){const S=v===void 0?this.terrain&&this.terrain.renderingToTexture:v,T=[];return this.style&&this.style.enable3dLights()&&(u==="globeRaster"||u==="terrainRaster"?(T.push("LIGHTING_3D_MODE"),T.push("LIGHTING_3D_ALPHA_EMISSIVENESS")):S||T.push("LIGHTING_3D_MODE")),this.renderPass==="shadow"&&(this._shadowMapDebug||T.push("DEPTH_TEXTURE")),this.terrainRenderModeElevated()&&(T.push("TERRAIN"),this.linearFloatFilteringSupported()&&T.push("TERRAIN_DEM_FLOAT_FORMAT")),this.transform.projection.name==="globe"&&T.push("GLOBE"),!this._fogVisible||S||f!==void 0&&!f||T.push("FOG","FOG_DITHERING"),S&&T.push("RENDER_TO_TEXTURE"),this._showOverdrawInspector&&T.push("OVERDRAW_INSPECTOR"),T}getOrCreateProgram(u,f){this.cache=this.cache||{};const v=f&&f.defines||[],S=f&&f.config,T=this.currentGlobalDefines(u,f&&f.overrideFog,f&&f.overrideRtt).concat(v),E=_E.cacheKey(wS[u],u,T,S);return this.cache[E]||(this.cache[E]=new _E(this.context,u,wS[u],S,eb[u],T)),this.cache[E]}setCustomLayerDefaults(){this.context.unbindVAO(),this.context.cullFace.setDefault(),this.context.frontFace.setDefault(),this.context.cullFaceSide.setDefault(),this.context.activeTexture.setDefault(),this.context.pixelStoreUnpack.setDefault(),this.context.pixelStoreUnpackPremultiplyAlpha.setDefault(),this.context.pixelStoreUnpackFlipY.setDefault()}setBaseState(){const u=this.context.gl;this.context.cullFace.set(!1),this.context.viewport.set([0,0,this.width,this.height]),this.context.blendEquation.set(u.FUNC_ADD)}initDebugOverlayCanvas(){this.debugOverlayCanvas==null&&(this.debugOverlayCanvas=document.createElement("canvas"),this.debugOverlayCanvas.width=512,this.debugOverlayCanvas.height=512,this.debugOverlayTexture=new a.T(this.context,this.debugOverlayCanvas,this.context.gl.RGBA8))}destroy(){this._terrain&&this._terrain.destroy(),this._atmosphere&&(this._atmosphere.destroy(),this._atmosphere=void 0),this.globeSharedBuffers&&this.globeSharedBuffers.destroy(),this.emptyTexture.destroy(),this.debugOverlayTexture&&this.debugOverlayTexture.destroy(),this._wireframeDebugCache.destroy(),this.depthFBO&&(this.depthFBO.destroy(),this.depthFBO=void 0,this.depthTexture=void 0),this.emptyDepthTexture&&this.emptyDepthTexture.destroy()}prepareDrawTile(){this.terrain&&this.terrain.prepareDrawTile()}uploadCommonLightUniforms(u,f){if(this.style.enable3dLights()){const v=this.style.directionalLight,S=this.style.ambientLight;if(v&&S){const T=((E,L,B)=>{const q=E.properties.get("direction"),G=E.properties.get("color-use-theme")==="none",ee=E.properties.get("color").toNonPremultipliedRenderColor(G?null:B.getLut(E.scope)).toArray01(),J=E.properties.get("intensity"),re=L.properties.get("color-use-theme")==="none",oe=L.properties.get("color").toNonPremultipliedRenderColor(re?null:B.getLut(L.scope)).toArray01(),se=L.properties.get("intensity"),me=[q.x,q.y,q.z],fe=a.dN(oe,se),Ne=a.dN(ee,J);return{u_lighting_ambient_color:fe,u_lighting_directional_dir:me,u_lighting_directional_color:Ne,u_ground_radiance:Ng(me,Ne,fe)}})(v,S,this.style);f.setLightsUniformValues(u,T)}}}uploadCommonUniforms(u,f,v,S,T){if(this.uploadCommonLightUniforms(u,f),this.terrain&&this.terrain.renderingToTexture)return;const E=this.style.fog;if(E){const L=E.getOpacity(this.transform.pitch),B=((q,G,ee,J,re,oe,se,me,fe,Ne,Ae,Te)=>{const Ze=q.transform,$e=G.properties.get("color-use-theme")==="none",He=G.properties.get("color").toNonPremultipliedRenderColor($e?null:q.style.getLut(G.scope)).toArray01();He[3]=J;const ze=q.frameCounter/1e3%1,[De,Qe]=G.properties.get("vertical-range");return{u_fog_matrix:ee?Ze.calculateFogTileMatrix(ee):Te||q.identityMat,u_fog_range:G.getFovAdjustedRange(Ze._fov),u_fog_color:He,u_fog_horizon_blend:G.properties.get("horizon-blend"),u_fog_vertical_limit:[Math.min(De,Qe),Qe],u_fog_temporal_offset:ze,u_frustum_tl:re,u_frustum_tr:oe,u_frustum_br:se,u_frustum_bl:me,u_globe_pos:fe,u_globe_radius:Ne,u_viewport:Ae,u_globe_transition:a.aj(Ze.zoom),u_is_globe:+(Ze.projection.name==="globe")}})(this,E,v,L,this.transform.frustumCorners.TL,this.transform.frustumCorners.TR,this.transform.frustumCorners.BR,this.transform.frustumCorners.BL,this.transform.globeCenterInViewSpace,this.transform.globeRadius,[this.transform.width*a.o.devicePixelRatio,this.transform.height*a.o.devicePixelRatio],S);f.setFogUniformValues(u,B)}T&&f.setCutoffUniformValues(u,T.uniformValues)}setTileLoadedFlag(u){this.tileLoaded=u}saveCanvasCopy(){const u=this.canvasCopy();u&&(this.frameCopies.push(u),this.tileLoaded=!1)}canvasCopy(){const u=this.context.gl,f=u.createTexture();return u.bindTexture(u.TEXTURE_2D,f),u.copyTexImage2D(u.TEXTURE_2D,0,u.RGBA,0,0,u.drawingBufferWidth,u.drawingBufferHeight,0),f}getCanvasCopiesAndTimestamps(){return{canvasCopies:this.frameCopies,timeStamps:this.loadTimeStamps}}averageElevationNeedsEasing(){if(!this.transform._elevation)return!1;const u=this.style&&this.style.fog;return!!u&&u.getOpacity(this.transform.pitch)!==0}getBackgroundTiles(){const u=this._backgroundTiles,f=this._backgroundTiles={},v=this.transform.coveringTiles({tileSize:512});for(const S of v)f[S.key]=u[S.key]||new Up(S,512,this.transform.tileZoom,this,void 0,this.worldview);return f}clearBackgroundTiles(){this._backgroundTiles={}}isSourceForClippingOrConflation(u,f){return!(!u.is3D(!(!this.terrain||!this.terrain.enabled))||u.type!=="clip"&&u.type!=="building"&&(u.minzoom&&u.minzoom>this.transform.zoom||(this.style._clipLayerPresent||u.sourceLayer!=="building"&&u.sourceLayer!=="procedural_buildings")&&(!f||f.type!=="batched-model")))}isTileAffectedByFog(u){if(!this.style||!this.style.fog)return!1;if(this.transform.projection.name==="globe")return!0;let f=this._cachedTileFogOpacities[u.key];return f||(this._cachedTileFogOpacities[u.key]=f=this.style.fog.getOpacityForTile(u)),f[0]>=Ut||f[1]>=Ut}setupDepthForOcclusion(u,f,v){const S=this.context,T=S.gl,E=!!v;var L;v||(v={u_dem:2,u_dem_prev:4,u_dem_tl:[0,0],u_dem_tl_prev:[0,0],u_dem_scale:0,u_dem_scale_prev:0,u_dem_size:0,u_dem_lerp:1,u_depth:3,u_depth_size_inv:[0,0],u_depth_range_unpack:[0,1],u_occluder_half_size:16,u_occlusion_depth_offset:-1e-4,u_exaggeration:0}),S.activeTexture.set(T.TEXTURE3),u&&this.depthFBO&&this.depthTexture?(this.depthTexture.bind(T.NEAREST,T.CLAMP_TO_EDGE),v.u_depth_size_inv=[1/this.depthFBO.width,1/this.depthFBO.height],v.u_depth_range_unpack=[2/((L=this.depthRangeFor3D)[1]-L[0]),-1-2*L[0]/(L[1]-L[0])],v.u_occluder_half_size=.5*this.occlusionParams.occluderSize,v.u_occlusion_depth_offset=this.occlusionParams.depthOffset):this.emptyDepthTexture.bind(T.NEAREST,T.CLAMP_TO_EDGE),S.activeTexture.set(T.TEXTURE0),E||f.setTerrainUniformValues(S,v)}updateEmissiveMode(){if(this._forceEmissiveMode)return;const u=this.style.hasDataDrivenEmissiveStrength();this.emissiveMode=u?this.context.extBlendFuncExtended?"dual-source-blending":"mrt-fallback":"constant"}}function xb(x,u){let f=!1,v=null;const S=()=>{v=null,f&&(x(),v=setTimeout(S,u),f=!1)};return()=>(f=!0,v||S(),v)}class QS{constructor(u){this._hashName=u&&encodeURIComponent(u),a.aY(["_getCurrentHash","_onHashChange","_updateHash"],this),this._updateHash=xb(this._updateHashUnthrottled.bind(this),300)}addTo(u){return this._map=u,window.addEventListener("hashchange",this._onHashChange,!1),u.on("moveend",this._updateHash),this}remove(){return this._map?(this._map.off("moveend",this._updateHash),window.removeEventListener("hashchange",this._onHashChange,!1),clearTimeout(this._updateHash()),this._map=void 0,this):this}getHashString(){const u=this._map;if(!u)return"";const f=Fa(u);if(this._hashName){const v=this._hashName;let S=!1;const T=location.hash.slice(1).split("&").map(E=>{const L=E.split("=")[0];return L===v?(S=!0,`${L}=${f}`):E}).filter(E=>E);return S||T.push(`${v}=${f}`),`#${T.join("&")}`}return`#${f}`}_getCurrentHash(){const u=location.hash.replace("#","");if(this._hashName){let f;return u.split("&").map(v=>v.split("=")).forEach(v=>{v[0]===this._hashName&&(f=v)}),(f&&f[1]||"").split("/")}return u.split("/")}_onHashChange(){const u=this._map;if(!u)return!1;const f=this._getCurrentHash();if(f.length>=3&&!f.some(v=>isNaN(Number(v)))){const v=u.dragRotate.isEnabled()&&u.touchZoomRotate.isEnabled()?+(f[3]||0):u.getBearing();return u.jumpTo({center:[+f[2],+f[1]],zoom:+f[0],bearing:v,pitch:+(f[4]||0)}),!0}return!1}_updateHashUnthrottled(){history.replaceState(history.state,"",location.href.replace(/(#.+)?$/,this.getHashString()))}}function Fa(x,u){const f=x.getCenter(),v=Math.round(100*x.getZoom())/100,S=Math.ceil((v*Math.LN2+Math.log(512/360/.5))/Math.LN10),T=Math.pow(10,S),E=Math.round(f.lng*T)/T,L=Math.round(f.lat*T)/T,B=x.getBearing(),q=x.getPitch();let G=u?`/${E}/${L}/${v}`:`${v}/${L}/${E}`;return(B||q)&&(G+="/"+Math.round(10*B)/10),q&&(G+=`/${Math.round(q)}`),G}const Ig={linearity:.3,easing:a.eT(0,0,.3,1)},JS=Object.assign({deceleration:2500,maxSpeed:1400},Ig),eN=Object.assign({deceleration:20,maxSpeed:1400},Ig),sm=Object.assign({deceleration:1e3,maxSpeed:360},Ig),tN=Object.assign({deceleration:1e3,maxSpeed:90},Ig);class rN{constructor(u){this._map=u,this.clear()}clear(){this._inertiaBuffer=[]}record(u){this._drainInertiaBuffer(),this._inertiaBuffer.push({time:a.o.now(),settings:u})}_drainInertiaBuffer(){const u=this._inertiaBuffer,f=a.o.now();for(;u.length>0&&f-u[0].time>160;)u.shift()}_onMoveEnd(u){if(this._map._prefersReducedMotion()||(this._drainInertiaBuffer(),this._inertiaBuffer.length<2))return;const f={zoom:0,bearing:0,pitch:0,pan:new a.P(0,0),pinchAround:void 0,around:void 0};for(const{settings:T}of this._inertiaBuffer)f.zoom+=T.zoomDelta||0,f.bearing+=T.bearingDelta||0,f.pitch+=T.pitchDelta||0,T.panDelta&&f.pan._add(T.panDelta),T.around&&(f.around=T.around),T.pinchAround&&(f.pinchAround=T.pinchAround);const v=this._inertiaBuffer[this._inertiaBuffer.length-1].time-this._inertiaBuffer[0].time,S={};if(f.pan.mag()){const T=zd(f.pan.mag(),v,Object.assign({},JS,u||{}));S.offset=f.pan.mult(T.amount/f.pan.mag()),S.center=this._map.transform.center,Mg(S,T)}if(f.zoom){const T=zd(f.zoom,v,eN);S.zoom=this._map.transform.zoom+T.amount,Mg(S,T)}if(f.bearing){const T=zd(f.bearing,v,sm);S.bearing=this._map.transform.bearing+a.aA(T.amount,-179,179),Mg(S,T)}if(f.pitch){const T=zd(f.pitch,v,tN);S.pitch=this._map.transform.pitch+T.amount,Mg(S,T)}if(S.zoom||S.bearing){const T=f.pinchAround===void 0?f.around:f.pinchAround;S.around=T?this._map.unproject(T):this._map.getCenter()}return this.clear(),S.noMoveStart=!0,S}}function Mg(x,u){(!x.duration||x.durationf.unproject(B)),L=T.reduce((B,q,G,ee)=>B.add(q.div(ee.length)),new a.P(0,0));super(u,{points:T,point:L,lngLats:E,lngLat:f.unproject(L),originalEvent:v}),this._defaultPrevented=!1}}class nN extends a.z{preventDefault(){this._defaultPrevented=!0}get defaultPrevented(){return this._defaultPrevented}constructor(u,f){super("wheel",{originalEvent:f}),this._defaultPrevented=!1}}class vb{constructor(u,f){this._map=u,this._clickTolerance=f.clickTolerance}reset(){this._mousedownPos=void 0}wheel(u){return this._firePreventable(new nN(this._map,u))}mousedown(u,f){return this._mousedownPos=f,this._firePreventable(new ac(u.type,this._map,u))}mouseup(u){this._map.fire(new ac(u.type,this._map,u))}preclick(u){const f=new MouseEvent("preclick",u);this._map.fire(new ac(f.type,this._map,f))}click(u,f){this._mousedownPos&&this._mousedownPos.dist(f)>=this._clickTolerance||(this.preclick(u),this._map.fire(new ac(u.type,this._map,u)))}dblclick(u){return this._firePreventable(new ac(u.type,this._map,u))}mouseover(u){this._map.fire(new ac(u.type,this._map,u))}mouseout(u){this._map.fire(new ac(u.type,this._map,u))}touchstart(u){return this._firePreventable(new Kf(u.type,this._map,u))}touchmove(u){this._map.fire(new Kf(u.type,this._map,u))}touchend(u){this._map.fire(new Kf(u.type,this._map,u))}touchcancel(u){this._map.fire(new Kf(u.type,this._map,u))}_firePreventable(u){if(this._map.fire(u),u.defaultPrevented)return{}}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class sN{constructor(u){this._map=u}reset(){this._delayContextMenu=!1,this._contextMenuEvent=void 0}mousemove(u){this._map.fire(new ac(u.type,this._map,u))}mousedown(){this._delayContextMenu=!0}mouseup(){this._delayContextMenu=!1,this._contextMenuEvent&&(this._map.fire(new ac("contextmenu",this._map,this._contextMenuEvent)),delete this._contextMenuEvent)}contextmenu(u){this._delayContextMenu?this._contextMenuEvent=u:this._map.fire(new ac(u.type,this._map,u)),this._map.listens("contextmenu")&&u.preventDefault()}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class _b{constructor(u,f){this._map=u,this._el=u.getCanvasContainer(),this._container=u.getContainer(),this._clickTolerance=f.clickTolerance||1}isEnabled(){return!!this._enabled}isActive(){return!!this._active}enable(){this.isEnabled()||(this._enabled=!0)}disable(){this.isEnabled()&&(this._enabled=!1)}mousedown(u,f){this.isEnabled()&&u.shiftKey&&u.button===0&&(W(),this._startPos=this._lastPos=f,this._active=!0)}mousemoveWindow(u,f){if(!this._active)return;const v=f,S=this._startPos,T=this._lastPos;if(!S||!T||T.equals(v)||!this._box&&v.dist(S){this._box&&(this._box.style.transform=`translate(${E}px,${B}px)`,this._box.style.width=L-E+"px",this._box.style.height=q-B+"px")})}mouseupWindow(u,f){if(!this._active)return;const v=this._startPos,S=f;if(v&&u.button===0){if(this.reset(),Q(),v.x!==S.x||v.y!==S.y)return this._map.fire(new a.z("boxzoomend",{originalEvent:u})),{cameraAnimation:T=>T.fitScreenCoordinates(v,S,this._map.getBearing(),{linear:!1})};this._fireEvent("boxzoomcancel",u)}}keydown(u){this._active&&u.keyCode===27&&(this.reset(),this._fireEvent("boxzoomcancel",u))}blur(){this.reset()}reset(){this._active=!1,this._container.classList.remove("mapboxgl-crosshair"),this._box&&(this._box.remove(),this._box=null),V(),delete this._startPos,delete this._lastPos}_fireEvent(u,f){return this._map.fire(new a.z(u,{originalEvent:f}))}}function bb(x,u){const f={};for(let v=0;vthis.numTouches)&&(this.aborted=!0),this.aborted||(this.startTime===0&&(this.startTime=u.timeStamp),v.length===this.numTouches&&(this.centroid=function(S){const T=new a.P(0,0);for(const E of S)T._add(E);return T.div(S.length)}(f),this.touches=bb(v,f)))}touchmove(u,f,v){if(this.aborted||!this.centroid)return;const S=bb(v,f);for(const T in this.touches){const E=S[T];(!E||E.dist(this.touches[T])>30)&&(this.aborted=!0)}}touchend(u,f,v){if((!this.centroid||u.timeStamp-this.startTime>500)&&(this.aborted=!0),v.length===0){const S=!this.aborted&&this.centroid;if(this.reset(),S)return S}}}class wb{constructor(u){this.singleTap=new KE(u),this.numTaps=u.numTaps,this.reset()}reset(){this.lastTime=1/0,this.lastTap=void 0,this.count=0,this.singleTap.reset()}touchstart(u,f,v){this.singleTap.touchstart(u,f,v)}touchmove(u,f,v){this.singleTap.touchmove(u,f,v)}touchend(u,f,v){const S=this.singleTap.touchend(u,f,v);if(S){const T=u.timeStamp-this.lastTime<500,E=!this.lastTap||this.lastTap.dist(S)<30;if(T&&E||this.reset(),this.count++,this.lastTime=u.timeStamp,this.lastTap=S,this.count===this.numTaps)return this.reset(),S}}}class ZE{constructor(){this._zoomIn=new wb({numTouches:1,numTaps:2}),this._zoomOut=new wb({numTouches:2,numTaps:1}),this.reset()}reset(){this._active=!1,this._zoomIn.reset(),this._zoomOut.reset()}touchstart(u,f,v){this._zoomIn.touchstart(u,f,v),this._zoomOut.touchstart(u,f,v)}touchmove(u,f,v){this._zoomIn.touchmove(u,f,v),this._zoomOut.touchmove(u,f,v)}touchend(u,f,v){const S=this._zoomIn.touchend(u,f,v),T=this._zoomOut.touchend(u,f,v);return S?(this._active=!0,u.preventDefault(),setTimeout(()=>this.reset(),0),{cameraAnimation:E=>E.easeTo({duration:300,zoom:E.getZoom()+1,around:E.unproject(S)},{originalEvent:u})}):T?(this._active=!0,u.preventDefault(),setTimeout(()=>this.reset(),0),{cameraAnimation:E=>E.easeTo({duration:300,zoom:E.getZoom()-1,around:E.unproject(T)},{originalEvent:u})}):void 0}touchcancel(){this.reset()}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}const YE={0:1,2:2},iN={Control:"ctrlKey",Alt:"altKey",Shift:"shiftKey",Meta:"metaKey"};class jb{constructor(u){this.reset(),this._clickTolerance=u.clickTolerance||1}blur(){this.reset()}reset(){this._active=!1,this._moved=!1,this._lastPoint=void 0,this._eventButton=void 0}_correctButton(u,f){return!1}_move(u,f){return{}}mousedown(u,f){if(this._lastPoint)return;const v=ie(u);this._correctButton(u,v)&&(this._lastPoint=f,this._eventButton=v)}mousemoveWindow(u,f){const v=this._lastPoint;if(v){if(u.preventDefault(),this._eventButton!=null&&function(S,T){const E=YE[T];return S.buttons===void 0||(S.buttons&E)!==E}(u,this._eventButton))this.reset();else if(this._moved||!(f.dist(v)0&&(this._active=!0);const S=bb(v,f),T=new a.P(0,0),E=new a.P(0,0);let L=0;for(const q in S){const G=S[q],ee=this._touches[q];ee&&(T._add(G),E._add(G.sub(ee)),L++,S[q]=G)}if(this._touches=S,L{this._alertContainer.classList.remove("mapboxgl-touch-pan-blocker-show"),this._alertContainer.removeAttribute("role")},500)}}class Sb{constructor(){this.reset()}reset(){this._active=!1,this._firstTwoTouches=void 0}_start(u){}_move(u,f,v){return{}}touchstart(u,f,v){this._firstTwoTouches||v.length<2||(this._firstTwoTouches=[v[0].identifier,v[1].identifier],this._start([f[0],f[1]]))}touchmove(u,f,v){const S=this._firstTwoTouches;if(!S)return;u.preventDefault();const[T,E]=S,L=lv(v,f,T),B=lv(v,f,E);if(!L||!B)return;const q=this._aroundCenter?null:L.add(B).div(2);return this._move([L,B],q,u)}touchend(u,f,v){if(!this._firstTwoTouches)return;const[S,T]=this._firstTwoTouches,E=lv(v,f,S),L=lv(v,f,T);E&&L||(this._active&&Q(),this.reset())}touchcancel(){this.reset()}enable(u){this._enabled=!0,this._aroundCenter=!!u&&u.around==="center"}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}function lv(x,u,f){for(let v=0;vMath.abs(x.x)}class E4 extends Sb{constructor(u){super(),this._map=u}reset(){super.reset(),this._valid=void 0,this._firstMove=void 0,this._lastPoints=void 0}_start(u){this._lastPoints=u,Nb(u[0].sub(u[1]))&&(this._valid=!1)}_move(u,f,v){const S=this._lastPoints;if(!S)return;const T=u[0].sub(S[0]),E=u[1].sub(S[1]);return this._map._cooperativeGestures&&!a.eU()&&v.touches.length<3||(this._valid=this.gestureBeginsVertically(T,E,v.timeStamp),!this._valid)?void 0:(this._lastPoints=u,this._active=!0,{pitchDelta:(T.y+E.y)/2*-.5})}gestureBeginsVertically(u,f,v){if(this._valid!==void 0)return this._valid;const S=u.mag()>=2,T=f.mag()>=2;if(!S&&!T)return;if(!S||!T)return this._firstMove==null&&(this._firstMove=v),v-this._firstMove<100&&void 0;const E=u.y>0==f.y>0;return Nb(u)&&Nb(f)&&E}}const A4={panStep:100,bearingStep:15,pitchStep:10};class P4{constructor(){const u=A4;this._panStep=u.panStep,this._bearingStep=u.bearingStep,this._pitchStep=u.pitchStep,this._rotationDisabled=!1}blur(){this.reset()}reset(){this._active=!1}keydown(u){if(u.altKey||u.ctrlKey||u.metaKey)return;let f=0,v=0,S=0,T=0,E=0;switch(u.keyCode){case 61:case 107:case 171:case 187:f=1;break;case 189:case 109:case 173:f=-1;break;case 37:u.shiftKey?v=-1:(u.preventDefault(),T=-1);break;case 39:u.shiftKey?v=1:(u.preventDefault(),T=1);break;case 38:u.shiftKey?S=1:(u.preventDefault(),E=-1);break;case 40:u.shiftKey?S=-1:(u.preventDefault(),E=1);break;default:return}return this._rotationDisabled&&(v=0,S=0),{cameraAnimation:L=>{const B=L.getZoom();L.easeTo({duration:300,easeId:"keyboardHandler",easing:cv,zoom:f?Math.round(B)+f*(u.shiftKey?2:1):B,bearing:L.getBearing()+v*this._bearingStep,pitch:L.getPitch()+S*this._pitchStep,offset:[-T*this._panStep,-E*this._panStep],center:L.getCenter()},{originalEvent:u})}}}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}disableRotation(){this._rotationDisabled=!0}enableRotation(){this._rotationDisabled=!1}}function cv(x){return x*(2-x)}const lN=4.000244140625,cN=1/450;class Cb{constructor(u,f){this._map=u,this._el=u.getCanvasContainer(),this._handler=f,this._delta=0,this._lastDelta=0,this._defaultZoomRate=.01,this._wheelZoomRate=cN,a.aY(["_onTimeout","_addScrollZoomBlocker","_showBlockerAlert"],this)}setZoomRate(u){this._defaultZoomRate=u}setWheelZoomRate(u){this._wheelZoomRate=u}isEnabled(){return!!this._enabled}isActive(){return this._active||this._finishTimeout!==void 0}isZooming(){return!!this._zooming}enable(u){this.isEnabled()||(this._enabled=!0,this._aroundCenter=!!u&&u.around==="center",this._map._cooperativeGestures&&this._addScrollZoomBlocker())}disable(){this.isEnabled()&&(this._enabled=!1,this._map._cooperativeGestures&&(clearTimeout(this._alertTimer),this._alertContainer.remove()))}wheel(u){if(!this.isEnabled())return;if(this._map._cooperativeGestures){if(!(u.ctrlKey||u.metaKey||this.isZooming()||a.eU()))return void this._showBlockerAlert();this._alertContainer.style.visibility!=="hidden"&&(this._alertContainer.style.visibility="hidden",clearTimeout(this._alertTimer))}let f=u.deltaMode===WheelEvent.DOM_DELTA_LINE?40*u.deltaY:u.deltaY;const v=a.o.now(),S=v-(this._lastWheelEventTime||0);this._lastWheelEventTime=v,f!==0&&f%lN==0?this._type="wheel":f!==0&&Math.abs(f)<4?this._type="trackpad":S>400?(this._type=null,this._lastValue=f,this._timeout=window.setTimeout(this._onTimeout,40,u)):this._type||(this._type=Math.abs(S*f)<200?"trackpad":"wheel",this._timeout&&(clearTimeout(this._timeout),this._timeout=null,f+=this._lastValue)),u.shiftKey&&f&&(f/=4),this._type&&(this._lastWheelEvent=u,this._delta-=f,this._active||this._start(u)),u.preventDefault()}_onTimeout(u){this._type="wheel",this._delta-=this._lastValue,this._active||this._start(u)}_start(u){if(!this._delta)return;this._frameId&&(this._frameId=null),this._active=!0,this.isZooming()||(this._zooming=!0),this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout);const f=te(this._el,u);this._aroundPoint=this._aroundCenter?this._map.transform.centerPoint:f,this._aroundCoord=this._map.transform.pointCoordinate3D(this._aroundPoint),this._targetZoom=void 0,this._frameId||(this._frameId=!0,this._handler._triggerRenderFrame())}renderFrame(){if(!this._frameId||(this._frameId=null,!this.isActive()))return;const u=this._map.transform;this._type==="wheel"&&u.projection.wrap&&(u._center.lng>=180||u._center.lng<=-180)&&(this._prevEase=null,this._easing=null,this._lastWheelEvent=null,this._lastWheelEventTime=0);const f=()=>u._terrainEnabled()&&this._aroundCoord?u.computeZoomRelativeTo(this._aroundCoord):u.zoom;if(this._delta!==0){const q=this._type==="wheel"&&Math.abs(this._delta)>lN?this._wheelZoomRate:this._defaultZoomRate;let G=2/(1+Math.exp(-Math.abs(this._delta*q)));this._delta<0&&G!==0&&(G=1/G);const ee=f(),J=Math.pow(2,ee),re=typeof this._targetZoom=="number"?u.zoomScale(this._targetZoom):J;this._targetZoom=Math.min(u.maxZoom,Math.max(u.minZoom,u.scaleZoom(re*G))),this._type==="wheel"&&(this._startZoom=ee,this._easing=this._smoothOutEasing(200)),this._lastDelta=this._delta,this._delta=0}const v=typeof this._targetZoom=="number"?this._targetZoom:f(),S=this._startZoom,T=this._easing;let E,L=!1;if(this._type==="wheel"&&S&&T){const q=Math.min((a.o.now()-this._lastWheelEventTime)/200,1),G=T(q);E=a.ak(S,v,G),q<1?this._frameId||(this._frameId=!0):L=!0}else E=v,L=!0;this._active=!0,L&&(this._active=!1,this._finishTimeout=window.setTimeout(()=>{this._zooming=!1,this._handler._triggerRenderFrame(),delete this._targetZoom,delete this._finishTimeout},200));let B=E-f();return B*this._lastDelta<0&&(B=0),{noInertia:!0,needsRenderFrame:!L,zoomDelta:B,around:this._aroundPoint,aroundCoord:this._aroundCoord,originalEvent:this._lastWheelEvent}}_smoothOutEasing(u){let f=a.eV;if(this._prevEase){const v=this._prevEase,S=(a.o.now()-v.start)/v.duration,T=v.easing(S+.01)-v.easing(S),E=.27/Math.sqrt(T*T+1e-4)*.01,L=Math.sqrt(.0729-E*E);f=a.eT(E,L,.25,1)}return this._prevEase={start:a.o.now(),duration:u,easing:f},f}blur(){this.reset()}reset(){this._active=!1}_addScrollZoomBlocker(){this._map&&!this._alertContainer&&(this._alertContainer=A("div","mapboxgl-scroll-zoom-blocker",this._map._container),this._alertContainer.textContent=/(Mac|iPad)/i.test(navigator.userAgent)?this._map._getUIString("ScrollZoomBlocker.CmdMessage"):this._map._getUIString("ScrollZoomBlocker.CtrlMessage"),this._alertContainer.style.fontSize=`${Math.max(10,Math.min(24,Math.floor(.05*this._el.clientWidth)))}px`)}_showBlockerAlert(){this._alertContainer.style.visibility="visible",this._alertContainer.classList.add("mapboxgl-scroll-zoom-blocker-show"),this._alertContainer.setAttribute("role","alert"),clearTimeout(this._alertTimer),this._alertTimer=window.setTimeout(()=>{this._alertContainer.classList.remove("mapboxgl-scroll-zoom-blocker-show"),this._alertContainer.removeAttribute("role")},200)}}class Oh{constructor(u,f){this._clickZoom=u,this._tapZoom=f}enable(){this._clickZoom.enable(),this._tapZoom.enable()}disable(){this._clickZoom.disable(),this._tapZoom.disable()}isEnabled(){return this._clickZoom.isEnabled()&&this._tapZoom.isEnabled()}isActive(){return this._clickZoom.isActive()||this._tapZoom.isActive()}}class kb{constructor(){this.reset()}reset(){this._active=!1}blur(){this.reset()}dblclick(u,f){return u.preventDefault(),{cameraAnimation:v=>{v.easeTo({duration:300,zoom:v.getZoom()+(u.shiftKey?-1:1),around:v.unproject(f)},{originalEvent:u})}}}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class za{constructor(){this._tap=new wb({numTouches:1,numTaps:1}),this.reset()}reset(){this._active=!1,this._swipePoint=void 0,this._swipeTouch=0,this._tapTime=0,this._tap.reset()}touchstart(u,f,v){this._swipePoint||(this._tapTime&&u.timeStamp-this._tapTime>500&&this.reset(),this._tapTime?v.length>0&&(this._swipePoint=f[0],this._swipeTouch=v[0].identifier):this._tap.touchstart(u,f,v))}touchmove(u,f,v){if(this._tapTime){if(this._swipePoint){if(v[0].identifier!==this._swipeTouch)return;const S=f[0],T=S.y-this._swipePoint.y;return this._swipePoint=S,u.preventDefault(),this._active=!0,{zoomDelta:T/128}}}else this._tap.touchmove(u,f,v)}touchend(u,f,v){this._tapTime?this._swipePoint&&v.length===0&&this.reset():this._tap.touchend(u,f,v)&&(this._tapTime=u.timeStamp)}touchcancel(){this.reset()}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class Bd{constructor(u,f,v){this._el=u,this._mousePan=f,this._touchPan=v}enable(u){this._inertiaOptions=u||{},this._mousePan.enable(),this._touchPan.enable(),this._el.classList.add("mapboxgl-touch-drag-pan")}disable(){this._mousePan.disable(),this._touchPan.disable(),this._el.classList.remove("mapboxgl-touch-drag-pan")}isEnabled(){return this._mousePan.isEnabled()&&this._touchPan.isEnabled()}isActive(){return this._mousePan.isActive()||this._touchPan.isActive()}}class uv{constructor(u,f,v){this._pitchWithRotate=u.pitchWithRotate,this._mouseRotate=f,this._mousePitch=v}enable(){this._mouseRotate.enable(),this._pitchWithRotate&&this._mousePitch.enable()}disable(){this._mouseRotate.disable(),this._mousePitch.disable()}isEnabled(){return this._mouseRotate.isEnabled()&&(!this._pitchWithRotate||this._mousePitch.isEnabled())}isActive(){return this._mouseRotate.isActive()||this._mousePitch.isActive()}}class Tb{constructor(u,f,v,S){this._el=u,this._touchZoom=f,this._touchRotate=v,this._tapDragZoom=S,this._rotationDisabled=!1,this._enabled=!0}enable(u){this._touchZoom.enable(u),this._rotationDisabled||this._touchRotate.enable(u),this._tapDragZoom.enable(),this._el.classList.add("mapboxgl-touch-zoom-rotate")}disable(){this._touchZoom.disable(),this._touchRotate.disable(),this._tapDragZoom.disable(),this._el.classList.remove("mapboxgl-touch-zoom-rotate")}isEnabled(){return this._touchZoom.isEnabled()&&(this._rotationDisabled||this._touchRotate.isEnabled())&&this._tapDragZoom.isEnabled()}isActive(){return this._touchZoom.isActive()||this._touchRotate.isActive()||this._tapDragZoom.isActive()}disableRotation(){this._rotationDisabled=!0,this._touchRotate.disable()}enableRotation(){this._rotationDisabled=!1,this._touchZoom.isEnabled()&&this._touchRotate.enable()}}const dv=x=>x.zoom||x.drag||x.pitch||x.rotate;class I4 extends a.z{}class hv{constructor(){this.constants=[1,1,.01],this.radius=0}setup(u,f){const v=a.av([],f,u);this.radius=a.ag(v[2]<0?a.eX([],v,this.constants):[v[0],v[1],0])}projectRay(u){a.eX(u,u,this.constants),a.aw(u,u),a.eY(u,u,this.constants);const f=a.c5([],u,this.radius);if(f[2]>0){const v=a.c5([],[0,0,1],a.bJ(f,[0,0,1])),S=a.c5([],a.aw([],[f[0],f[1],0]),this.radius),T=a.d8([],f,a.c5([],a.av([],a.d8([],S,v),f),2));f[0]=T[0],f[1]=T[1]}return f}}function Eb(x){return x.panDelta&&x.panDelta.mag()||x.zoomDelta||x.bearingDelta||x.pitchDelta}class M4{constructor(u,f){this._map=u,this._el=this._map.getCanvasContainer(),this._handlers=[],this._handlersById={},this._changes=[],this._inertia=new rN(u),this._bearingSnap=f.bearingSnap,this._previousActiveHandlers={},this._trackingEllipsoid=new hv,this._dragOrigin=null,this._eventsInProgress={},this._addDefaultHandlers(f),a.aY(["handleEvent","handleWindowEvent"],this);const v=this._el;this._listeners=[[v,"touchstart",{passive:!0}],[v,"touchmove",{passive:!1}],[v,"touchend",void 0],[v,"touchcancel",void 0],[v,"mousedown",void 0],[v,"mousemove",void 0],[v,"mouseup",void 0],[document,"mousemove",{capture:!0}],[document,"mouseup",void 0],[v,"mouseover",void 0],[v,"mouseout",void 0],[v,"dblclick",void 0],[v,"click",void 0],[v,"keydown",{capture:!1}],[v,"keyup",void 0],[v,"wheel",{passive:!1}],[v,"contextmenu",void 0],[window,"blur",void 0]];for(const[S,T,E]of this._listeners){const L=S===document?this.handleWindowEvent:this.handleEvent;S.addEventListener(T,L,E)}}destroy(){for(const[u,f,v]of this._listeners){const S=u===document?this.handleWindowEvent:this.handleEvent;u.removeEventListener(f,S,v)}}_addDefaultHandlers(u){const f=this._map,v=f.getCanvasContainer();this._add("mapEvent",new vb(f,u));const S=f.boxZoom=new _b(f,u);this._add("boxZoom",S);const T=new ZE,E=new kb;f.doubleClickZoom=new Oh(E,T),this._add("tapZoom",T),this._add("clickZoom",E);const L=new za;this._add("tapDragZoom",L);const B=f.touchPitch=new E4(f);this._add("touchPitch",B);const q=new aN(u),G=new oN(u);f.dragRotate=new uv(u,q,G),this._add("mouseRotate",q,["mousePitch"]),this._add("mousePitch",G,["mouseRotate"]);const ee=new XE(u),J=new QE(f,u);f.dragPan=new Bd(v,ee,J),this._add("mousePan",ee),this._add("touchPan",J,["touchZoom","touchRotate"]);const re=new Hi,oe=new T4;f.touchZoomRotate=new Tb(v,oe,re,L),this._add("touchRotate",re,["touchPan","touchZoom"]),this._add("touchZoom",oe,["touchPan","touchRotate"]),this._add("blockableMapEvent",new sN(f));const se=f.scrollZoom=new Cb(f,this);this._add("scrollZoom",se,["mousePan"]);const me=f.keyboard=new P4;this._add("keyboard",me);for(const fe of["boxZoom","doubleClickZoom","tapDragZoom","touchPitch","dragRotate","dragPan","touchZoomRotate","scrollZoom","keyboard"])u.interactive&&u[fe]&&f[fe].enable(u[fe])}_add(u,f,v){this._handlers.push({handlerName:u,handler:f,allowed:v}),this._handlersById[u]=f}stop(u){if(!this._updatingCamera){for(const{handler:f}of this._handlers)f.reset();this._inertia.clear(),this._fireEvents({},{},u),this._changes=[],this._originalZoom=void 0}}isActive(){for(const{handler:u}of this._handlers)if(u.isActive())return!0;return!1}isZooming(){return!!this._eventsInProgress.zoom||this._map.scrollZoom.isZooming()}isRotating(){return!!this._eventsInProgress.rotate}isMoving(){return!!dv(this._eventsInProgress)||this.isZooming()}_isDragging(){return!!this._eventsInProgress.drag}_blockedByActive(u,f,v){for(const S in u)if(S!==v&&(!f||f.indexOf(S)<0))return!0;return!1}handleWindowEvent(u){this.handleEvent(u,`${u.type}Window`)}_getMapTouches(u){const f=[];for(const v of u)this._el.contains(v.target)&&f.push(v);return f}handleEvent(u,f){this._updatingCamera=!0;const v=u.type==="renderFrame",S=v?void 0:u,T={needsRenderFrame:!1},E={},L={},B=u.touches?this._getMapTouches(u.touches):void 0,q=B?X(this._el,B):v?void 0:te(this._el,u);for(const{handlerName:J,handler:re,allowed:oe}of this._handlers){if(!re.isEnabled())continue;let se;this._blockedByActive(L,oe,J)?re.reset():re[f||u.type]&&(se=re[f||u.type](u,q,B),this.mergeHandlerResult(T,E,se,J,S),se&&se.needsRenderFrame&&this._triggerRenderFrame()),(se||re.isActive())&&(L[J]=re)}const G={};for(const J in this._previousActiveHandlers)L[J]||(G[J]=S);this._previousActiveHandlers=L,(Object.keys(G).length||Eb(T))&&(this._changes.push([T,E,G]),this._triggerRenderFrame()),(Object.keys(L).length||Eb(T))&&this._map._stop(!0),this._updatingCamera=!1;const{cameraAnimation:ee}=T;ee&&(this._inertia.clear(),this._fireEvents({},{},!0),this._changes=[],ee(this._map))}mergeHandlerResult(u,f,v,S,T){if(!v)return;Object.assign(u,v);const E={handlerName:S,originalEvent:v.originalEvent||T};v.zoomDelta!==void 0&&(f.zoom=E),v.panDelta!==void 0&&(f.drag=E),v.pitchDelta!==void 0&&(f.pitch=E),v.bearingDelta!==void 0&&(f.rotate=E)}_applyChanges(){const u={},f={},v={};for(const[S,T,E]of this._changes)S.panDelta&&(u.panDelta=(u.panDelta||new a.P(0,0))._add(S.panDelta)),S.zoomDelta&&(u.zoomDelta=(u.zoomDelta||0)+S.zoomDelta),S.bearingDelta&&(u.bearingDelta=(u.bearingDelta||0)+S.bearingDelta),S.pitchDelta&&(u.pitchDelta=(u.pitchDelta||0)+S.pitchDelta),S.around!==void 0&&(u.around=S.around),S.aroundCoord!==void 0&&(u.aroundCoord=S.aroundCoord),S.pinchAround!==void 0&&(u.pinchAround=S.pinchAround),S.noInertia&&(u.noInertia=S.noInertia),Object.assign(f,T),Object.assign(v,E);this._updateMapTransform(u,f,v),this._changes=[]}_updateMapTransform(u,f,v){const S=this._map,T=S.transform,E=Ne=>[Ne.x,Ne.y,Ne.z];if((Ne=>{const Ae=this._eventsInProgress.drag;return Ae&&!this._handlersById[Ae.handlerName].isActive()})()&&!Eb(u)){const Ne=T.zoom;T.cameraElevationReference="sea",this._originalZoom!=null&&T._orthographicProjectionAtLowPitch&&T.projection.name!=="globe"&&T.pitch===0?(T.cameraElevationReference="ground",T.zoom=this._originalZoom):(T.recenterOnTerrain(),T.cameraElevationReference="ground"),Ne!==T.zoom&&this._map._update(!0)}if(T._isCameraConstrained&&S._stop(!0),!Eb(u))return void this._fireEvents(f,v,!0);let{panDelta:L,zoomDelta:B,bearingDelta:q,pitchDelta:G,around:ee,aroundCoord:J,pinchAround:re}=u;T._isCameraConstrained&&(B>0&&(B=0),T._isCameraConstrained=!1),re!==void 0&&(ee=re),(B||(Ne=>f[Ne]&&!this._eventsInProgress[Ne])("drag"))&&ee&&(this._dragOrigin=E(T.pointCoordinate3D(ee)),this._originalZoom=T.zoom,this._trackingEllipsoid.setup(T._camera.position,this._dragOrigin)),T.cameraElevationReference="sea",S._stop(!0),ee=ee||S.transform.centerPoint,q&&(T.bearing+=q),G&&(T.pitch+=G),T._updateCameraState();const oe=[0,0,0];if(L)if(T.projection.name==="mercator"){const Ne=this._trackingEllipsoid.projectRay(T.screenPointToMercatorRay(ee).dir),Ae=this._trackingEllipsoid.projectRay(T.screenPointToMercatorRay(ee.sub(L)).dir);oe[0]=Ae[0]-Ne[0],oe[1]=Ae[1]-Ne[1]}else{const Ne=T.pointCoordinate(ee);if(T.projection.name==="globe"){L=L.rotate(-T.angle);const Ae=T._pixelsPerMercatorPixel/T.worldSize;oe[0]=-L.x*a.eW(a.a$(Ne.y))*Ae,oe[1]=-L.y*a.eW(T.center.lat)*Ae}else{const Ae=T.pointCoordinate(ee.sub(L));Ne&&Ae&&(oe[0]=Ae.x-Ne.x,oe[1]=Ae.y-Ne.y)}}const se=T.zoom,me=[0,0,0];if(B){const Ne=E(J||T.pointCoordinate3D(ee)),Ae={dir:a.aw([],a.av([],Ne,T._camera.position))};if(Ae.dir[2]<0){const Te=T.zoomDeltaToMovement(Ne,B);a.c5(me,Ae.dir,Te)}}const fe=a.d8(oe,oe,me);T._translateCameraConstrained(fe),B&&Math.abs(T.zoom-se)>1e-4&&T.recenterOnTerrain(),T.cameraElevationReference="ground",this._map._update(),u.noInertia||this._inertia.record(u),this._fireEvents(f,v,!0)}_fireEvents(u,f,v){const S=dv(this._eventsInProgress),T=dv(u),E={};for(const G in u){const{originalEvent:ee}=u[G];this._eventsInProgress[G]||(E[`${G}start`]=ee),this._eventsInProgress[G]=u[G]}!S&&T&&this._fireEvent("movestart",T.originalEvent);for(const G in E)this._fireEvent(G,E[G]);T&&this._fireEvent("move",T.originalEvent);for(const G in u){const{originalEvent:ee}=u[G];this._fireEvent(G,ee)}const L={};let B;for(const G in this._eventsInProgress){const{handlerName:ee,originalEvent:J}=this._eventsInProgress[G];this._handlersById[ee].isActive()||(delete this._eventsInProgress[G],B=f[ee]||J,L[`${G}end`]=B)}for(const G in L)this._fireEvent(G,L[G]);const q=dv(this._eventsInProgress);if(v&&(S||T)&&!q){this._updatingCamera=!0;const G=this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions),ee=J=>J!==0&&-this._bearingSnap{this._frameId=void 0,this.handleEvent(new I4("renderFrame",{timeStamp:u})),this._applyChanges()})}_triggerRenderFrame(){this._frameId===void 0&&(this._frameId=this._requestFrame())}}const Ab="map.setFreeCameraOptions(...) and map.getFreeCameraOptions() are not yet supported for non-mercator projections.";class uN extends a.E{constructor(u,f){super(),this._moving=!1,this._zooming=!1,this.transform=u,this._bearingSnap=f.bearingSnap,this._respectPrefersReducedMotion=f.respectPrefersReducedMotion!==!1,a.aY(["_renderFrameCallback"],this)}getCenter(){return new a.aT(this.transform.center.lng,this.transform.center.lat)}setCenter(u,f){return this.jumpTo({center:u},f)}panBy(u,f,v){return u=a.P.convert(u).mult(-1),this.panTo(this.transform.center,Object.assign({offset:u},f),v)}panTo(u,f,v){return this.easeTo(Object.assign({center:u},f),v)}getZoom(){return this.transform.zoom}setZoom(u,f){return this.jumpTo({zoom:u},f),this}zoomTo(u,f,v){return this.easeTo(Object.assign({zoom:u},f),v)}zoomIn(u,f){return this.zoomTo(this.getZoom()+1,u,f),this}zoomOut(u,f){return this.zoomTo(this.getZoom()-1,u,f),this}getBearing(){return this.transform.bearing}setBearing(u,f){return this.jumpTo({bearing:u},f),this}getPadding(){return this.transform.padding}setPadding(u,f){return this.jumpTo({padding:u},f),this}rotateTo(u,f,v){return this.easeTo(Object.assign({bearing:u},f),v)}resetNorth(u,f){return this.rotateTo(0,Object.assign({duration:1e3},u),f),this}resetNorthPitch(u,f){return this.easeTo(Object.assign({bearing:0,pitch:0,duration:1e3},u),f),this}snapToNorth(u,f){return Math.abs(this.getBearing())u.aspect?v/(2*Math.tan(.5*u.fovX)*u.aspect):S/(2*Math.tan(.5*u.fovY)*u.aspect)}_cameraForBoundsOnGlobe(u,f,v,S,T,E){const L=u.clone(),B=this._extendCameraOptions(E);L.bearing=S,L.pitch=T;const q=a.aT.convert(f),G=a.aT.convert(v),ee=.5*(q.lat+G.lat),J=.5*(q.lng+G.lng),re=a.eZ(ee,J),oe=a.aw([],re),se=a.aw([],a.bI([],oe,[0,1,0])),me=a.bI([],se,oe),fe=[se[0],se[1],se[2],0,me[0],me[1],me[2],0,oe[0],oe[1],oe[2],0,0,0,0,1],Ne=[re,a.eZ(q.lat,q.lng),a.eZ(G.lat,q.lng),a.eZ(G.lat,G.lng),a.eZ(q.lat,G.lng),a.eZ(ee,q.lng),a.eZ(ee,G.lng),a.eZ(q.lat,J),a.eZ(G.lat,J)];let Ae=a.d9.fromPoints(Ne.map(kt=>[a.bJ(se,kt),a.bJ(me,kt),a.bJ(oe,kt)]));const Te=a.af([],Ae.center,fe);a.e_(Te)===0&&a.e$(Te,0,0,1),a.aw(Te,Te),a.c5(Te,Te,a.aD),L.center=a.f0(Te);const Ze=L.getWorldToCameraMatrix(),$e=a.bl(new Float64Array(16),Ze);Ae=a.d9.applyTransform(Ae,a.aB([],Ze,fe));const He=this._extendAABB(Ae,L,B,S);if(!He)return void a.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");Ae=He,a.af(Te,Te,Ze);const ze=.5*(Ae.max[2]-Ae.min[2]),De=this._minimumAABBFrustumDistance(L,Ae),Qe=a.c5([],[0,0,1],ze),ht=a.d8(Qe,Te,Qe),ot=De+(L.pitch===0?0:a.bG(Te,ht)),Tt=L.globeCenterInViewSpace,At=a.av([],Te,[Tt[0],Tt[1],Tt[2]]);a.aw(At,At),a.c5(At,At,ot);const Bt=a.d8([],Te,At);a.af(Bt,Bt,$e);const or=a.eM/a.aD,wt=a.ag(Bt),st=a.cf(Math.max(wt*or-a.eM,Number.EPSILON),0),Mt=Math.min(L.zoomFromMercatorZAdjusted(st),B.maxZoom);return Mt>.5*(a.c_+a.cL)?(L.setProjection({name:"mercator"}),L.zoom=Mt,this._cameraForBounds(L,f,v,S,T,E)):{center:L.center,zoom:Mt,bearing:S,pitch:T}}_extendAABB(u,f,v,S){const T=.5*((v.padding.left||0)+(v.padding.right||0)),E=.5*((v.padding.top||0)+(v.padding.bottom||0)),L=E,B=T,q=T,G=E,ee=f.width-(B+q),J=f.height-(L+G),re=a.av([],u.max,u.min),oe=Math.min(ee/re[0],J/re[1]),se=Math.min(f.scaleZoom(f.scale*oe),v.maxZoom);if(isNaN(se))return null;const me=f.scale/f.zoomScale(se),fe=new a.d9([u.min[0]-B*me,u.min[1]-G*me,u.min[2]],[u.max[0]+q*me,u.max[1]+L*me,u.max[2]]),Ne=(typeof v.offset.x=="number"&&typeof v.offset.y=="number"?new a.P(v.offset.x,v.offset.y):a.P.convert(v.offset)).rotate(-a.an(S));return fe.center[0]-=Ne.x*me,fe.center[1]+=Ne.y*me,fe}queryTerrainElevation(u,f){const v=this.transform.elevation;return v?(f=Object.assign({},{exaggerated:!0},f),v.getAtPoint(a.ae.fromLngLat(u),null,f.exaggerated)):null}_cameraForBounds(u,f,v,S,T,E){if(u.projection.name==="globe")return this._cameraForBoundsOnGlobe(u,f,v,S,T,E);const L=u.clone(),B=this._extendCameraOptions(E);L.bearing=S,L.pitch=T;const q=a.aT.convert(f),G=a.aT.convert(v),ee=new a.aT(q.lng,G.lat),J=new a.aT(G.lng,q.lat),re=L.project(q),oe=L.project(G),se=this.queryTerrainElevation(q),me=this.queryTerrainElevation(G),fe=this.queryTerrainElevation(ee),Ne=this.queryTerrainElevation(J),Ae=[[re.x,re.y,Math.min(se||0,me||0,fe||0,Ne||0)],[oe.x,oe.y,Math.max(se||0,me||0,fe||0,Ne||0)]];let Te=a.d9.fromPoints(Ae);const Ze=L.getWorldToCameraMatrix(),$e=a.bl(new Float64Array(16),Ze);Te=a.d9.applyTransform(Te,Ze);const He=this._extendAABB(Te,L,B,S);if(!He)return void a.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");Te=He;const ze=.5*a.av([],Te.max,Te.min)[2],De=this._minimumAABBFrustumDistance(L,Te),Qe=[0,0,1,0];a.aC(Qe,Qe,Ze),a.f1(Qe,Qe);const ht=a.c5([],Qe,De+ze),ot=a.d8([],Te.center,ht);a.af(Te.center,Te.center,$e),a.af(ot,ot,$e);const Tt=L.unproject(new a.P(Te.center[0],Te.center[1])),At=a.f2(L.projection,Tt),Bt=Math.pow(2,At),or=Math.min(L._zoomFromMercatorZ(ot[2]*L.pixelsPerMeter*Bt/L.worldSize),B.maxZoom);return L.mercatorFromTransition&&or<.5*(a.c_+a.cL)?(L.setProjection({name:"globe"}),L.zoom=or,this._cameraForBounds(L,f,v,S,T,E)):{center:Tt,zoom:or,bearing:S,pitch:T}}fitBounds(u,f,v){const S=this.cameraForBounds(u,f);return this._fitInternal(S,f,v)}fitScreenCoordinates(u,f,v,S,T){const E=a.P.convert(u),L=a.P.convert(f),B=new a.P(Math.min(E.x,L.x),Math.min(E.y,L.y)),q=new a.P(Math.max(E.x,L.x),Math.max(E.y,L.y));if(this.transform.projection.name==="mercator"&&this.transform.anyCornerOffEdge(E,L))return this;const G=this.transform.pointLocation3D(B),ee=this.transform.pointLocation3D(q),J=this.transform.pointLocation3D(new a.P(B.x,q.y)),re=this.transform.pointLocation3D(new a.P(q.x,B.y)),oe=[Math.min(G.lng,ee.lng,J.lng,re.lng),Math.min(G.lat,ee.lat,J.lat,re.lat)],se=[Math.max(G.lng,ee.lng,J.lng,re.lng),Math.max(G.lat,ee.lat,J.lat,re.lat)],me=S&&S.pitch?S.pitch:this.getPitch(),fe=this._cameraForBounds(this.transform,oe,se,v,me,S);return this._fitInternal(fe,S,T)}_fitInternal(u,f,v){return u?(f=Object.assign(u,f)).linear?this.easeTo(f,v):this.flyTo(f,v):this}jumpTo(u,f){this.stop();const v=u.preloadOnly?this.transform.clone():this.transform;let S=!1,T=!1,E=!1;"zoom"in u&&v.zoom!==+u.zoom&&(S=!0,v.zoom=+u.zoom),u.center!==void 0&&(v.center=a.aT.convert(u.center)),"bearing"in u&&v.bearing!==+u.bearing&&(T=!0,v.bearing=+u.bearing),"pitch"in u&&v.pitch!==+u.pitch&&(E=!0,v.pitch=+u.pitch);const L=typeof u.padding=="number"?this._extendPadding(u.padding):u.padding;if(u.padding!=null&&!v.isPaddingEqual(L))if(u.retainPadding===!1){const B=v.clone();B.padding=L,v.setLocationAtPoint(v.center,B.centerPoint)}else v.padding=L;return u.preloadOnly?(this._preloadTiles(v),this):(this.fire(new a.z("movestart",f)).fire(new a.z("move",f)),S&&this.fire(new a.z("zoomstart",f)).fire(new a.z("zoom",f)).fire(new a.z("zoomend",f)),T&&this.fire(new a.z("rotatestart",f)).fire(new a.z("rotate",f)).fire(new a.z("rotateend",f)),E&&this.fire(new a.z("pitchstart",f)).fire(new a.z("pitch",f)).fire(new a.z("pitchend",f)),this.fire(new a.z("moveend",f)))}getFreeCameraOptions(){return this.transform.projection.supportsFreeCamera||a.w(Ab),this.transform.getFreeCameraOptions()}setFreeCameraOptions(u,f){const v=this.transform;if(!v.projection.supportsFreeCamera)return a.w(Ab),this;this.stop();const S=v.zoom,T=v.pitch,E=v.bearing;v.setFreeCameraOptions(u);const L=S!==v.zoom,B=T!==v.pitch,q=E!==v.bearing;return this.fire(new a.z("movestart",f)).fire(new a.z("move",f)),L&&this.fire(new a.z("zoomstart",f)).fire(new a.z("zoom",f)).fire(new a.z("zoomend",f)),q&&this.fire(new a.z("rotatestart",f)).fire(new a.z("rotate",f)).fire(new a.z("rotateend",f)),B&&this.fire(new a.z("pitchstart",f)).fire(new a.z("pitch",f)).fire(new a.z("pitchend",f)),this.fire(new a.z("moveend",f)),this}easeTo(u,f){this._stop(!1,u.easeId),((u=Object.assign({offset:[0,0],duration:500,easing:a.eV},u)).animate===!1||this._prefersReducedMotion(u))&&(u.duration=0);const v=this.transform,S=this.getZoom(),T=this.getBearing(),E=this.getPitch(),L=this.getPadding(),B="zoom"in u?+u.zoom:S,q="bearing"in u?this._normalizeBearing(u.bearing,T):T,G="pitch"in u?+u.pitch:E,ee=this._extendPadding(u.padding),J=a.P.convert(u.offset);let re,oe,se;if(v.projection.name==="globe"){const Qe=a.ae.fromLngLat(v.center),ht=J.rotate(-v.angle);Qe.x+=ht.x/v.worldSize,Qe.y+=ht.y/v.worldSize;const ot=Qe.toLngLat(),Tt=a.aT.convert(u.center||ot);this._normalizeCenter(Tt),re=v.centerPoint.add(ht),oe=new a.P(Qe.x,Qe.y).mult(v.worldSize),se=new a.P(a.aF(Tt.lng),a.aJ(Tt.lat)).mult(v.worldSize).sub(oe)}else{re=v.centerPoint.add(J);const Qe=v.pointLocation(re),ht=a.aT.convert(u.center||Qe);this._normalizeCenter(ht),oe=v.project(Qe),se=v.project(ht).sub(oe)}const me=v.zoomScale(B-S);let fe,Ne;u.around&&(fe=a.aT.convert(u.around),Ne=v.locationPoint(fe));const Ae=this._zooming||B!==S,Te=this._rotating||T!==q,Ze=this._pitching||G!==E,$e=!v.isPaddingEqual(ee),He=u.retainPadding===!1?v.clone():v,ze=Qe=>ht=>{if(Ae&&(Qe.zoom=a.ak(S,B,ht)),Te&&(Qe.bearing=a.ak(T,q,ht)),Ze&&(Qe.pitch=a.ak(E,G,ht)),$e&&(He.interpolatePadding(L,ee,ht),re=He.centerPoint.add(J)),fe)Qe.setLocationAtPoint(fe,Ne);else{const ot=Qe.zoomScale(Qe.zoom-S),Tt=B>S?Math.min(2,me):Math.max(.5,me),At=Math.pow(Tt,1-ht),Bt=Qe.unproject(oe.add(se.mult(ht*At)).mult(ot));Qe.setLocationAtPoint(Qe.renderWorldCopies?Bt.wrap():Bt,re)}return u.preloadOnly||this._fireMoveEvents(f),Qe};if(u.preloadOnly){const Qe=this._emulate(ze,u.duration,v);return this._preloadTiles(Qe),this}const De={moving:this._moving,zooming:this._zooming,rotating:this._rotating,pitching:this._pitching};return this._zooming=Ae,this._rotating=Te,this._pitching=Ze,this._padding=$e,this._easeId=u.easeId,this._prepareEase(f,u.noMoveStart,De),this._ease(ze(v),Qe=>{v.cameraElevationReference==="sea"&&v.recenterOnTerrain(),this._afterEase(f,Qe)},u),this}_prepareEase(u,f,v={}){this._moving=!0,this.transform.cameraElevationReference="sea",this.transform._orthographicProjectionAtLowPitch&&this.transform.pitch===0&&this.transform.projection.name!=="globe"&&(this.transform.cameraElevationReference="ground"),f||v.moving||this.fire(new a.z("movestart",u)),this._zooming&&!v.zooming&&this.fire(new a.z("zoomstart",u)),this._rotating&&!v.rotating&&this.fire(new a.z("rotatestart",u)),this._pitching&&!v.pitching&&this.fire(new a.z("pitchstart",u))}_fireMoveEvents(u){this.fire(new a.z("move",u)),this._zooming&&this.fire(new a.z("zoom",u)),this._rotating&&this.fire(new a.z("rotate",u)),this._pitching&&this.fire(new a.z("pitch",u))}_afterEase(u,f){if(this._easeId&&f&&this._easeId===f)return;this._easeId=void 0,this.transform.cameraElevationReference="ground";const v=this._zooming,S=this._rotating,T=this._pitching;this._moving=!1,this._zooming=!1,this._rotating=!1,this._pitching=!1,this._padding=!1,v&&this.fire(new a.z("zoomend",u)),S&&this.fire(new a.z("rotateend",u)),T&&this.fire(new a.z("pitchend",u)),this.fire(new a.z("moveend",u))}flyTo(u,f){if(this._prefersReducedMotion(u)){const kt=a.aH(u,["center","zoom","bearing","pitch","around","padding","retainPadding"]);return this.jumpTo(kt,f)}this.stop(),u=Object.assign({offset:[0,0],speed:1.2,curve:1.42,easing:a.eV},u);const v=this.transform,S=this.getZoom(),T=this.getBearing(),E=this.getPitch(),L=this.getPadding(),B="zoom"in u?a.aA(+u.zoom,v.minZoom,v.maxZoom):S,q="bearing"in u?this._normalizeBearing(u.bearing,T):T,G="pitch"in u?+u.pitch:E,ee=this._extendPadding(u.padding),J=v.zoomScale(B-S),re=a.P.convert(u.offset);let oe=v.centerPoint.add(re);const se=v.pointLocation(oe),me=a.aT.convert(u.center||se);this._normalizeCenter(me);const fe=v.project(se),Ne=v.project(me).sub(fe);let Ae=u.curve;const Te=Math.max(v.width,v.height),Ze=Te/J,$e=Ne.mag();if("minZoom"in u){const kt=a.aA(Math.min(u.minZoom,S,B),v.minZoom,v.maxZoom),Zt=Te/v.zoomScale(kt-S);Ae=Math.sqrt(Zt/$e*2)}const He=Ae*Ae;function ze(kt){const Zt=(Ze*Ze-Te*Te+(kt?-1:1)*He*He*$e*$e)/(2*(kt?Ze:Te)*He*$e);return Math.log(Math.sqrt(Zt*Zt+1)-Zt)}function De(kt){return(Math.exp(kt)-Math.exp(-kt))/2}function Qe(kt){return(Math.exp(kt)+Math.exp(-kt))/2}const ht=ze(0);let ot=function(kt){return Qe(ht)/Qe(ht+Ae*kt)},Tt=function(kt){return Te*((Qe(ht)*(De(Zt=ht+Ae*kt)/Qe(Zt))-De(ht))/He)/$e;var Zt},At=(ze(1)-ht)/Ae;if(Math.abs($e)<1e-6||!isFinite(At)){if(Math.abs(Te-Ze)<1e-6)return this.easeTo(u,f);const kt=Zeu.maxDuration&&(u.duration=0);const Bt=T!==q,or=G!==E,wt=!v.isPaddingEqual(ee),st=u.retainPadding===!1?v.clone():v,Mt=kt=>Zt=>{const yr=Zt*At,Pr=1/ot(yr);kt.zoom=Zt===1?B:S+kt.scaleZoom(Pr),Bt&&(kt.bearing=a.ak(T,q,Zt)),or&&(kt.pitch=a.ak(E,G,Zt)),wt&&(st.interpolatePadding(L,ee,Zt),oe=st.centerPoint.add(re));const fr=Zt===1?me:kt.unproject(fe.add(Ne.mult(Tt(yr))).mult(Pr));return kt.setLocationAtPoint(kt.renderWorldCopies?fr.wrap():fr,oe),kt._updateCameraOnTerrain(),u.preloadOnly||this._fireMoveEvents(f),kt};if(u.preloadOnly){const kt=this._emulate(Mt,u.duration,v);return this._preloadTiles(kt),this}return this._zooming=!0,this._rotating=Bt,this._pitching=or,this._padding=wt,this._prepareEase(f,!1),this._ease(Mt(v),()=>this._afterEase(f),u),this}isEasing(){return!!this._easeFrameId}stop(){return this._stop()}_requestRenderFrame(u){}_cancelRenderFrame(u){}_stop(u,f){if(this._easeFrameId&&(this._cancelRenderFrame(this._easeFrameId),this._easeFrameId=void 0,this._onEaseFrame=void 0),this._onEaseEnd){const v=this._onEaseEnd;this._onEaseEnd=void 0,v.call(this,f)}if(!u){const v=this.handlers;v&&v.stop(!1)}return this}_ease(u,f,v){v.animate===!1||v.duration===0?(u(1),f()):(this._easeStart=a.o.now(),this._easeOptions=v,this._onEaseFrame=u,this._onEaseEnd=f,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback))}_renderFrameCallback(){const u=Math.min((a.o.now()-this._easeStart)/this._easeOptions.duration,1),f=this._onEaseFrame;f&&f(this._easeOptions.easing(u)),u<1?this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback):this.stop()}_normalizeBearing(u,f){u=a.bT(u,-180,180);const v=Math.abs(u-f);return Math.abs(u-360-f)180?-360:v<-180?360:0}_prefersReducedMotion(u){return this._respectPrefersReducedMotion&&a.o.prefersReducedMotion&&!(u&&u.essential)}_emulate(u,f,v){const S=Math.ceil(15*f/1e3),T=[],E=u(v.clone());for(let L=0;L<=S;L++){const B=E(L/S);T.push(B.clone())}return T}_preloadTiles(u,f){}}class fv{constructor(u={}){this.options=u,a.aY(["_toggleAttribution","_updateEditLink","_updateData","_updateCompact"],this)}getDefaultPosition(){return"bottom-right"}onAdd(u){const f=this.options&&this.options.compact,v=u._getUIString("AttributionControl.ToggleAttribution");this._map=u,this._container=A("div","mapboxgl-ctrl mapboxgl-ctrl-attrib"),this._compactButton=A("button","mapboxgl-ctrl-attrib-button",this._container),this._compactButton.type="button",this._compactButton.addEventListener("click",this._toggleAttribution),this._compactButton.setAttribute("aria-label",v);const S=A("span","mapboxgl-ctrl-icon",this._compactButton);return S.setAttribute("aria-hidden","true"),S.setAttribute("title",v),this._innerContainer=A("div","mapboxgl-ctrl-attrib-inner",this._container),f&&this._container.classList.add("mapboxgl-compact"),this._updateAttributions(),this._updateEditLink(),this._map.on("styledata",this._updateData),this._map.on("sourcedata",this._updateData),this._map.on("moveend",this._updateEditLink),f===void 0&&(this._map.on("resize",this._updateCompact),this._updateCompact()),this._container}onRemove(){this._container.remove(),this._map.off("styledata",this._updateData),this._map.off("sourcedata",this._updateData),this._map.off("moveend",this._updateEditLink),this._map.off("resize",this._updateCompact),this._map=void 0,this._attribHTML=void 0}_toggleAttribution(){this._container.classList.contains("mapboxgl-compact-show")?(this._container.classList.remove("mapboxgl-compact-show"),this._compactButton.setAttribute("aria-expanded","false")):(this._container.classList.add("mapboxgl-compact-show"),this._compactButton.setAttribute("aria-expanded","true"))}_updateEditLink(){let u=this._editLink;u||(u=this._editLink=this._container.querySelector(".mapbox-improve-map"));const f=[{key:"owner",value:this.styleOwner},{key:"id",value:this.styleId},{key:"access_token",value:this._map._requestManager._customAccessToken||a.e.ACCESS_TOKEN}];if(u){const v=f.reduce((S,T,E)=>(T.value&&(S+=`${T.key}=${T.value}${ES.length-T.length),u=u.filter((S,T)=>{for(let E=T+1;E=0)return!1;return!0}),this.options.customAttribution&&(Array.isArray(this.options.customAttribution)?u=[...this.options.customAttribution,...u]:u.unshift(this.options.customAttribution));const v=u.map(S=>function(T){const E=new DOMParser().parseFromString(T,"text/html");return Array.from(E.body.querySelectorAll("*")).forEach(L=>{const B=L.textContent||"";if(L.tagName!=="A")return void L.replaceWith(E.createTextNode(B));const q=L.getAttribute("href");if(!q||!/^(https?:|mailto:)/i.test(q))return void L.replaceWith(E.createTextNode(B));const G=E.createElement("a");G.href=q,G.textContent=B,G.rel="noopener nofollow";const ee=L.getAttribute("class");ee&&(G.className=ee),L.replaceWith(G)}),E.body.innerHTML}(S)).join(" | ");v!==this._attribHTML&&(this._attribHTML=v,u.length?(this._innerContainer.innerHTML=v,this._container.classList.remove("mapboxgl-attrib-empty")):this._container.classList.add("mapboxgl-attrib-empty"),this._editLink=null)}_updateCompact(){this._map.getCanvasContainer().offsetWidth<=640?this._container.classList.add("mapboxgl-compact"):this._container.classList.remove("mapboxgl-compact","mapboxgl-compact-show")}}class pv{constructor(){a.aY(["_updateLogo","_updateCompact"],this)}onAdd(u){this._map=u,this._container=A("div","mapboxgl-ctrl");const f=A("a","mapboxgl-ctrl-logo");return f.target="_blank",f.rel="noopener nofollow",f.href="https://www.mapbox.com/",f.setAttribute("aria-label",this._map._getUIString("LogoControl.Title")),f.setAttribute("rel","noopener nofollow"),this._container.appendChild(f),this._container.style.display="none",this._map.on("sourcedata",this._updateLogo),this._updateLogo(),this._map.on("resize",this._updateCompact),this._updateCompact(),this._container}onRemove(){this._container.remove(),this._map.off("sourcedata",this._updateLogo),this._map.off("resize",this._updateCompact)}getDefaultPosition(){return"bottom-left"}_updateLogo(u){u&&u.sourceDataType!=="metadata"||(this._container.style.display=this._logoRequired()?"block":"none")}_logoRequired(){if(!this._map.style)return!0;const u=this._map.style._sourceCaches;if(Object.entries(u).length===0)return!0;for(const f in u){const v=u[f].getSource();if(v.hasOwnProperty("mapbox_logo")&&!v.mapbox_logo)return!1}return!0}_updateCompact(){const u=this._container.children;if(u.length){const f=u[0];this._map.getCanvasContainer().offsetWidth<250?f.classList.add("mapboxgl-compact"):f.classList.remove("mapboxgl-compact")}}}class Og{constructor(){a.aY(["_onIndoorUpdate"],this)}onAdd(u){return this._map=u,this._container=A("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._map.indoor.on("selector-update",f=>this._onIndoorUpdate(f)),this._container}_createButton(u,f){const v=A("button",u,this._container);return v.type="button",v.addEventListener("click",f),v}_createSeparator(){return A("div","mapboxgl-ctrl-separator",this._container)}_setButtonTitle(u,f){this._map&&(u.setAttribute("aria-label",f),u.textContent=f)}onRemove(){this._container&&this._container.remove(),this._map&&this._map.indoor&&(this._map.indoor.off("selector-update",this._onIndoorUpdate),this._map=null)}getDefaultPosition(){return"right"}_onIndoorUpdate(u){if(!u||!u.floors)return this._model=u,void(this._container.style.display="none");const f=this._model;this._model=u,this._container.style.display="inline-block",this._container.style.borderRadius="8px",f&&Array.from(this._container.children).forEach(v=>v.remove()),u.floors.length>0&&(this.addBuildingsToggleButton(),this.addCurrentFloors(u.floors,u.activeFloorsVisible),this._updateBuildingsButtonState())}addBuildingsToggleButton(){const u=this._createButton("mapboxgl-ctrl-buildings-toggle",()=>{const f=this._map;this._model&&f&&f._setIndoorActiveFloorsVisibility(!this._model.activeFloorsVisible)});A("span","mapboxgl-ctrl-icon",u).setAttribute("aria-hidden","true"),u.classList.add("mapboxgl-ctrl-level-button","mapboxgl-ctrl-buildings-toggle"),this._model&&!this._model.activeFloorsVisible&&u.classList.add("mapboxgl-ctrl-level-button-selected"),this._container.append(u),this._createSeparator()}_updateBuildingsButtonState(){const u=this._container.querySelector(".mapboxgl-ctrl-buildings-toggle");u&&this._model&&(this._model.activeFloorsVisible?u.classList.remove("mapboxgl-ctrl-level-button-selected"):u.classList.add("mapboxgl-ctrl-level-button-selected"))}addCurrentFloors(u,f){for(let v=0;v{this._map._selectIndoorFloor(S.id)});this._setButtonTitle(T,S.zIndex.toString()),this._model&&S.id===this._model.selectedFloorId&&f&&T.classList.add("mapboxgl-ctrl-level-button-selected"),this._container.append(T),v=this._endTime)return this._end;const f=a.dD((u-this._startTime)/(this._endTime-this._startTime));return this._start*(1-f)+this._end*f}isEasing(u){return u>=this._startTime&&u<=this._endTime}jumpTo(u){this._startTime=-1/0,this._endTime=-1/0,this._start=u,this._end=u}easeTo(u,f,v){this._start=this.getValue(f),this._end=u,this._startTime=f,this._endTime=f+v}}const Lh={"AttributionControl.ToggleAttribution":"Toggle attribution","FullscreenControl.Enter":"Enter fullscreen","FullscreenControl.Exit":"Exit fullscreen","GeolocateControl.FindMyLocation":"Find my location","GeolocateControl.LocationNotAvailable":"Location not available","LogoControl.Title":"Mapbox homepage","Map.Title":"Map","NavigationControl.ResetBearing":"Reset bearing to north","NavigationControl.ZoomIn":"Zoom in","NavigationControl.ZoomOut":"Zoom out","ScrollZoomBlocker.CtrlMessage":"Use ctrl + scroll to zoom the map","ScrollZoomBlocker.CmdMessage":"Use ⌘ + scroll to zoom the map","TouchPanBlocker.Message":"Use two fingers to move the map"};class Zf extends a.z{constructor(u,f,v,S){const{point:T,lngLat:E,originalEvent:L,target:B}=u;super(u.type,{point:T,lngLat:E,originalEvent:L,target:B}),this.preventDefault=()=>{u.preventDefault()},this.id=f,this.interaction=v,this.feature=S}}class ed{constructor(u){this.map=u,this.interactionsByType=new Map,this.delegatedInteractions=new Map,this.typeById=new Map,this.filters=new Map,this.handleType=this.handleType.bind(this),this.handleMove=this.handleMove.bind(this),this.handleOut=this.handleOut.bind(this),this.hoveredFeatures=new Map,this.prevHoveredFeatures=new Map}add(u,f){if(this.typeById.has(u))throw new Error(`Interaction id "${u}" already exists.`);const v=f.filter;let S=f.type;v&&this.filters.set(u,a.b6(v)),S==="mouseover"&&(S="mouseenter"),S==="mouseout"&&(S="mouseleave");const T=this.interactionsByType.get(S)||new Map;S==="mouseenter"||S==="mouseleave"?(this.delegatedInteractions.size===0&&(this.map.on("mousemove",this.handleMove),this.map.on("mouseout",this.handleOut)),this.delegatedInteractions.set(u,f)):T.size===0&&this.map.on(S,this.handleType),T.size===0&&this.interactionsByType.set(S,T),T.set(u,f),this.typeById.set(u,S)}get(u){const f=this.typeById.get(u);if(!f)return;const v=this.interactionsByType.get(f);return v?v.get(u):void 0}remove(u){const f=this.typeById.get(u);if(!f)return;this.typeById.delete(u),this.filters.delete(u);const v=this.interactionsByType.get(f);v&&(v.delete(u),f==="mouseenter"||f==="mouseleave"?(this.delegatedInteractions.delete(u),this.delegatedInteractions.size===0&&(this.map.off("mousemove",this.handleMove),this.map.off("mouseout",this.handleOut))):v.size===0&&this.map.off(f,this.handleType))}queryTargets(u,f){const v=[];for(const[S,T]of f)T.target&&v.push({targetId:S,target:T.target,filter:this.filters.get(S)});return this.map.style.queryRenderedTargets(u,v,this.map.transform)}handleMove(u){this.prevHoveredFeatures=this.hoveredFeatures,this.hoveredFeatures=new Map;const f=this.queryTargets(u.point,Array.from(this.delegatedInteractions).reverse());f.length&&(u.type="mouseenter",this.handleType(u,f));const v=new Map;for(const[S,{feature:T}]of this.prevHoveredFeatures)this.hoveredFeatures.has(S)||v.set(T.id,T);v.size&&(u.type="mouseleave",this.handleType(u,Array.from(v.values())))}handleOut(u){const f=Array.from(this.hoveredFeatures.values()).map(({feature:v})=>v);f.length&&(u.type="mouseleave",this.handleType(u,f)),this.hoveredFeatures.clear()}handleType(u,f){const v=u.type==="mouseenter";if(v&&!this.interactionsByType.has(u.type))return void a.w("mouseenter interaction required for mouseleave to work.");const S=Array.from(this.interactionsByType.get(u.type)).reverse(),T=!!f;f=f||this.queryTargets(u.point,S);let E=!1;const L=new Set;for(const B of f){for(const[q,G]of S){if(!G.target)continue;const ee=B.variants?B.variants[q]:null;if(ee){for(const J of ee){if(hg(J,B,L,q))continue;const re=new a.dx(B,J),oe=Bp(J,B,q);T&&re.id!==void 0&&(re.state=this.map.getFeatureState(re));const se=v?this.prevHoveredFeatures.get(oe):null,me=new Zf(u,q,G,re),fe=se?se.stop:G.handler(me);if(v&&this.hoveredFeatures.set(oe,{feature:B,stop:fe}),fe!==!1){E=!0;break}}if(E)break}}if(E)break}if(!E)for(const[B,q]of S){const{handler:G,target:ee}=q;if(!ee&&G(new Zf(u,B,q,null))!==!1)break}}}function O4(x,u){if(Array.isArray(x)&&Array.isArray(u)){const f=new Set(x),v=new Set(u);return f.size===v.size&&x.every(S=>v.has(S))}return a.by(x,u)}const R4={center:[0,0],zoom:0,bearing:0,pitch:0,minZoom:-2,maxZoom:22,minPitch:0,maxPitch:85,interactive:!0,scrollZoom:!0,boxZoom:!0,dragRotate:!0,dragPan:!0,keyboard:!0,doubleClickZoom:!0,touchZoomRotate:!0,touchPitch:!0,cooperativeGestures:!1,performanceMetricsCollection:!0,bearingSnap:7,clickTolerance:3,pitchWithRotate:!0,hash:!1,attributionControl:!0,antialias:!1,failIfMajorPerformanceCaveat:!1,preserveDrawingBuffer:!1,trackResize:!0,renderWorldCopies:!0,refreshExpiredTiles:!0,minTileCacheSize:null,maxTileCacheSize:null,localIdeographFontFamily:"sans-serif",localFontFamily:null,transformRequest:null,accessToken:null,fadeDuration:300,respectPrefersReducedMotion:!0,crossSourceCollisions:!0,collectResourceTiming:!1,testMode:!1,precompilePrograms:!0,scaleFactor:1,spriteFormat:"auto"},D4={showCompass:!0,showZoom:!0,visualizePitch:!1};class L4{constructor(u,f,v=!1){this._clickTolerance=10,this.element=f,this.mouseRotate=new aN({clickTolerance:u.dragRotate._mouseRotate._clickTolerance}),this.map=u,v&&(this.mousePitch=new oN({clickTolerance:u.dragRotate._mousePitch._clickTolerance})),a.aY(["mousedown","mousemove","mouseup","touchstart","touchmove","touchend","reset"],this),f.addEventListener("mousedown",this.mousedown),f.addEventListener("touchstart",this.touchstart,{passive:!1}),f.addEventListener("touchmove",this.touchmove),f.addEventListener("touchend",this.touchend),f.addEventListener("touchcancel",this.reset)}down(u,f){this.mouseRotate.mousedown(u,f),this.mousePitch&&this.mousePitch.mousedown(u,f),W()}move(u,f){const v=this.map,S=this.mouseRotate.mousemoveWindow(u,f),T=S&&S.bearingDelta;if(T&&v.setBearing(v.getBearing()+T),this.mousePitch){const E=this.mousePitch.mousemoveWindow(u,f),L=E&&E.pitchDelta;L&&v.setPitch(v.getPitch()+L)}}off(){const u=this.element;u.removeEventListener("mousedown",this.mousedown),u.removeEventListener("touchstart",this.touchstart),u.removeEventListener("touchmove",this.touchmove),u.removeEventListener("touchend",this.touchend),u.removeEventListener("touchcancel",this.reset),this.offTemp()}offTemp(){V(),window.removeEventListener("mousemove",this.mousemove),window.removeEventListener("mouseup",this.mouseup)}mousedown(u){this.down(Object.assign({},u,{ctrlKey:!0,preventDefault:()=>u.preventDefault()}),te(this.element,u)),window.addEventListener("mousemove",this.mousemove),window.addEventListener("mouseup",this.mouseup)}mousemove(u){this.move(u,te(this.element,u))}mouseup(u){this.mouseRotate.mouseupWindow(u),this.mousePitch&&this.mousePitch.mouseupWindow(u),this.offTemp()}touchstart(u){u.targetTouches.length!==1?this.reset():(this._startPos=this._lastPos=X(this.element,u.targetTouches)[0],this.down({type:"mousedown",button:0,ctrlKey:!0,preventDefault:()=>u.preventDefault()},this._startPos))}touchmove(u){u.targetTouches.length!==1?this.reset():(this._lastPos=X(this.element,u.targetTouches)[0],this.move({preventDefault:()=>u.preventDefault()},this._lastPos))}touchend(u){u.targetTouches.length===0&&this._startPos&&this._lastPos&&this._startPos.dist(this._lastPos)f.width||u.y>f.height;f.locationPoint3D(v).distSqr(u)180;){const v=f.locationPoint3D(x);if(v.x>=0&&v.y>=0&&v.x<=f.width&&v.y<=f.height)break;x.lng>f.center.lng?x.lng-=360:x.lng+=360}return x}const rl={center:"translate(-50%,-50%)",top:"translate(-50%,0)","top-left":"translate(0,0)","top-right":"translate(-100%,0)",bottom:"translate(-50%,-100%)","bottom-left":"translate(0,-100%)","bottom-right":"translate(-100%,-100%)",left:"translate(0,-50%)",right:"translate(-100%,-50%)"},ju={rotation:0,rotationAlignment:"auto",pitchAlignment:"auto",occludedOpacity:.2,altitude:0};class Pb extends a.E{constructor(u,f){super(),(u instanceof HTMLElement||f)&&(u=Object.assign({element:u},f)),a.aY(["_update","_onMove","_onUp","_addDragHandler","_onMapClick","_onKeyPress","_clearFadeTimer"],this);const{anchor:v="center",color:S="#3FB1CE",scale:T=1,draggable:E=!1,clickTolerance:L=0,rotation:B=ju.rotation,rotationAlignment:q=ju.rotationAlignment,pitchAlignment:G=ju.pitchAlignment,occludedOpacity:ee=ju.occludedOpacity,altitude:J=ju.altitude}=u||{};this._anchor=v,this._color=S,this._scale=T,this._draggable=E,this._clickTolerance=L,this._rotation=B,this._rotationAlignment=q,this._pitchAlignment=G,this._occludedOpacity=ee,this._altitude=J,this._state="inactive",this._isDragging=!1,this._updateMoving=()=>this._update(!0),u&&u.element?(this._element=u.element,this._offset=a.P.convert(u&&u.offset||[0,0])):(this._defaultMarker=!0,this._element=this._createDefaultMarker(),this._offset=a.P.convert(u&&u.offset||[0,-14])),this._element.hasAttribute("aria-label")||this._element.setAttribute("aria-label","Map marker"),this._element.hasAttribute("role")||this._element.setAttribute("role","img"),this._element.classList.add("mapboxgl-marker"),this._element.addEventListener("dragstart",se=>{se.preventDefault()}),this._element.addEventListener("mousedown",se=>{se.preventDefault()});const re=this._element.classList;for(const se in rl)re.remove(`mapboxgl-marker-anchor-${se}`);re.add(`mapboxgl-marker-anchor-${this._anchor}`);const oe=u&&u.className?u.className.trim().split(/\s+/):[];re.add(...oe),this._popup=null}_createDefaultMarker(){const u=A("div"),f=I("svg",{display:"block",height:41*this._scale+"px",width:27*this._scale+"px",viewBox:"0 0 27 41"},u);if(this._altitude===0){const v=I("radialGradient",{id:"shadowGradient"},I("defs",{},f));I("stop",{offset:"10%","stop-opacity":.4},v),I("stop",{offset:"100%","stop-opacity":.05},v),I("ellipse",{cx:13.5,cy:34.8,rx:10.5,ry:5.25,fill:"url(#shadowGradient)"},f)}return I("path",{fill:this._color,d:"M27,13.5C27,19.07 20.25,27 14.75,34.5C14.02,35.5 12.98,35.5 12.25,34.5C6.75,27 0,19.22 0,13.5C0,6.04 6.04,0 13.5,0C20.96,0 27,6.04 27,13.5Z"},f),I("path",{opacity:.25,d:"M13.5,0C6.04,0 0,6.04 0,13.5C0,19.22 6.75,27 12.25,34.5C13,35.52 14.02,35.5 14.75,34.5C20.25,27 27,19.07 27,13.5C27,6.04 20.96,0 13.5,0ZM13.5,1C20.42,1 26,6.58 26,13.5C26,15.9 24.5,19.18 22.22,22.74C19.95,26.3 16.71,30.14 13.94,33.91C13.74,34.18 13.61,34.32 13.5,34.44C13.39,34.32 13.26,34.18 13.06,33.91C10.28,30.13 7.41,26.31 5.02,22.77C2.62,19.23 1,15.95 1,13.5C1,6.58 6.58,1 13.5,1Z"},f),I("circle",{fill:"white",cx:13.5,cy:13.5,r:5.5},f),u}addTo(u){return u===this._map||(this.remove(),this._map=u,u.getCanvasContainer().appendChild(this._element),u.on("move",this._updateMoving),u.on("moveend",this._update),u.on("remove",this._clearFadeTimer),u._addMarker(this),this.setDraggable(this._draggable),this._update(),u.on("click",this._onMapClick)),this}remove(){const u=this._map;return u&&(u.off("click",this._onMapClick),u.off("move",this._updateMoving),u.off("moveend",this._update),u.off("mousedown",this._addDragHandler),u.off("touchstart",this._addDragHandler),u.off("mouseup",this._onUp),u.off("touchend",this._onUp),u.off("mousemove",this._onMove),u.off("touchmove",this._onMove),u.off("remove",this._clearFadeTimer),u._removeMarker(this),this._map=void 0),this._clearFadeTimer(),this._element.remove(),this._popup&&this._popup.remove(),this}getLngLat(){return this._lngLat}setLngLat(u){return this._lngLat=a.aT.convert(u),this._pos=null,this._popup&&this._popup.setLngLat(this._lngLat),this._update(!0),this}setAltitude(u){return u===this._altitude||(this._defaultMarker&&(this._altitude===0&&u!==0||this._altitude!==0&&u===0)&&(this._element=this._createDefaultMarker()),this._altitude=u||ju.altitude,this._update()),this}getAltitude(){return this._altitude}getElement(){return this._element}setPopup(u){if(this._popup&&(this._popup.remove(),this._popup=null,this._element.removeAttribute("role"),this._element.removeEventListener("keypress",this._onKeyPress),this._originalTabIndex||this._element.removeAttribute("tabindex")),u){if(!("offset"in u.options)){const S=Math.sqrt(Math.pow(13.5,2)/2);u.options.offset=this._defaultMarker?{top:[0,0],"top-left":[0,0],"top-right":[0,0],bottom:[0,-38.1],"bottom-left":[S,-1*(38.1-13.5+S)],"bottom-right":[-S,-1*(38.1-13.5+S)],left:[13.5,-1*(38.1-13.5)],right:[-13.5,-1*(38.1-13.5)]}:this._offset}this._popup=u,u._marker=this,u._altitude=this._altitude,this._lngLat&&this._popup.setLngLat(this._lngLat),this._element.setAttribute("role","button"),this._originalTabIndex=this._element.getAttribute("tabindex"),this._originalTabIndex||this._element.setAttribute("tabindex","0"),this._element.addEventListener("keypress",this._onKeyPress),this._element.setAttribute("aria-expanded","false")}return this}_onKeyPress(u){const f=u.code,v=u.charCode||u.keyCode;f!=="Space"&&f!=="Enter"&&v!==32&&v!==13||this.togglePopup()}_onMapClick(u){const f=u.originalEvent.target,v=this._element;this._popup&&(f===v||v.contains(f))&&this.togglePopup()}getPopup(){return this._popup}togglePopup(){const u=this._popup;return u?(u.isOpen()?(u.remove(),this._element.setAttribute("aria-expanded","false")):this._map&&(u.addTo(this._map),this._element.setAttribute("aria-expanded","true")),this):this}_behindTerrain(){const u=this._map,f=this._pos;if(!u||!f)return!1;const v=u.unproject(f,this._altitude),S=u.getFreeCameraOptions();if(!S.position)return!1;const T=S.position.toLngLat();return T.distanceTo(v)<.9*T.distanceTo(this._lngLat)}_evaluateOpacity(){const u=this._map;if(!u)return;const f=this._pos;if(!f||f.x<0||f.x>u.transform.width||f.y<0||f.y>u.transform.height)return void this._clearFadeTimer();const v=u.unproject(f,this._altitude);let S;u._showingGlobe()&&a.f5(u.transform,this._lngLat)?S=0:(S=1-u._queryFogOpacity(v),u.transform._terrainEnabled()&&u.getTerrain()&&this._behindTerrain()&&(S*=this._occludedOpacity)),this._element.style.opacity=`${S}`,this._element.style.pointerEvents=S>0?"auto":"none",this._popup&&this._popup._setOpacity(S),this._fadeTimer=null}_clearFadeTimer(){this._fadeTimer&&(clearTimeout(this._fadeTimer),this._fadeTimer=null)}_updateDOM(){const u=this._pos;if(!u||!this._map)return;const f=this._offset.mult(this._scale);this._element.style.transform=` translate(${u.x}px,${u.y}px) ${rl[this._anchor]} ${this._calculateXYTransform()} ${this._calculateZTransform()} translate(${f.x}px,${f.y}px) `}_calculateXYTransform(){const u=this._pos,f=this._map,v=this.getPitchAlignment();if(!f||!u||v!=="map")return"";if(!f._showingGlobe()){const B=f.getPitch();return B?`rotateX(${B}deg)`:""}const S=a.cX(a.f6(f.transform,this._lngLat)),T=u.sub(a.f7(f.transform)),E=Math.abs(T.x)+Math.abs(T.y);if(E===0)return"";const L=S/E;return`rotateX(${-T.y*L}deg) rotateY(${T.x*L}deg)`}_calculateZTransform(){const u=this._pos,f=this._map;if(!f||!u)return"";let v=0;const S=this.getRotationAlignment();if(S==="map")if(f._showingGlobe()){const T=f.project(new a.aT(this._lngLat.lng,this._lngLat.lat+.001),this._altitude),E=f.project(new a.aT(this._lngLat.lng,this._lngLat.lat-.001),this._altitude).sub(T);v=a.cX(Math.atan2(E.y,E.x))-90}else v=-f.getBearing();else if(S==="horizon"){const T=a.ah(4,6,f.getZoom()),E=a.f7(f.transform);E.y+=T*f.transform.height;const L=u.sub(E),B=a.cX(Math.atan2(L.y,L.x));v=(B>90?B-270:B+90)*(1-T)}return v+=this._rotation,v?`rotateZ(${v}deg)`:""}_update(u){cancelAnimationFrame(this._updateFrameId);const f=this._map;f&&(f.transform.renderWorldCopies&&(this._lngLat=dN(this._lngLat,this._pos,f.transform)),this._pos=f.project(this._lngLat,this._altitude),u===!0?this._updateFrameId=requestAnimationFrame(()=>{this._element&&this._pos&&this._anchor&&(this._pos=this._pos.round(),this._updateDOM())}):this._pos=this._pos.round(),f._requestDomTask(()=>{this._map&&(this._element&&this._pos&&this._anchor&&this._updateDOM(),(f._showingGlobe()||f.getTerrain()||f.getFog())&&!this._fadeTimer&&(this._fadeTimer=window.setTimeout(this._evaluateOpacity.bind(this),60)))}))}getOffset(){return this._offset}setOffset(u){return this._offset=a.P.convert(u),this._update(),this}addClassName(u){return this._element.classList.add(u),this}removeClassName(u){return this._element.classList.remove(u),this}toggleClassName(u){return this._element.classList.toggle(u)}_onMove(u){const f=this._map;if(!f)return;const v=this._pointerdownPos,S=this._positionDelta;if(v&&S){if(!this._isDragging){const T=this._clickTolerance||f._clickTolerance;if(u.point.dist(v)x.maxZoom)throw new Error("maxZoom must be greater than or equal to minZoom");if(x.minPitch!=null&&x.maxPitch!=null&&x.minPitch>x.maxPitch)throw new Error("maxPitch must be greater than or equal to minPitch");if(x.minPitch!=null&&x.minPitch<0)throw new Error("minPitch must be greater than or equal to 0");if(x.maxPitch!=null&&x.maxPitch>85)throw new Error("maxPitch must be less than or equal to 85");if(x.antialias&&a.f3(window)&&(x.antialias=!1,a.w("Antialiasing is disabled for this WebGL context to avoid browser bug: https://github.com/mapbox/mapbox-gl-js/issues/11609")),super(new mS(x.minZoom,x.maxZoom,x.minPitch,x.maxPitch,x.renderWorldCopies,null,null),x),this._repaint=!!x.repaint,this._interactive=x.interactive,this._minTileCacheSize=x.minTileCacheSize,this._maxTileCacheSize=x.maxTileCacheSize,this._failIfMajorPerformanceCaveat=x.failIfMajorPerformanceCaveat,this._preserveDrawingBuffer=x.preserveDrawingBuffer,this._antialias=x.antialias,this._trackResize=x.trackResize,this._bearingSnap=x.bearingSnap,this._refreshExpiredTiles=x.refreshExpiredTiles,this._fadeDuration=x.fadeDuration,this._isInitialLoad=!0,this._crossSourceCollisions=x.crossSourceCollisions,this._collectResourceTiming=x.collectResourceTiming,this._language=this._parseLanguage(x.language),this._worldview=x.worldview,this._renderTaskQueue=new Rh,this._domRenderTaskQueue=new Rh,this._controls=[],this._markers=[],this._popups=[],this._mapId=a.b2(),this._locale=Object.assign({},Lh,x.locale),this._clickTolerance=x.clickTolerance,this._cooperativeGestures=x.cooperativeGestures,this._performanceMetricsCollection=x.performanceMetricsCollection,this._tessellationStep=x.tessellationStep,this._containerWidth=0,this._containerHeight=0,this._showParseStatus=!0,this._precompilePrograms=x.precompilePrograms,this._scaleFactorChanged=!1,this._averageElevationLastSampledAt=-1/0,this._averageElevationExaggeration=0,this._averageElevation=new Dh(0),this._interactionRange=[1/0,-1/0],this._visibilityHidden=0,this._useExplicitProjection=!1,this._frameId=0,this._scaleFactor=x.scaleFactor,this._requestManager=new ve(x.transformRequest,x.accessToken,x.testMode),this._silenceAuthErrors=!!x.testMode,this._contextCreateOptions=x.contextCreateOptions?Object.assign({},x.contextCreateOptions):{},typeof x.container=="string"){const f=document.getElementById(x.container);if(!f)throw new Error(`Container '${x.container.toString()}' not found.`);this._container=f}else{if(!(x.container instanceof HTMLElement))throw new Error("Invalid type: 'container' must be a String or HTMLElement.");this._container=x.container}if(this._container.childNodes.length>0&&a.w("The map container element should be empty, otherwise the map's interactivity will be negatively impacted. If you want to display a message when WebGL is not supported, use the Mapbox GL Supported plugin instead."),x.maxBounds&&this.setMaxBounds(x.maxBounds),this._spriteFormat=x.spriteFormat,a.aY(["_onWindowOnline","_onWindowResize","_onVisibilityChange","_onMapScroll","_contextLost","_contextRestored"],this),this._setupContainer(),this._setupPainter(),this.painter===void 0)throw new Error("Failed to initialize WebGL.");if(this.on("move",()=>this._update(!1)),this.on("moveend",()=>this._update(!1)),this.on("zoom",()=>this._update(!0)),this._fullscreenchangeEvent="onfullscreenchange"in document?"fullscreenchange":"webkitfullscreenchange",window.addEventListener("online",this._onWindowOnline,!1),window.addEventListener("resize",this._onWindowResize,!1),window.addEventListener("orientationchange",this._onWindowResize,!1),window.addEventListener(this._fullscreenchangeEvent,this._onWindowResize,!1),window.addEventListener("visibilitychange",this._onVisibilityChange,!1),this.handlers=new M4(this,x),this._localFontFamily=x.localFontFamily,this._localIdeographFontFamily=x.localIdeographFontFamily,(x.style||!x.testMode)&&this.setStyle(x.style||a.e.DEFAULT_STYLE,{config:x.config,localFontFamily:this._localFontFamily,localIdeographFontFamily:this._localIdeographFontFamily}),x.projection&&this.setProjection(x.projection),x.hash&&(this._hash=new QS(typeof x.hash=="string"&&x.hash||void 0).addTo(this)),!this._hash||!this._hash._onHashChange()){u.center==null&&u.zoom==null||(this.transform._unmodified=!1),this.jumpTo({center:x.center,zoom:x.zoom,bearing:x.bearing,pitch:x.pitch});const f=x.bounds;f&&(this.resize(),this.fitBounds(f,Object.assign({},x.fitBoundsOptions,{duration:0})))}this.resize(),x.attributionControl&&this.addControl(new fv({customAttribution:x.customAttribution})),this._logoControl=new pv,this.addControl(this._logoControl,x.logoPosition),this.on("style.load",()=>{this.transform.unmodified&&this.jumpTo(this.style.stylesheet),this._postStyleLoadEvent(),this._postStyleWithAppearanceEvent(),this._setupIndoor()}),this.on("data",f=>{this._update(f.dataType==="style"),this.fire(new a.z(`${f.dataType}data`,f))}),this.on("dataloading",f=>{this.fire(new a.z(`${f.dataType}dataloading`,f))}),this._interactions=new ed(this)}_getMapId(){return this._mapId}addControl(x,u){if(u===void 0&&(u=x.getDefaultPosition?x.getDefaultPosition():"top-right"),!x||!x.onAdd)return this.fire(new a.y(new Error("Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.")));const f=x.onAdd(this);this._controls.push(x);const v=this._controlPositions[u];return u.indexOf("bottom")!==-1?v.insertBefore(f,v.firstChild):v.appendChild(f),this}removeControl(x){if(!x||!x.onRemove)return this.fire(new a.y(new Error("Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.")));const u=this._controls.indexOf(x);return u>-1&&this._controls.splice(u,1),x.onRemove(this),this}hasControl(x){return this._controls.indexOf(x)>-1}getContainer(){return this._container}getCanvasContainer(){return this._canvasContainer}getCanvas(){return this._canvas}resize(x){if(this._updateContainerDimensions(),this._containerWidth===this.transform.width&&this._containerHeight===this.transform.height)return this;this._resizeCanvas(this._containerWidth,this._containerHeight),this.transform.resize(this._containerWidth,this._containerHeight),this.painter.resize(Math.ceil(this._containerWidth),Math.ceil(this._containerHeight));const u=!this._moving;return u&&this.fire(new a.z("movestart",x)).fire(new a.z("move",x)),this.fire(new a.z("resize",x)),u&&this.fire(new a.z("moveend",x)),this}getBounds(){return this.transform.getBounds()}getMaxBounds(){return this.transform.getMaxBounds()||null}setMaxBounds(x){return this.transform.setMaxBounds(a.aI.convert(x)),this._update()}setMinZoom(x){if((x=x??-2)>=-2&&x<=this.transform.maxZoom)return this.transform.minZoom=x,this._update(),this.getZoom()=this.transform.minZoom)return this.transform.maxZoom=x,this._update(),this.getZoom()>x?this.setZoom(x):this.fire(new a.z("zoomstart")).fire(new a.z("zoom")).fire(new a.z("zoomend")),this;throw new Error("maxZoom must be greater than the current minZoom")}getMaxZoom(){return this.transform.maxZoom}setMinPitch(x){if((x=x??0)<0)throw new Error("minPitch must be greater than or equal to 0");if(x>=0&&x<=this.transform.maxPitch)return this.transform.minPitch=x,this._update(),this.getPitch()85)throw new Error("maxPitch must be less than or equal to 85");if(x>=this.transform.minPitch)return this.transform.maxPitch=x,this._update(),this.getPitch()>x?this.setPitch(x):this.fire(new a.z("pitchstart")).fire(new a.z("pitch")).fire(new a.z("pitchend")),this;throw new Error("maxPitch must be greater than or equal to minPitch")}getMaxPitch(){return this.transform.maxPitch}getScaleFactor(){return this._scaleFactor}setScaleFactor(x){return this._scaleFactor=x,this.painter.scaleFactor=x,this._scaleFactorChanged=!0,this.style._updateFilteredLayers(u=>u.type==="symbol"),this._update(!0),this}getRenderWorldCopies(){return this.transform.renderWorldCopies}setRenderWorldCopies(x){return this.transform.renderWorldCopies=x,this.transform.renderWorldCopies||this._forceMarkerAndPopupUpdate(!0),this._update()}getLanguage(){return this._language}_parseLanguage(x){return x==="auto"?navigator.language:Array.isArray(x)?x.length===0?void 0:x.map(u=>u==="auto"?navigator.language:u):x}setLanguage(x){const u=this._parseLanguage(x);if(!this.style||u===this._language)return this;this._language=u,this.style.reloadSources();for(const f of this._controls)f._setLanguage&&f._setLanguage(this._language);return this}getWorldview(){return this._worldview}setWorldview(x){return this.style&&x!==this._worldview?(this._worldview=x,this._styleDirty=!0,this.style.reloadSources(),this):this}getProjection(){return this.transform.mercatorFromTransition?{name:"globe",center:[0,0]}:this.transform.getProjection()}_showingGlobe(){return this.transform.projection.name==="globe"}setProjection(x){return this._lazyInitEmptyStyle(),x?typeof x=="string"&&(x={name:x}):x=null,this._useExplicitProjection=!!x,this._prioritizeAndUpdateProjection(x,this.style.projection)}_updateProjectionTransition(){if(this.getProjection().name!=="globe")return;const x=this.transform,u=x.projection.name;let f;u==="globe"&&x.zoom>=a.cL?(x.setMercatorFromTransition(),f=!0):u==="mercator"&&x.zoom=a.cL?this.transform.setMercatorFromTransition():this.transform.setProjection(x),this.style.applyProjectionUpdate();const v=this.transform.getProjection().name==="mercator"&&f!==this.transform.mercatorFromTransition;return(u||v)&&(this.painter.clearBackgroundTiles(),this.style.clearSources(),this._update(!0),this._forceMarkerAndPopupUpdate(!0)),this}project(x,u){return this.transform.locationPoint3D(a.aT.convert(x),u)}unproject(x,u){return this.transform.pointLocation3D(a.P.convert(x),u)}isMoving(){return this._moving||this.handlers&&this.handlers.isMoving()||!1}isZooming(){return this._zooming||this.handlers&&this.handlers.isZooming()||!1}isRotating(){return this._rotating||this.handlers&&this.handlers.isRotating()||!1}_isDragging(){return this.handlers&&this.handlers._isDragging()||!1}_createDelegatedListener(x,u,f){const v=S=>{let T=[];if(Array.isArray(u)){const E=u.filter(L=>this.getLayer(L));T=E.length?this.queryRenderedFeatures(S,{layers:E}):[]}else T=this.queryRenderedFeatures(S,{target:u});return T};if(x==="mouseenter"||x==="mouseover"){let S=!1;return{listener:f,targets:u,delegates:{mousemove:E=>{const L=v(E.point);L.length?S||(S=!0,f.call(this,new ac(x,this,E.originalEvent,{features:L}))):S=!1},mouseout:()=>{S=!1}}}}if(x==="mouseleave"||x==="mouseout"){let S=!1;return{listener:f,targets:u,delegates:{mousemove:L=>{v(L.point).length?S=!0:S&&(S=!1,f.call(this,new ac(x,this,L.originalEvent)))},mouseout:L=>{S&&(S=!1,f.call(this,new ac(x,this,L.originalEvent)))}}}}{const S=T=>{const E=v(T.point);E.length&&(T.features=E,f.call(this,T),delete T.features)};return{listener:f,targets:u,delegates:{[x]:S}}}}on(x,u,f){if(typeof u=="function"||f===void 0)return super.on(x,u);if(typeof u=="string"&&(u=[u]),!this._areTargetsValid(u))return this;const v=this._createDelegatedListener(x,u,f);this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[x]=this._delegatedListeners[x]||[],this._delegatedListeners[x].push(v);for(const S in v.delegates)this.on(S,v.delegates[S]);return this}once(x,u,f){if(typeof u=="function"||f===void 0)return super.once(x,u);if(typeof u=="string"&&(u=[u]),!this._areTargetsValid(u))return this;const v=this._createDelegatedListener(x,u,f);for(const S in v.delegates)this.once(S,v.delegates[S]);return this}off(x,u,f){if(typeof u=="function"||f===void 0)return super.off(x,u);if(typeof u=="string"&&(u=[u]),!this._areTargetsValid(u))return this;const v=this._delegatedListeners?this._delegatedListeners[x]:void 0;return v&&(S=>{for(let T=0;T{if(f){const S=typeof f=="string"?f:f instanceof Error?f.message:f.error;a.w(`Unable to perform style diff: ${S}. Rebuilding the style from scratch.`),this._updateStyle(x,u)}else v&&this._update(!0)},()=>this._postStyleLoadEvent()),this):(this._localIdeographFontFamily=u.localIdeographFontFamily,this._localFontFamily=u.localFontFamily,this._updateStyle(x,u))}_getUIString(x){const u=this._locale[x];if(u==null)throw new Error(`Missing UI string '${x}'`);return u}_updateStyle(x,u){if(this.style&&(this.style.setEventedParent(null),this.style._remove(),this.style=void 0),x){const f=Object.assign({},u);u&&u.config&&(f.initialConfig=u.config,delete f.config),this.style=new wu(this,f).load(x),this.style.setEventedParent(this,{style:this.style})}return this._updateTerrain(),this}_lazyInitEmptyStyle(){this.style||(this.style=new wu(this,{}),this.style.setEventedParent(this,{style:this.style}),this.style.loadEmpty())}getStyle(){if(this.style)return this.style.serialize()}isStyleLoaded(){return this.style?this.style.loaded():(a.w("There is no style added to the map."),!1)}_isValidId(x){return x==null?(this.fire(new a.y(new Error("IDs can't be empty."))),!1):!a.dr(x)||(this.fire(new a.y(new Error(`IDs can't contain special symbols: "${x}".`))),!1)}_isTargetValid(x){return"featuresetId"in x?this._isValidId("importId"in x?x.importId:x.featuresetId):"layerId"in x&&this._isValidId(x.layerId)}_areTargetsValid(x){if(Array.isArray(x)){for(const u of x)if(!this._isValidId(u))return!1;return!0}return this._isTargetValid(x)}addSource(x,u){return this._isValidId(x)?(this._lazyInitEmptyStyle(),this.style.addSource(x,u),this._update(!0)):this}isSourceLoaded(x){return!!this._isValidId(x)&&!!this.style&&this.style._isSourceCacheLoaded(x)}areTilesLoaded(){return this.style.areTilesLoaded()}addSourceType(x,u,f){this._lazyInitEmptyStyle(),this.style.addSourceType(x,u,f)}removeSource(x){return this._isValidId(x)?(this.style.removeSource(x),this._updateTerrain(),this._update(!0)):this}getSource(x){return this._isValidId(x)?this.style.getOwnSource(x):null}addImage(x,u,{pixelRatio:f=1,sdf:v=!1,stretchX:S,stretchY:T,content:E}={}){this._lazyInitEmptyStyle();const L=a.I.from(x);if(u instanceof HTMLImageElement||ImageBitmap&&u instanceof ImageBitmap){const{width:B,height:q,data:G}=a.o.getImageData(u);this.style.addImage(L,{data:new a.q({width:B,height:q},G),pixelRatio:f,stretchX:S,stretchY:T,content:E,sdf:v,version:0,usvg:!1})}else if(u.width===void 0||u.height===void 0)this.fire(new a.y(new Error("Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));else{const{width:B,height:q}=u,G=u;this.style.addImage(L,{data:new a.q({width:B,height:q},new Uint8Array(G.data)),pixelRatio:f,stretchX:S,stretchY:T,content:E,sdf:v,usvg:!1,version:0,userImage:G}),G.onAdd&&G.onAdd(this,x)}}updateImage(x,u){this._lazyInitEmptyStyle();const f=a.I.from(x),v=this.style.getImage(f);if(!v)return void this.fire(new a.y(new Error("The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.")));const S=u instanceof HTMLImageElement||ImageBitmap&&u instanceof ImageBitmap?a.o.getImageData(u):u,{width:T,height:E,data:L}=S;if(T===void 0||E===void 0)return void this.fire(new a.y(new Error("Invalid arguments to map.updateImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));if(T!==(v.usvg?v.icon.usvg_tree.width:v.data.width)||E!==(v.usvg?v.icon.usvg_tree.height:v.data.height))return void this.fire(new a.y(new Error(`The width and height of the updated image (${T}, ${E}) must be that same as the previous version of the image (${v.data.width}, ${v.data.height})`)));const B=!(u instanceof HTMLImageElement||ImageBitmap&&u instanceof ImageBitmap);let q=!1;v.usvg?(v.data=new a.q({width:T,height:E},new Uint8Array(L)),v.usvg=!1,v.icon=void 0,q=!0):v.data.replace(L,B),this.style.updateImage(f,v,q)}hasImage(x){return x?!!this.style&&!!this.style.getImage(a.I.from(x)):(this.fire(new a.y(new Error("Missing required image id"))),!1)}removeImage(x){this.style.removeImage(a.I.from(x))}loadImage(x,u){a.n(this._requestManager.transformRequest(x,a.R.Image),(f,v)=>{u(f,v instanceof HTMLImageElement?a.o.getImageData(v):v)})}listImages(){return this.style.listImages().map(x=>x.name)}addModel(x,u){this._lazyInitEmptyStyle(),this.style.addModel(x,u)}hasModel(x){return x?this.style.hasModel(x):(this.fire(new a.y(new Error("Missing required model id"))),!1)}removeModel(x){this.style.removeModel(x)}listModels(){return this.style.listModels()}addLayer(x,u){return this._isValidId(x.id)?(this._lazyInitEmptyStyle(),this.style.addLayer(x,u),this._update(!0)):this}getSlot(x){const u=this.getLayer(x);return u&&u.slot||null}setSlot(x,u){return this.style.setSlot(x,u),this.style.mergeLayers(),this._update(!0)}addImport(x,u){return this.style.addImport(x,u).catch(f=>this.fire(new a.y(new Error("Failed to add import",f)))),this}updateImport(x,u){return typeof u!="string"&&u.id!==x?(this.removeImport(x),this.addImport(u)):(this.style.updateImport(x,u),this._update(!0))}removeImport(x){return this.style.removeImport(x),this}moveImport(x,u){return this.style.moveImport(x,u),this._update(!0)}moveLayer(x,u){return this._isValidId(x)?(this.style.moveLayer(x,u),this._update(!0)):this}removeLayer(x){return this._isValidId(x)?(this.style.removeLayer(x),this._update(!0)):this}getLayer(x){if(!this._isValidId(x))return null;const u=this.style.getOwnLayer(x);return u?u.type==="custom"?u.implementation:u.serialize():void 0}getSlots(){return this.style.getSlots()}setLayerZoomRange(x,u,f){return this._isValidId(x)?(this.style.setLayerZoomRange(x,u,f),this._update(!0)):this}setFilter(x,u,f={}){return this._isValidId(x)?(this.style.setFilter(x,u,f),this._update(!0)):this}getFilter(x){return this._isValidId(x)?this.style.getFilter(x):null}setPaintProperty(x,u,f,v={}){return this._isValidId(x)?(this.style.setPaintProperty(x,u,f,v),this._update(!0)):this}getPaintProperty(x,u){return this._isValidId(x)?this.style.getPaintProperty(x,u):null}setLayoutProperty(x,u,f,v={}){return this._isValidId(x)?(this.style.setLayoutProperty(x,u,f,v),this._update(!0)):this}getLayoutProperty(x,u){return this._isValidId(x)?this.style.getLayoutProperty(x,u):null}setLayerProperty(x,u,f,v={}){return this._isValidId(x)?(u==="appearances"&&this._postAddingAppearancesToStyleEvent(),this.style.setLayerProperty(x,u,f,v),this._update(!0)):this}getGlyphsUrl(){return this.style.getGlyphsUrl()}setGlyphsUrl(x){return this.style.setGlyphsUrl(x),this._update(!0)}getSchema(x){return this.style.getSchema(x)}setSchema(x,u){return this.style.setSchema(x,u),this._update(!0)}getConfig(x){return this.style.getConfig(x)}setConfig(x,u){return this.style.setConfig(x,u),this._update(!0)}getConfigProperty(x,u){return this.style.getConfigProperty(x,u)}setConfigProperty(x,u,f){return this.style.setConfigProperty(x,u,f),this._update(!0)}getFeaturesetDescriptors(x){return this.style.getFeaturesetDescriptors(x)}setLights(x){if(this._lazyInitEmptyStyle(),x&&x.length===1&&x[0].type==="flat"){const u=x[0];u.properties?this.style.setFlatLight(u.properties,u.id,{}):this.style.setFlatLight({},"flat")}else this.style.setLights(x),this.painter.terrain&&(this.painter.terrain.invalidateRenderCache=!0);return this._update(!0)}getLights(){const x=this.style.getLights()||[];return x.length===0&&x.push({id:this.style.light.id,type:"flat",properties:this.style.getFlatLight()}),x}setLight(x,u={}){return console.log("The `map.setLight` function is deprecated, prefer using `map.setLights` with `flat` light type instead."),this.setLights([{id:"flat",type:"flat",properties:x}])}getLight(){return console.log("The `map.getLight` function is deprecated, prefer using `map.getLights` instead."),this.style.getFlatLight()}setTerrain(x){return this._lazyInitEmptyStyle(),!x&&this.transform.projection.requiresDraping?this.style.setTerrainForDraping():this.style.setTerrain(x),this._averageElevationLastSampledAt=-1/0,this._update(!0)}getTerrain(){return this.style?this.style.getTerrain():null}setFog(x){return this._lazyInitEmptyStyle(),this.style.setFog(x),this._update(!0)}getFog(){return this.style?this.style.getFog():null}setSnow(x){return this._lazyInitEmptyStyle(),this.style.setSnow(x),this._update(!0)}getSnow(){return this.style?this.style.getSnow():null}setRain(x){return this._lazyInitEmptyStyle(),this.style.setRain(x),this._update(!0)}getRain(){return this.style?this.style.getRain():null}setColorTheme(x){return this._lazyInitEmptyStyle(),this.style.setColorTheme(x),this._update(!0)}setImportColorTheme(x,u){return this._lazyInitEmptyStyle(),this.style.setImportColorTheme(x,u),this._update(!0)}setCamera(x){return this.style.setCamera(x),this._triggerCameraUpdate(x)}_triggerCameraUpdate(x){return this._update(this.transform.setOrthographicProjectionAtLowPitch(x["camera-projection"]==="orthographic"))}getCamera(){return this.style.camera}_queryFogOpacity(x){return this.style&&this.style.fog?this.style.fog.getOpacityAtLatLng(a.aT.convert(x),this.transform):0}setFeatureState(x,u){return x.source&&!this._isValidId(x.source)?this:(this.style.setFeatureState(x,u),this._update())}removeFeatureState(x,u){return x.source&&!this._isValidId(x.source)?this:(this.style.removeFeatureState(x,u),this._update())}getFeatureState(x){return x.source&&!this._isValidId(x.source)?null:this.style.getFeatureState(x)}_selectIndoorFloor(x){this.indoor.selectFloor(x)}_setIndoorActiveFloorsVisibility(x){this.indoor.setActiveFloorsVisibility(x)}_addIndoorControl(){this._indoorControl||(this._indoorControl=new Og),this.addControl(this._indoorControl,"right")}_removeIndoorControl(){this._indoorControl&&this.removeControl(this._indoorControl)}_updateContainerDimensions(){if(!this._container)return;const x=this._container.getBoundingClientRect().width||400,u=this._container.getBoundingClientRect().height||300;let f,v,S,T=this._container;for(;T&&(!v||!S);){const E=window.getComputedStyle(T).transform;E&&E!=="none"&&(f=E.match(/matrix.*\((.+)\)/)[1].split(", "),f[0]&&f[0]!=="0"&&f[0]!=="1"&&(v=f[0]),f[3]&&f[3]!=="0"&&f[3]!=="1"&&(S=f[3])),T=T.parentElement}this._containerWidth=v?Math.abs(x/v):x,this._containerHeight=S?Math.abs(u/S):u}_detectMissingCSS(){window.getComputedStyle(this._missingCSSCanary).getPropertyValue("background-color")!=="rgb(250, 128, 114)"&&a.w("This page appears to be missing CSS declarations for Mapbox GL JS, which may cause the map to display incorrectly. Please ensure your page includes mapbox-gl.css, as described in https://www.mapbox.com/mapbox-gl-js/api/.")}_setupIndoor(){this.style.isIndoorEnabled()&&(this.indoor=new lE(this.style),this.on("load",()=>{this._addIndoorControl(),this.indoor._updateUI(this.transform.zoom,this.transform.center,this.transform.getBounds()),this.on("move",()=>{this.indoor._updateUI(this.transform.zoom,this.transform.center,this.transform.getBounds())}),this.on("idle",()=>{this.indoor._updateUI(this.transform.zoom,this.transform.center,this.transform.getBounds())})}))}_setupContainer(){const x=this._container;x.classList.add("mapboxgl-map"),(this._missingCSSCanary=A("div","mapboxgl-canary",x)).style.visibility="hidden",this._detectMissingCSS();const u=this._canvasContainer=A("div","mapboxgl-canvas-container",x);this._canvas=A("canvas","mapboxgl-canvas",u),this._interactive&&(u.classList.add("mapboxgl-interactive"),this._canvas.setAttribute("tabindex","0")),this._canvas.addEventListener("webglcontextlost",this._contextLost,!1),this._canvas.addEventListener("webglcontextrestored",this._contextRestored,!1),this._canvas.setAttribute("aria-label",this._getUIString("Map.Title")),this._canvas.setAttribute("role","region"),this._updateContainerDimensions(),this._resizeCanvas(this._containerWidth,this._containerHeight);const f=this._controlContainer=A("div","mapboxgl-control-container",x),v=this._controlPositions={};["top-left","top","top-right","right","bottom-right","bottom","bottom-left","left"].forEach(S=>{v[S]=A("div",`mapboxgl-ctrl-${S}`,f)}),this._container.addEventListener("scroll",this._onMapScroll,!1)}_resizeCanvas(x,u){const f=a.o.devicePixelRatio||1;this._canvas.width=f*Math.ceil(x),this._canvas.height=f*Math.ceil(u),this._canvas.style.width=`${x}px`,this._canvas.style.height=`${u}px`}_addMarker(x){this._markers.push(x)}_removeMarker(x){const u=this._markers.indexOf(x);u!==-1&&this._markers.splice(u,1)}_addPopup(x){this._popups.push(x)}_removePopup(x){const u=this._popups.indexOf(x);u!==-1&&this._popups.splice(u,1)}_setupPainter(){const x=Object.assign({},P.supported.webGLContextAttributes,{failIfMajorPerformanceCaveat:this._failIfMajorPerformanceCaveat,preserveDrawingBuffer:this._preserveDrawingBuffer,antialias:this._antialias||!1}),u=this._canvas.getContext("webgl2",x);u?(Lt(u,!0),this.painter=new yb(u,this._contextCreateOptions,this.transform,this._scaleFactor,this._worldview),this.on("data",f=>{f.dataType==="source"&&this.painter.setTileLoadedFlag(!0)}),a.k.testSupport(u)):this.fire(new a.y(new Error("Failed to initialize WebGL")))}_contextLost(x){x.preventDefault(),this._frame&&(this._frame.cancel(),this._frame=null),this.fire(new a.z("webglcontextlost",{originalEvent:x}))}_contextRestored(x){this._setupPainter(),this.painter.resize(Math.ceil(this._containerWidth),Math.ceil(this._containerHeight)),this._updateTerrain(),this.style&&(this.style.clearLayers(),this.style.imageManager.destroyAtlasTextures(),this.style.reloadModels(),this.style.clearSources()),this._update(),this.fire(new a.z("webglcontextrestored",{originalEvent:x}))}_onMapScroll(x){if(x.target===this._container)return this._container.scrollTop=0,this._container.scrollLeft=0,!1}idle(){return!this.isMoving()&&this.loaded()}loaded(){return!this._styleDirty&&!this._sourcesDirty&&!!this.style&&this.style.loaded()}frameReady(){return this.loaded()&&!this._placementDirty}_update(x){return this.style?(this._styleDirty=this._styleDirty||x,this._sourcesDirty=!0,this.triggerRepaint(),this):this}_requestRenderFrame(x){return this._update(),this._renderTaskQueue.add(x)}_cancelRenderFrame(x){this._renderTaskQueue.remove(x)}_requestDomTask(x){!this.loaded()||this.loaded()&&!this.isMoving()?x():this._domRenderTaskQueue.add(x)}_render(x){let u;this.fire(new a.z("renderstart")),++this._frameId;const f=this.painter.context.extTimerQuery,v=a.o.now(),S=this.painter.context.gl;if(this.listens("gpu-timing-frame")&&(u=S.createQuery(),S.beginQuery(f.TIME_ELAPSED_EXT,u)),this.painter.context.setDirty(),this.painter.setBaseState(),(this.isMoving()||this.isRotating()||this.isZooming())&&(this._interactionRange[0]=Math.min(this._interactionRange[0],performance.now()),this._interactionRange[1]=Math.max(this._interactionRange[1],performance.now())),this._renderTaskQueue.run(x),this._domRenderTaskQueue.run(x),this._removed)return;this._updateProjectionTransition();const T=this._isInitialLoad?0:this._fadeDuration;if(this.style&&this._styleDirty){this._styleDirty=!1;const q=this.transform.zoom,G=this.transform.pitch,ee=a.o.now(),J=new a.ac(q,{now:ee,fadeDuration:T,pitch:G,transition:this.style.transition,worldview:this._worldview});this.style.update(J)}this.style&&this.style.hasFogTransition()&&(this.style._markersNeedUpdate=!0,this._sourcesDirty=!0);let E=!1;this.style&&this._sourcesDirty?(this._sourcesDirty=!1,this.painter._updateFog(this.style),this._updateTerrain(),E=this._updateAverageElevation(v),this.style.updateSources(this.transform),this.style.updateImageProviders(),this.isMoving()||this._forceMarkerAndPopupUpdate()):E=this._updateAverageElevation(v);const L=this.style&&this.style._updatePlacement(this.painter,this.painter.transform,this.showCollisionBoxes,T,this._crossSourceCollisions,this.painter.replacementSource,this._scaleFactorChanged);if(this._scaleFactorChanged&&(this._scaleFactorChanged=!1),L&&(this._placementDirty=L.needsRerender),this.style&&this.painter.render(this.style,{showTileBoundaries:this.showTileBoundaries,showParseStatus:this.showParseStatus,wireframe:{terrain:this.showTerrainWireframe,layers2D:this.showLayers2DWireframe,layers3D:this.showLayers3DWireframe},showOverdrawInspector:this._showOverdrawInspector,showQueryGeometry:!!this._showQueryGeometry,showTileAABBs:this.showTileAABBs,rotating:this.isRotating(),zooming:this.isZooming(),moving:this.isMoving(),fadeDuration:T,isInitialLoad:this._isInitialLoad,showPadding:this.showPadding,gpuTiming:!!this.listens("gpu-timing-layer"),gpuTimingDeferredRender:!!this.listens("gpu-timing-deferred-render"),speedIndexTiming:this.speedIndexTiming}),this.fire(new a.z("render")),this.loaded()&&!this._loaded&&(this._loaded=!0,_.mark(g.load),this.fire(new a.z("load"))),this.style&&this.style.hasTransitions()&&(this._styleDirty=!0),this.style&&(this.style.snow||this.style.rain)&&(this._styleDirty=!0),this.style&&this.style.imageManager.hasPatternsInFlight()&&(this._styleDirty=!0),this.style&&!this.style.modelManager.isLoaded()&&(this._styleDirty=!0),this.style&&!this._placementDirty&&this.style._releaseSymbolFadeTiles(),u){const q=a.o.now()-v;S.endQuery(f.TIME_ELAPSED_EXT),setTimeout(()=>{const G=S.getQueryParameter(u,S.QUERY_RESULT)/1e6;S.deleteQuery(u),this.fire(new a.z("gpu-timing-frame",{cpuTime:q,gpuTime:G}))},50)}if(this.listens("gpu-timing-layer")){const q=this.painter.collectGpuTimers();setTimeout(()=>{const G=this.painter.queryGpuTimers(q);this.fire(new a.z("gpu-timing-layer",{layerTimes:G}))},50)}if(this.listens("gpu-timing-deferred-render")){const q=this.painter.collectDeferredRenderGpuQueries();setTimeout(()=>{const G=this.painter.queryGpuTimeDeferredRender(q);this.fire(new a.z("gpu-timing-deferred-render",{gpuTime:G}))},50)}const B=this._sourcesDirty||this._styleDirty||this._placementDirty||E;if(B||this._repaint)this.triggerRepaint();else{const q=this.idle();if(q&&(E=this._updateAverageElevation(v,!0)),E)this.triggerRepaint();else if(this._triggerFrame(!1),q&&(this.fire(new a.z("idle")),this._isInitialLoad=!1,this.speedIndexTiming)){const G=this._calculateSpeedIndex();this.fire(new a.z("speedindexcompleted",{speedIndex:G})),this.speedIndexTiming=!1}}!this._loaded||this._fullyLoaded||B||(this._fullyLoaded=!0,_.mark(g.fullLoad),this._performanceMetricsCollection&&ut(this._requestManager._customAccessToken,{width:this.painter.width,height:this.painter.height,interactionRange:this._interactionRange,visibilityHidden:this._visibilityHidden,terrainEnabled:!!this.painter.style.getTerrain(),fogEnabled:!!this.painter.style.getFog(),projection:this.getProjection().name,zoom:this.transform.zoom,renderer:this.painter.context.renderer,vendor:this.painter.context.vendor}),this._authenticate())}_forceMarkerAndPopupUpdate(x){for(const u of this._markers)x&&!this.getRenderWorldCopies()&&(u._lngLat=u._lngLat.wrap()),u._update();for(const u of this._popups)!x||this.getRenderWorldCopies()||u._trackPointer||(u._lngLat=u._lngLat.wrap()),u._update()}_updateAverageElevation(x,u=!1){const f=S=>(this.transform.averageElevation=S,this._update(!1),!0);if(!this.painter.averageElevationNeedsEasing())return this.transform.averageElevation!==0&&f(0);const v=this.transform.elevation&&this.transform.elevation.exaggeration()!==this._averageElevationExaggeration;if(v||(u||x-this._averageElevationLastSampledAt>500)&&!this._averageElevation.isEasing(x)){const S=this.transform.averageElevation;let T=this.transform.sampleAverageElevation();this.transform.elevation!=null&&(this._averageElevationExaggeration=this.transform.elevation.exaggeration()),isNaN(T)?T=0:this._averageElevationLastSampledAt=x;const E=Math.abs(S-T);if(E>1){if(this._isInitialLoad||v)return this._averageElevation.jumpTo(T),f(T);this._averageElevation.easeTo(T,x,300)}else if(E>1e-4)return this._averageElevation.jumpTo(T),f(T)}return!!this._averageElevation.isEasing(x)&&f(this._averageElevation.getValue(x))}_authenticate(){$t(this._getMapId(),this._requestManager._skuToken,this._requestManager._customAccessToken,x=>{if(x&&(x.message===pe||x.status===401)){const u=this.painter.context.gl;Lt(u,!1),this._logoControl instanceof pv&&this._logoControl._updateLogo(),u&&u.clear(u.DEPTH_BUFFER_BIT|u.COLOR_BUFFER_BIT|u.STENCIL_BUFFER_BIT),this._silenceAuthErrors||this.fire(new a.y(new Error("A valid Mapbox access token is required to use Mapbox GL JS. To create an account or a new access token, visit https://account.mapbox.com/")))}}),nt(this._getMapId(),this._requestManager._skuToken,this._requestManager._customAccessToken,()=>{})}_postStyleLoadEvent(){this.style.globalId&>(this._requestManager._customAccessToken,{map:this,style:this.style.globalId,importedStyles:this.style.getImportGlobalIds()})}_postStyleWithAppearanceEvent(){this.style.globalId&&this.style.hasAppearances()&&Oe(this._requestManager._customAccessToken)}_postAddingAppearancesToStyleEvent(){Be(this._requestManager._customAccessToken)}_updateTerrain(){const x=this._isDragging();this.painter.updateTerrain(this.style,x)}_calculateSpeedIndex(){const x=this.painter.canvasCopy(),u=this.painter.getCanvasCopiesAndTimestamps();u.timeStamps.push(performance.now());const f=this.painter.context.gl,v=f.createFramebuffer();function S(T){f.framebufferTexture2D(f.FRAMEBUFFER,f.COLOR_ATTACHMENT0,f.TEXTURE_2D,T,0);const E=new Uint8Array(f.drawingBufferWidth*f.drawingBufferHeight*4);return f.readPixels(0,0,f.drawingBufferWidth,f.drawingBufferHeight,f.RGBA,f.UNSIGNED_BYTE,E),E}return f.bindFramebuffer(f.FRAMEBUFFER,v),this._canvasPixelComparison(S(x),u.canvasCopies.map(S),u.timeStamps)}_canvasPixelComparison(x,u,f){let v=f[1]-f[0];const S=x.length/4;for(let T=0;T{const f=!!this._renderNextFrame;this._frame=null,this._renderNextFrame=null,f&&this._render(u)}))}_preloadTiles(x){const u=this.style?this.style.getSourceCaches():[];return a.bw(u,(f,v)=>f._preloadTiles(x,v),()=>{this.triggerRepaint()}),this}_onWindowOnline(){this._update()}_onWindowResize(x){this._trackResize&&this.resize({originalEvent:x})._update()}_onVisibilityChange(){document.visibilityState==="hidden"&&this._visibilityHidden++}get showTileBoundaries(){return!!this._showTileBoundaries}set showTileBoundaries(x){this._showTileBoundaries!==x&&(this._showTileBoundaries=x,this._update())}get showParseStatus(){return!!this._showParseStatus}set showParseStatus(x){this._showParseStatus!==x&&(this._showParseStatus=x,this._update())}get showTerrainWireframe(){return!!this._showTerrainWireframe}set showTerrainWireframe(x){this._showTerrainWireframe!==x&&(this._showTerrainWireframe=x,this._update())}get showLayers2DWireframe(){return!!this._showLayers2DWireframe}set showLayers2DWireframe(x){this._showLayers2DWireframe!==x&&(this._showLayers2DWireframe=x,this._update())}get showLayers3DWireframe(){return!!this._showLayers3DWireframe}set showLayers3DWireframe(x){this._showLayers3DWireframe!==x&&(this._showLayers3DWireframe=x,this._update())}get speedIndexTiming(){return!!this._speedIndexTiming}set speedIndexTiming(x){this._speedIndexTiming!==x&&(this._speedIndexTiming=x,this._update())}get showPadding(){return!!this._showPadding}set showPadding(x){this._showPadding!==x&&(this._showPadding=x,this._update())}get showCollisionBoxes(){return!!this._showCollisionBoxes}set showCollisionBoxes(x){this._showCollisionBoxes!==x&&(this._showCollisionBoxes=x,this.style&&x?this.style._generateCollisionBoxes():this._update())}get showOverdrawInspector(){return!!this._showOverdrawInspector}set showOverdrawInspector(x){this._showOverdrawInspector!==x&&(this._showOverdrawInspector=x,this._update())}get repaint(){return!!this._repaint}set repaint(x){this._repaint!==x&&(this._repaint=x,this.triggerRepaint())}get vertices(){return!!this._vertices}set vertices(x){this._vertices=x,this._update()}get showTileAABBs(){return!!this._showTileAABBs}set showTileAABBs(x){this._showTileAABBs!==x&&(this._showTileAABBs=x,x&&this._update())}_setCacheLimits(x,u){a.f4(x,u)}get version(){return m}},NavigationControl:class{constructor(x={}){this.options=Object.assign({},D4,x),this._container=A("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._container.addEventListener("contextmenu",u=>u.preventDefault()),this.options.showZoom&&(a.aY(["_setButtonTitle","_updateZoomButtons"],this),this._zoomInButton=this._createButton("mapboxgl-ctrl-zoom-in",u=>{this._map&&this._map.zoomIn({},{originalEvent:u})}),A("span","mapboxgl-ctrl-icon",this._zoomInButton).setAttribute("aria-hidden","true"),this._zoomOutButton=this._createButton("mapboxgl-ctrl-zoom-out",u=>{this._map&&this._map.zoomOut({},{originalEvent:u})}),A("span","mapboxgl-ctrl-icon",this._zoomOutButton).setAttribute("aria-hidden","true")),this.options.showCompass&&(a.aY(["_rotateCompassArrow"],this),this._compass=this._createButton("mapboxgl-ctrl-compass",u=>{const f=this._map;f&&(this.options.visualizePitch?f.resetNorthPitch({},{originalEvent:u}):f.resetNorth({},{originalEvent:u}))}),this._compassIcon=A("span","mapboxgl-ctrl-icon",this._compass),this._compassIcon.setAttribute("aria-hidden","true"))}_updateZoomButtons(){const x=this._map;if(!x)return;const u=x.getZoom(),f=u===x.getMaxZoom(),v=u===x.getMinZoom();this._zoomInButton.disabled=f,this._zoomOutButton.disabled=v,this._zoomInButton.setAttribute("aria-disabled",f.toString()),this._zoomOutButton.setAttribute("aria-disabled",v.toString())}_rotateCompassArrow(){const x=this._map;if(!x)return;const u=this.options.visualizePitch?`scale(${1/Math.pow(Math.cos(x.transform.pitch*(Math.PI/180)),.5)}) rotateX(${x.transform.pitch}deg) rotateZ(${x.transform.angle*(180/Math.PI)}deg)`:`rotate(${x.transform.angle*(180/Math.PI)}deg)`;x._requestDomTask(()=>{this._compassIcon&&(this._compassIcon.style.transform=u)})}onAdd(x){return this._map=x,this.options.showZoom&&(this._setButtonTitle(this._zoomInButton,"ZoomIn"),this._setButtonTitle(this._zoomOutButton,"ZoomOut"),x.on("zoom",this._updateZoomButtons),this._updateZoomButtons()),this.options.showCompass&&(this._setButtonTitle(this._compass,"ResetBearing"),this.options.visualizePitch&&x.on("pitch",this._rotateCompassArrow),x.on("rotate",this._rotateCompassArrow),this._rotateCompassArrow(),this._handler=new L4(x,this._compass,this.options.visualizePitch)),this._container}onRemove(){const x=this._map;x&&(this._container.remove(),this.options.showZoom&&x.off("zoom",this._updateZoomButtons),this.options.showCompass&&(this.options.visualizePitch&&x.off("pitch",this._rotateCompassArrow),x.off("rotate",this._rotateCompassArrow),this._handler&&this._handler.off(),this._handler=void 0),this._map=void 0)}_createButton(x,u){const f=A("button",x,this._container);return f.type="button",f.addEventListener("click",u),f}_setButtonTitle(x,u){if(!this._map)return;const f=this._map._getUIString(`NavigationControl.${u}`);x.setAttribute("aria-label",f),x.firstElementChild&&x.firstElementChild.setAttribute("title",f)}},GeolocateControl:class extends a.E{constructor(x={}){super();const u=navigator.geolocation;this.options=Object.assign({geolocation:u},F4,x),a.aY(["_onSuccess","_onError","_onZoom","_finish","_setupUI","_updateCamera","_updateMarker","_updateMarkerRotation","_onDeviceOrientation"],this),this._updateMarkerRotationThrottled=xb(this._updateMarkerRotation,20),this._numberOfWatches=0}onAdd(x){return this._map=x,this._container=A("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._checkGeolocationSupport(this._setupUI),this._container}onRemove(){this._geolocationWatchID!==void 0&&(this.options.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0),this.options.showUserLocation&&this._userLocationDotMarker&&this._userLocationDotMarker.remove(),this.options.showAccuracyCircle&&this._accuracyCircleMarker&&this._accuracyCircleMarker.remove(),this._container.remove(),this._map.off("zoom",this._onZoom),this._map=void 0,this._numberOfWatches=0,this._noTimeout=!1}_checkGeolocationSupport(x){const u=(f=!!this.options.geolocation)=>{this._supportsGeolocation=f,x(f)};this._supportsGeolocation!==void 0?x(this._supportsGeolocation):navigator.permissions!==void 0?navigator.permissions.query({name:"geolocation"}).then(f=>u(f.state!=="denied")).catch(()=>u()):u()}_isOutOfMapMaxBounds(x){const u=this._map.getMaxBounds(),f=x.coords;return!!u&&(f.longitudeu.getEast()||f.latitudeu.getNorth())}_setErrorState(){switch(this._watchState){case"WAITING_ACTIVE":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error");break;case"ACTIVE_LOCK":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting");break;case"BACKGROUND":this._watchState="BACKGROUND_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting")}}_onSuccess(x){if(this._map){if(this._isOutOfMapMaxBounds(x))return this._setErrorState(),this.fire(new a.z("outofmaxbounds",x)),this._updateMarker(),void this._finish();if(this.options.trackUserLocation)switch(this._lastKnownPosition=x,this._watchState){case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"BACKGROUND":case"BACKGROUND_ERROR":this._watchState="BACKGROUND",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background")}this.options.showUserLocation&&this._watchState!=="OFF"&&this._updateMarker(x),this.options.trackUserLocation&&this._watchState!=="ACTIVE_LOCK"||this._updateCamera(x),this.options.showUserLocation&&this._userLocationDotMarker.removeClassName("mapboxgl-user-location-dot-stale"),this.fire(new a.z("geolocate",Object.assign({coords:x.coords,timestamp:x.timestamp},x.toJSON?{toJSON:x.toJSON.bind(x)}:{}))),this._finish()}}_updateCamera(x){const u=new a.aT(x.coords.longitude,x.coords.latitude),f=x.coords.accuracy,v=this._map.getBearing(),S=Object.assign({bearing:v},this.options.fitBoundsOptions);this._map.fitBounds(u.toBounds(f),S,{geolocateSource:!0})}_updateMarker(x){if(x){const u=new a.aT(x.coords.longitude,x.coords.latitude);this._accuracyCircleMarker.setLngLat(u).addTo(this._map),this._userLocationDotMarker.setLngLat(u).addTo(this._map),this._accuracy=x.coords.accuracy,this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius()}else this._userLocationDotMarker.remove(),this._accuracyCircleMarker.remove()}_updateCircleRadius(){const x=this._map.transform,u=a.cf(1,x._center.lat)*x.worldSize,f=Math.ceil(2*this._accuracy*u);this._circleElement.style.width=`${f}px`,this._circleElement.style.height=`${f}px`}_onZoom(){this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius()}_updateMarkerRotation(){this._userLocationDotMarker&&typeof this._heading=="number"?(this._userLocationDotMarker.setRotation(this._heading),this._userLocationDotMarker.addClassName("mapboxgl-user-location-show-heading")):(this._userLocationDotMarker.removeClassName("mapboxgl-user-location-show-heading"),this._userLocationDotMarker.setRotation(0))}_onError(x){if(this._map){if(this.options.trackUserLocation)if(x.code===1){this._watchState="OFF",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.disabled=!0;const u=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.setAttribute("aria-label",u),this._geolocateButton.firstElementChild&&this._geolocateButton.firstElementChild.setAttribute("title",u),this._geolocationWatchID!==void 0&&this._clearWatch()}else{if(x.code===3&&this._noTimeout)return;this._setErrorState()}this._watchState!=="OFF"&&this.options.showUserLocation&&this._userLocationDotMarker.addClassName("mapboxgl-user-location-dot-stale"),this.fire(new a.z("error",x)),this._finish()}}_finish(){this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0}_setupUI(x){if(this._map!==void 0){if(this._container.addEventListener("contextmenu",u=>u.preventDefault()),this._geolocateButton=A("button","mapboxgl-ctrl-geolocate",this._container),A("span","mapboxgl-ctrl-icon",this._geolocateButton).setAttribute("aria-hidden","true"),this._geolocateButton.type="button",x===!1){a.w("Geolocation support is not available so the GeolocateControl will be disabled.");const u=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.disabled=!0,this._geolocateButton.setAttribute("aria-label",u),this._geolocateButton.firstElementChild&&this._geolocateButton.firstElementChild.setAttribute("title",u)}else{const u=this._map._getUIString("GeolocateControl.FindMyLocation");this._geolocateButton.setAttribute("aria-label",u),this._geolocateButton.firstElementChild&&this._geolocateButton.firstElementChild.setAttribute("title",u)}this.options.trackUserLocation&&(this._geolocateButton.setAttribute("aria-pressed","false"),this._watchState="OFF"),this.options.showUserLocation&&(this._dotElement=A("div","mapboxgl-user-location"),this._dotElement.appendChild(A("div","mapboxgl-user-location-dot")),this._dotElement.appendChild(A("div","mapboxgl-user-location-heading")),this._userLocationDotMarker=new Pb({element:this._dotElement,rotationAlignment:"map",pitchAlignment:"map"}),this._circleElement=A("div","mapboxgl-user-location-accuracy-circle"),this._accuracyCircleMarker=new Pb({element:this._circleElement,pitchAlignment:"map"}),this.options.trackUserLocation&&(this._watchState="OFF"),this._map.on("zoom",this._onZoom)),this._geolocateButton.addEventListener("click",this.trigger.bind(this)),this._setup=!0,this.options.trackUserLocation&&this._map.on("movestart",u=>{u.geolocateSource||this._watchState!=="ACTIVE_LOCK"||u.originalEvent&&u.originalEvent.type==="resize"||(this._watchState="BACKGROUND",this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this.fire(new a.z("trackuserlocationend")))})}}_onDeviceOrientation(x){this._userLocationDotMarker&&(x.webkitCompassHeading?this._heading=x.webkitCompassHeading:x.absolute===!0&&(this._heading=-1*x.alpha),this._updateMarkerRotationThrottled())}trigger(){if(!this._setup)return a.w("Geolocate control triggered before added to a map"),!1;if(this.options.trackUserLocation){switch(this._watchState){case"OFF":this._watchState="WAITING_ACTIVE",this.fire(new a.z("trackuserlocationstart"));break;case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":case"BACKGROUND_ERROR":this._numberOfWatches--,this._noTimeout=!1,this._watchState="OFF",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this.fire(new a.z("trackuserlocationend"));break;case"BACKGROUND":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new a.z("trackuserlocationstart"))}switch(this._watchState){case"WAITING_ACTIVE":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"ACTIVE_LOCK":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"ACTIVE_ERROR":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error");break;case"BACKGROUND":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background");break;case"BACKGROUND_ERROR":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background-error")}if(this._watchState==="OFF"&&this._geolocationWatchID!==void 0)this._clearWatch();else if(this._geolocationWatchID===void 0){let x;this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","true"),this._numberOfWatches++,this._numberOfWatches>1?(x={maximumAge:6e5,timeout:0},this._noTimeout=!0):(x=this.options.positionOptions,this._noTimeout=!1),this._geolocationWatchID=this.options.geolocation.watchPosition(this._onSuccess,this._onError,x),this.options.showUserHeading&&this._addDeviceOrientationListener()}}else this.options.geolocation.getCurrentPosition(this._onSuccess,this._onError,this.options.positionOptions),this._timeoutId=window.setTimeout(this._finish,1e4);return!0}_addDeviceOrientationListener(){const x=()=>{"ondeviceorientationabsolute"in window?window.addEventListener("deviceorientationabsolute",this._onDeviceOrientation):window.addEventListener("deviceorientation",this._onDeviceOrientation)};typeof DeviceMotionEvent<"u"&&typeof DeviceMotionEvent.requestPermission=="function"?DeviceOrientationEvent.requestPermission().then(u=>{u==="granted"&&x()}).catch(console.error):x()}_clearWatch(){this.options.geolocation.clearWatch(this._geolocationWatchID),window.removeEventListener("deviceorientation",this._onDeviceOrientation),window.removeEventListener("deviceorientationabsolute",this._onDeviceOrientation),this._geolocationWatchID=void 0,this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","false"),this.options.showUserLocation&&this._updateMarker(null)}},AttributionControl:fv,ScaleControl:class{constructor(x={}){this.options=Object.assign({},Rg,x),a.aY(["_update","_setScale","setUnit"],this)}getDefaultPosition(){return"bottom-left"}_update(){const x=this.options.maxWidth||100,u=this._map,f=u._containerHeight/2,v=u._containerWidth/2-x/2,S=u.unproject([v,f]),T=u.unproject([v+x,f]),E=S.distanceTo(T);if(this.options.unit==="imperial"){const L=3.2808*E;L>5280?this._setScale(x,L/5280,"mile"):this._setScale(x,L,"foot")}else this.options.unit==="nautical"?this._setScale(x,E/1852,"nautical-mile"):E>=1e3?this._setScale(x,E/1e3,"kilometer"):this._setScale(x,E,"meter")}_setScale(x,u,f){this._map._requestDomTask(()=>{const v=function(T){const E=Math.pow(10,`${Math.floor(T)}`.length-1);let L=T/E;return L=L>=10?10:L>=5?5:L>=3?3:L>=2?2:L>=1?1:function(B){const q=Math.pow(10,Math.ceil(-Math.log(B)/Math.LN10));return Math.round(B*q)/q}(L),E*L}(u),S=v/u;this._container.innerHTML=f!=="nautical-mile"?new Intl.NumberFormat(this._language,{style:"unit",unitDisplay:"short",unit:f}).format(v):`${v} ${hN[f]}`,this._container.style.width=x*S+"px"})}onAdd(x){return this._map=x,this._language=x.getLanguage(),this._container=A("div","mapboxgl-ctrl mapboxgl-ctrl-scale",x.getContainer()),this._container.dir="auto",this._map.on("move",this._update),this._update(),this._container}onRemove(){this._container.remove(),this._map.off("move",this._update),this._map=void 0}_setLanguage(x){this._language=x,this._update()}setUnit(x){this.options.unit=x,this._update()}},FullscreenControl:class{constructor(x={}){this._fullscreen=!1,x&&x.container&&(x.container instanceof HTMLElement?this._container=x.container:a.w("Full screen control 'container' must be a DOM element.")),a.aY(["_onClickFullscreen","_changeIcon"],this),"onfullscreenchange"in document?this._fullscreenchange="fullscreenchange":"onwebkitfullscreenchange"in document&&(this._fullscreenchange="webkitfullscreenchange")}onAdd(x){return this._map=x,this._container||(this._container=this._map.getContainer()),this._controlContainer=A("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._checkFullscreenSupport()?this._setupUI():(this._controlContainer.style.display="none",a.w("This device does not support fullscreen mode.")),this._controlContainer}onRemove(){this._controlContainer.remove(),this._map=null,document.removeEventListener(this._fullscreenchange,this._changeIcon)}_checkFullscreenSupport(){return!(!document.fullscreenEnabled&&!document.webkitFullscreenEnabled)}_setupUI(){const x=this._fullscreenButton=A("button","mapboxgl-ctrl-fullscreen",this._controlContainer);A("span","mapboxgl-ctrl-icon",x).setAttribute("aria-hidden","true"),x.type="button",this._updateTitle(),this._fullscreenButton.addEventListener("click",this._onClickFullscreen),document.addEventListener(this._fullscreenchange,this._changeIcon)}_updateTitle(){const x=this._getTitle();this._fullscreenButton.setAttribute("aria-label",x),this._fullscreenButton.firstElementChild&&this._fullscreenButton.firstElementChild.setAttribute("title",x)}_getTitle(){return this._map._getUIString(this._isFullscreen()?"FullscreenControl.Exit":"FullscreenControl.Enter")}_isFullscreen(){return this._fullscreen}_changeIcon(){(document.fullscreenElement||document.webkitFullscreenElement)===this._container!==this._fullscreen&&(this._fullscreen=!this._fullscreen,this._fullscreenButton.classList.toggle("mapboxgl-ctrl-shrink"),this._fullscreenButton.classList.toggle("mapboxgl-ctrl-fullscreen"),this._updateTitle())}_onClickFullscreen(){this._isFullscreen()?document.exitFullscreen?document.exitFullscreen():document.webkitCancelFullScreen&&document.webkitCancelFullScreen():this._container.requestFullscreen?this._container.requestFullscreen():this._container.webkitRequestFullscreen&&this._container.webkitRequestFullscreen()}},IndoorControl:Og,Popup:class extends a.E{constructor(x){super(),this.options=Object.assign(Object.create(Su),x),this._altitude=this.options.altitude,a.aY(["_update","_onClose","remove","_onMouseEvent"],this),this._classList=new Set(x&&x.className?x.className.trim().split(/\s+/):[])}addTo(x){return this._map&&this.remove(),this._map=x,this.options.closeOnClick&&x.on("preclick",this._onClose),this.options.closeOnMove&&x.on("move",this._onClose),x.on("remove",this.remove),this._update(),x._addPopup(this),this._focusFirstElement(),this._trackPointer?(x.on("mousemove",this._onMouseEvent),x.on("mouseup",this._onMouseEvent),x._canvasContainer.classList.add("mapboxgl-track-pointer")):x.on("move",this._update),this.fire(new a.z("open")),this}isOpen(){return!!this._map}remove(){this._content&&this._content.remove(),this._container&&(this._container.remove(),this._container=void 0);const x=this._map;return x&&(x.off("move",this._update),x.off("move",this._onClose),x.off("preclick",this._onClose),x.off("click",this._onClose),x.off("remove",this.remove),x.off("mousemove",this._onMouseEvent),x.off("mouseup",this._onMouseEvent),x.off("drag",this._onMouseEvent),x._canvasContainer&&x._canvasContainer.classList.remove("mapboxgl-track-pointer"),x._removePopup(this),this._map=void 0),this.fire(new a.z("close")),this}getLngLat(){return this._lngLat}setLngLat(x){this._lngLat=a.aT.convert(x),this._pos=null,this._trackPointer=!1,this._update();const u=this._map;return u&&(u.on("move",this._update),u.off("mousemove",this._onMouseEvent),u._canvasContainer.classList.remove("mapboxgl-track-pointer")),this}getAltitude(){return this._altitude}setAltitude(x){return this._altitude=x,this._update(),this}trackPointer(){this._trackPointer=!0,this._pos=null,this._update();const x=this._map;return x&&(x.off("move",this._update),x.on("mousemove",this._onMouseEvent),x.on("drag",this._onMouseEvent),x._canvasContainer.classList.add("mapboxgl-track-pointer")),this}getElement(){return this._container}setText(x){return this.setDOMContent(document.createTextNode(x))}setHTML(x){const u=document.createDocumentFragment(),f=document.createElement("body");let v;for(f.innerHTML=x;v=f.firstChild,v;)u.appendChild(v);return this.setDOMContent(u)}getMaxWidth(){return this._container&&this._container.style.maxWidth}setMaxWidth(x){return this.options.maxWidth=x,this._update(),this}setDOMContent(x){let u=this._content;if(u)for(;u.hasChildNodes();)u.firstChild&&u.removeChild(u.firstChild);else u=this._content=A("div","mapboxgl-popup-content",this._container||void 0);if(u.appendChild(x),this.options.closeButton){const f=this._closeButton=A("button","mapboxgl-popup-close-button",u);f.type="button",f.setAttribute("aria-label","Close popup"),f.innerHTML='',f.addEventListener("click",this._onClose)}return this._update(),this._focusFirstElement(),this}addClassName(x){return this._classList.add(x),this._updateClassList(),this}removeClassName(x){return this._classList.delete(x),this._updateClassList(),this}setOffset(x){return this.options.offset=x,this._update(),this}toggleClassName(x){let u;return this._classList.delete(x)?u=!1:(this._classList.add(x),u=!0),this._updateClassList(),u}_onMouseEvent(x){this._update(x.point)}_getAnchor(x){if(this.options.anchor)return this.options.anchor;const u=this._map,f=this._container,v=this._pos;if(!u||!f||!v)return"bottom";const S=f.offsetWidth,T=f.offsetHeight,E=v.xu.transform.width-S/2;if(v.y+xu.transform.height-T){if(E)return"bottom-left";if(L)return"bottom-right"}return E?"left":L?"right":"bottom"}_updateClassList(){const x=this._container;if(!x)return;const u=[...this._classList];u.push("mapboxgl-popup"),this._anchor&&u.push(`mapboxgl-popup-anchor-${this._anchor}`),this._trackPointer&&u.push("mapboxgl-popup-track-pointer"),x.className=u.join(" ")}_update(x){const u=this._map,f=this._content;if(!u||!this._lngLat&&!this._trackPointer||!f)return;let v=this._container;if(v||(v=this._container=A("div","mapboxgl-popup",u.getContainer()),this._tip=A("div","mapboxgl-popup-tip",v),v.appendChild(f)),this.options.maxWidth&&v.style.maxWidth!==this.options.maxWidth&&(v.style.maxWidth=this.options.maxWidth),u.transform.renderWorldCopies&&!this._trackPointer&&(this._lngLat=dN(this._lngLat,this._pos,u.transform)),!this._trackPointer||x){const S=this._pos=this._trackPointer&&x instanceof a.P?x:u.project(this._lngLat,this._altitude),T=im(this.options.offset),E=this._anchor=this._getAnchor(T.y),L=im(this.options.offset,E),B=S.add(L).round();u._requestDomTask(()=>{this._container&&E&&(this._container.style.transform=`${rl[E]} translate(${B.x}px,${B.y}px)`)})}if(!this._marker&&u._showingGlobe()){const S=a.f5(u.transform,this._lngLat)?0:1;this._setOpacity(S)}this._updateClassList()}_focusFirstElement(){if(!this.options.focusAfterOpen||!this._container)return;const x=this._container.querySelector(Nu);x&&x.focus()}_onClose(){this.remove()}_setOpacity(x){this._container&&(this._container.style.opacity=`${x}`),this._content&&(this._content.style.pointerEvents=x?"auto":"none")}},Marker:Pb,Style:wu,LngLat:a.aT,LngLatBounds:a.aI,Point:a.P,MercatorCoordinate:a.ae,FreeCameraOptions:Ol,Evented:a.E,config:a.e,prewarm:a.f9,clearPrewarmedResources:a.f8,get accessToken(){return a.e.ACCESS_TOKEN},set accessToken(x){a.e.ACCESS_TOKEN=x},get baseApiUrl(){return a.e.API_URL},set baseApiUrl(x){a.e.API_URL=x},get workerCount(){return a.fi.workerCount},set workerCount(x){a.fi.workerCount=x},get maxParallelImageRequests(){return a.e.MAX_PARALLEL_IMAGE_REQUESTS},set maxParallelImageRequests(x){a.e.MAX_PARALLEL_IMAGE_REQUESTS=x},clearStorage(x){a.fh(x)},get workerUrl(){return a.fg.workerUrl},set workerUrl(x){a.fg.workerUrl=x},get workerClass(){return a.fg.workerClass},set workerClass(x){a.fg.workerClass=x},get workerParams(){return a.fg.workerParams},set workerParams(x){a.fg.workerParams=x},get dracoUrl(){return a.ff()},set dracoUrl(x){a.fe(x)},get meshoptUrl(){return a.fd()},set meshoptUrl(x){a.fc(x)},setNow:a.o.setNow,restoreNow:a.o.restoreNow}});var c=i;return c})})(Vye);var E7e=Vye.exports;const GP=sa(E7e);function A7e(){const t=Bs(),{isAdmin:e}=rn(),r=D.useRef(null),n=D.useRef(null),i=D.useRef([]),o=Bye(),{data:c}=Fye(),a=Uye(),[m,g]=D.useState(""),[_,j]=D.useState(""),[N,C]=D.useState(!0),[P,A]=D.useState(null),[I,O]=D.useState(null),[R,z]=D.useState(!1),[W,V]=D.useState({popby_item_id:"",notes:""}),K=o.filter(ie=>ie.address||ie.city&&ie.state);D.useEffect(()=>{(async()=>{C(!0);try{const{data:he}=await ae.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();he!=null&&he.value&&g(he.value)}catch(he){console.error("Error fetching mapbox token:",he)}C(!1)})()},[]),D.useEffect(()=>{"geolocation"in navigator&&navigator.geolocation.getCurrentPosition(ie=>{A([ie.coords.longitude,ie.coords.latitude])},ie=>{console.log("Could not get location:",ie)})},[]),D.useEffect(()=>{if(!(!r.current||!m||n.current))return GP.accessToken=m,n.current=new GP.Map({container:r.current,style:"mapbox://styles/mapbox/streets-v12",zoom:P?12:4,center:P||[-98.5795,39.8283]}),n.current.addControl(new GP.NavigationControl,"top-right"),()=>{var ie;(ie=n.current)==null||ie.remove(),n.current=null}},[m,P]),D.useEffect(()=>{!n.current||!m||(i.current.forEach(ie=>ie.remove()),i.current=[],K.forEach(async ie=>{var xe;const he=[ie.address,ie.city,ie.state,ie.zip].filter(Boolean).join(", ");if(he)try{const ve=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(he)}.json?access_token=${m}`)).json();if(ve.features&&ve.features.length>0){const[ge,ke]=ve.features[0].center,Ce=document.createElement("div");Ce.className="cursor-pointer",Ce.innerHTML=`
${ie.first_name[0]}${((xe=ie.last_name)==null?void 0:xe[0])||""}
${ie.isDue?'
':""}
`;const Se=new GP.Marker(Ce).setLngLat([ge,ke]).addTo(n.current);Ce.addEventListener("click",()=>{O(ie)}),i.current.push(Se)}}catch(pe){console.error("Geocoding error for",ie.first_name,pe)}}))},[K,m]);const Q=()=>{P&&n.current?n.current.flyTo({center:P,zoom:13}):na({title:"Location not available",description:"Please enable location services",variant:"destructive"})},te=async()=>{I&&(await a.mutateAsync({contact_id:I.id,popby_item_id:W.popby_item_id||void 0,notes:W.notes||void 0,latitude:P==null?void 0:P[1],longitude:P==null?void 0:P[0]}),z(!1),O(null),V({popby_item_id:"",notes:""}))},X=async()=>{if(_.trim())try{await ae.from("settings").upsert({key:"mapbox_public_token",value:_.trim()}),g(_.trim()),na({title:"Mapbox token saved!"})}catch{na({title:"Error saving token",variant:"destructive"})}};return N?s.jsx(Jr,{title:"Popby Map",children:s.jsx("div",{className:"flex items-center justify-center h-[60vh]",children:s.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})})}):m?s.jsx(Jr,{title:"Popby Map",children:s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs(de,{variant:"ghost",onClick:()=>t("/innercircle/popbys"),children:[s.jsx(Ka,{className:"h-4 w-4 mr-2"}),"Back to Popbys"]}),s.jsxs(de,{onClick:Q,children:[s.jsx(I2e,{className:"h-4 w-4 mr-2"}),"My Location"]})]}),s.jsxs("div",{className:"flex gap-4 text-sm",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("div",{className:"w-4 h-4 rounded-full bg-primary"}),s.jsx("span",{children:"Up to date"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("div",{className:"w-4 h-4 rounded-full bg-amber-500"}),s.jsx("span",{children:"Due for popby"})]})]}),s.jsxs("div",{className:"relative",children:[s.jsx("div",{ref:r,className:"w-full h-[60vh] rounded-lg shadow-lg"}),K.length===0&&s.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-background/80 rounded-lg",children:s.jsxs("div",{className:"text-center p-6",children:[s.jsx(sx,{className:"h-12 w-12 mx-auto text-muted-foreground mb-2"}),s.jsx("p",{className:"font-medium",children:"No contacts with addresses"}),s.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Add addresses to your contacts to see them on the map."})]})})]}),I&&s.jsx(at,{className:"fixed bottom-4 left-4 right-4 md:left-auto md:right-4 md:w-96 z-50 shadow-xl",children:s.jsxs(ct,{className:"p-4",children:[s.jsxs("div",{className:"flex items-start justify-between mb-3",children:[s.jsxs("div",{children:[s.jsxs("h3",{className:"font-semibold",children:[I.first_name," ",I.last_name]}),I.address&&s.jsxs("p",{className:"text-sm text-muted-foreground",children:[I.city,", ",I.state]})]}),s.jsx(de,{size:"sm",variant:"ghost",onClick:()=>O(null),children:"×"})]}),s.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[I.isDue?s.jsxs(ir,{variant:"destructive",children:[I.daysOverdue,"+ days overdue"]}):s.jsx(ir,{variant:"secondary",children:"Up to date"}),I.lastPopby&&s.jsxs("span",{className:"text-xs text-muted-foreground",children:["Last: ",Vn(new Date(I.lastPopby),"MMM d")]})]}),s.jsxs("div",{className:"flex gap-2",children:[I.phone&&s.jsx(de,{size:"sm",variant:"outline",asChild:!0,className:"flex-1",children:s.jsxs("a",{href:`tel:${I.phone}`,children:[s.jsx(Yl,{className:"h-4 w-4 mr-1"}),"Call"]})}),I.address&&s.jsxs(de,{size:"sm",variant:"outline",className:"flex-1",onClick:()=>{const ie=[I.address,I.city,I.state,I.zip].filter(Boolean).join(", ");window.open(`https://maps.google.com/maps?daddr=${encodeURIComponent(ie)}`,"_blank")},children:[s.jsx(L2e,{className:"h-4 w-4 mr-1"}),"Navigate"]}),s.jsxs(de,{size:"sm",className:"flex-1",onClick:()=>z(!0),children:[s.jsx(yd,{className:"h-4 w-4 mr-1"}),"Log Popby"]})]})]})}),s.jsx(mn,{open:R,onOpenChange:z,children:s.jsxs(pn,{children:[s.jsx(xn,{children:s.jsxs(gn,{children:["Log Popby for ",I==null?void 0:I.first_name," ",I==null?void 0:I.last_name]})}),s.jsxs("div",{className:"space-y-4 py-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Popby Item (optional)"}),s.jsxs(Kn,{value:W.popby_item_id,onValueChange:ie=>V(he=>({...he,popby_item_id:ie})),children:[s.jsx(qn,{children:s.jsx(Zn,{placeholder:"Select a popby item..."})}),s.jsx(Hn,{children:c==null?void 0:c.map(ie=>s.jsx(_r,{value:ie.id,children:ie.name},ie.id))})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Notes (optional)"}),s.jsx(mi,{placeholder:"Any notes about this popby...",value:W.notes,onChange:ie=>V(he=>({...he,notes:ie.target.value}))})]}),P&&s.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[s.jsx(wp,{className:"h-3 w-3"}),"Your current location will be recorded"]})]}),s.jsxs(zi,{children:[s.jsx(de,{variant:"outline",onClick:()=>z(!1),children:"Cancel"}),s.jsxs(de,{onClick:te,disabled:a.isPending,children:[s.jsx(gc,{className:"h-4 w-4 mr-1"}),"Log Popby"]})]})]})})]})}):e?s.jsx(Jr,{title:"Popby Map",children:s.jsx("div",{className:"max-w-md mx-auto mt-8",children:s.jsx(at,{children:s.jsxs(ct,{className:"p-6 space-y-4",children:[s.jsxs("div",{className:"text-center mb-4",children:[s.jsx(wp,{className:"h-12 w-12 mx-auto text-muted-foreground mb-2"}),s.jsx("h2",{className:"text-lg font-semibold",children:"Setup Map"}),s.jsx("p",{className:"text-sm text-muted-foreground",children:"Enter your Mapbox public token to enable the map feature."})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Mapbox Public Token"}),s.jsx(Et,{placeholder:"pk.eyJ1I...",value:_,onChange:ie=>j(ie.target.value)}),s.jsxs("p",{className:"text-xs text-muted-foreground",children:["Get your token at"," ",s.jsx("a",{href:"https://mapbox.com/",target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline",children:"mapbox.com"})]})]}),s.jsx(de,{onClick:X,className:"w-full",children:"Save Token"}),s.jsxs(de,{variant:"outline",className:"w-full",onClick:()=>t("/innercircle/popbys"),children:[s.jsx(Ka,{className:"h-4 w-4 mr-2"}),"Back to Popbys"]})]})})})}):s.jsx(Jr,{title:"Popby Map",children:s.jsx("div",{className:"max-w-md mx-auto mt-8",children:s.jsx(at,{children:s.jsxs(ct,{className:"p-6 space-y-4",children:[s.jsxs("div",{className:"text-center",children:[s.jsx(sx,{className:"h-12 w-12 mx-auto text-muted-foreground mb-2"}),s.jsx("h2",{className:"text-lg font-semibold",children:"Map Not Available"}),s.jsx("p",{className:"text-sm text-muted-foreground",children:"The map feature has not been configured yet. Please contact your administrator."})]}),s.jsxs(de,{variant:"outline",className:"w-full",onClick:()=>t("/innercircle/popbys"),children:[s.jsx(Ka,{className:"h-4 w-4 mr-2"}),"Back to Popbys"]})]})})})})}const P7e=wD({property_address:id().min(1,"Property address is required"),city:id().optional(),state:id().optional(),zip:id().optional(),transaction_type:Tue(["buyer","seller"]),close_date:id().min(1,"Close date is required"),sale_price:l2().min(0,"Sale price must be positive"),commission_amount:l2().optional(),lead_source_id:id().optional(),client_type_id:id().optional(),contact_id:id().optional(),notes:id().optional(),is_win:pDe()});function Hye({open:t,onOpenChange:e,transaction:r}){const[n,i]=D.useState(!1),[o,c]=D.useState(""),[a,m]=D.useState(!1),[g,_]=D.useState(""),j=Eq(),N=$Be(),{data:C}=kq(),{data:P}=sg(),{data:A}=ig(),I=npe(),O=BBe(),{data:R}=BD(),z=(R==null?void 0:R.show_commission)??!0,W=eq({resolver:tq(P7e),defaultValues:{property_address:"",city:"",state:"",zip:"",transaction_type:"buyer",close_date:new Date().toISOString().split("T")[0],sale_price:0,commission_amount:void 0,lead_source_id:void 0,client_type_id:void 0,contact_id:void 0,notes:"",is_win:!1}});D.useEffect(()=>{r?W.reset({property_address:r.property_address,city:r.city||"",state:r.state||"",zip:r.zip||"",transaction_type:r.transaction_type,close_date:r.close_date,sale_price:Number(r.sale_price),commission_amount:r.commission_amount?Number(r.commission_amount):void 0,lead_source_id:r.lead_source_id||void 0,client_type_id:r.client_type_id||void 0,contact_id:r.contact_id||void 0,notes:r.notes||"",is_win:r.is_win}):W.reset({property_address:"",city:"",state:"",zip:"",transaction_type:"buyer",close_date:new Date().toISOString().split("T")[0],sale_price:0,commission_amount:void 0,lead_source_id:void 0,client_type_id:void 0,contact_id:void 0,notes:"",is_win:!1})},[r,W]);const V=async X=>{const ie={property_address:X.property_address,transaction_type:X.transaction_type,close_date:X.close_date,sale_price:X.sale_price,is_win:X.is_win,commission_amount:X.commission_amount||null,lead_source_id:X.lead_source_id||null,client_type_id:X.client_type_id||null,contact_id:X.contact_id||null,city:X.city||null,state:X.state||null,zip:X.zip||null,notes:X.notes||null};r?await N.mutateAsync({id:r.id,...ie}):await j.mutateAsync(ie),e(!1)},K=async()=>{if(!o.trim())return;const[X,...ie]=o.trim().split(" "),he=ie.join(" ")||null,xe=await I.mutateAsync({first_name:X,last_name:he,tagIds:[]});xe&&(W.setValue("contact_id",xe.id),c(""),m(!1),i(!1))},Q=async()=>{if(!g.trim())return;const X=await O.mutateAsync(g.trim());X&&(W.setValue("lead_source_id",X.id),_(""))},te=A==null?void 0:A.find(X=>X.id===W.watch("contact_id"));return s.jsx(mn,{open:t,onOpenChange:e,children:s.jsxs(pn,{className:"max-w-lg max-h-[90vh]",children:[s.jsx(xn,{children:s.jsx(gn,{children:r?"Edit Transaction":"Add Transaction"})}),s.jsx(qu,{className:"max-h-[70vh] pr-4",children:s.jsx(rq,{...W,children:s.jsxs("form",{onSubmit:W.handleSubmit(V),className:"space-y-4",children:[s.jsx(Sl,{control:W.control,name:"property_address",render:({field:X})=>s.jsxs(cl,{children:[s.jsx(ul,{children:"Property Address *"}),s.jsx(dl,{children:s.jsx(Et,{placeholder:"123 Main St",...X})}),s.jsx(gf,{})]})}),s.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[s.jsx(Sl,{control:W.control,name:"city",render:({field:X})=>s.jsxs(cl,{children:[s.jsx(ul,{children:"City"}),s.jsx(dl,{children:s.jsx(Et,{placeholder:"City",...X})})]})}),s.jsx(Sl,{control:W.control,name:"state",render:({field:X})=>s.jsxs(cl,{children:[s.jsx(ul,{children:"State"}),s.jsx(dl,{children:s.jsx(Et,{placeholder:"TX",...X})})]})}),s.jsx(Sl,{control:W.control,name:"zip",render:({field:X})=>s.jsxs(cl,{children:[s.jsx(ul,{children:"Zip"}),s.jsx(dl,{children:s.jsx(Et,{placeholder:"75001",...X})})]})})]}),s.jsx(Sl,{control:W.control,name:"transaction_type",render:({field:X})=>s.jsxs(cl,{children:[s.jsx(ul,{children:"Transaction Type *"}),s.jsxs(Kn,{onValueChange:X.onChange,value:X.value,children:[s.jsx(dl,{children:s.jsx(qn,{children:s.jsx(Zn,{placeholder:"Select type"})})}),s.jsxs(Hn,{children:[s.jsx(_r,{value:"buyer",children:"Buyer"}),s.jsx(_r,{value:"seller",children:"Seller"})]})]}),s.jsx(gf,{})]})}),s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsx(Sl,{control:W.control,name:"close_date",render:({field:X})=>s.jsxs(cl,{children:[s.jsx(ul,{children:"Close Date *"}),s.jsx(dl,{children:s.jsx(Et,{type:"date",...X})}),s.jsx(gf,{})]})}),s.jsx(Sl,{control:W.control,name:"sale_price",render:({field:X})=>s.jsxs(cl,{children:[s.jsx(ul,{children:"Sale Price *"}),s.jsx(dl,{children:s.jsx(Et,{type:"number",placeholder:"0",...X,onChange:ie=>X.onChange(Number(ie.target.value))})}),s.jsx(gf,{})]})})]}),z&&s.jsx(Sl,{control:W.control,name:"commission_amount",render:({field:X})=>s.jsxs(cl,{children:[s.jsx(ul,{children:"Commission"}),s.jsx(dl,{children:s.jsx(Et,{type:"number",placeholder:"0",...X,value:X.value??"",onChange:ie=>X.onChange(ie.target.value?Number(ie.target.value):void 0)})})]})}),s.jsx(Sl,{control:W.control,name:"lead_source_id",render:({field:X})=>s.jsxs(cl,{children:[s.jsx(ul,{children:"Lead Source"}),s.jsxs(Kn,{onValueChange:X.onChange,value:X.value||"",children:[s.jsx(dl,{children:s.jsx(qn,{children:s.jsx(Zn,{placeholder:"Select source"})})}),s.jsx(Hn,{children:C==null?void 0:C.map(ie=>s.jsx(_r,{value:ie.id,children:ie.name},ie.id))})]})]})}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(Et,{placeholder:"Add custom source...",value:g,onChange:X=>_(X.target.value),className:"flex-1"}),s.jsx(de,{type:"button",variant:"outline",size:"icon",onClick:Q,disabled:!g.trim(),children:s.jsx(Qn,{className:"h-4 w-4"})})]}),s.jsx(Sl,{control:W.control,name:"client_type_id",render:({field:X})=>s.jsxs(cl,{children:[s.jsx(ul,{children:"Client Type"}),s.jsxs(Kn,{onValueChange:X.onChange,value:X.value||"",children:[s.jsx(dl,{children:s.jsx(qn,{children:s.jsx(Zn,{placeholder:"Select client type"})})}),s.jsx(Hn,{children:P==null?void 0:P.map(ie=>s.jsx(_r,{value:ie.id,children:ie.name},ie.id))})]})]})}),s.jsx(Sl,{control:W.control,name:"contact_id",render:({field:X})=>s.jsxs(cl,{children:[s.jsx(ul,{children:"Client Contact"}),s.jsxs(HD,{open:n,onOpenChange:i,children:[s.jsx(WD,{asChild:!0,children:s.jsx(dl,{children:s.jsxs(de,{variant:"outline",role:"combobox",className:ar("w-full justify-between",!X.value&&"text-muted-foreground"),children:[te?`${te.first_name} ${te.last_name||""}`.trim():"Select contact",s.jsx(S2e,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})})}),s.jsxs(RT,{className:"w-full p-0",align:"start",children:[s.jsxs(mq,{children:[s.jsx(gq,{placeholder:"Search contacts..."}),s.jsxs(yq,{children:[s.jsx(xq,{children:s.jsxs("div",{className:"p-2 space-y-2",children:[s.jsx("p",{className:"text-sm text-muted-foreground",children:"No contact found."}),!a&&s.jsxs(de,{variant:"outline",size:"sm",className:"w-full",onClick:()=>m(!0),children:[s.jsx(Qn,{className:"h-4 w-4 mr-2"}),"Add New Contact"]})]})}),s.jsx(vq,{children:A==null?void 0:A.map(ie=>s.jsxs(_q,{value:`${ie.first_name} ${ie.last_name||""}`,onSelect:()=>{X.onChange(ie.id),i(!1)},children:[s.jsx(ru,{className:ar("mr-2 h-4 w-4",ie.id===X.value?"opacity-100":"opacity-0")}),ie.first_name," ",ie.last_name||""]},ie.id))})]})]}),a&&s.jsxs("div",{className:"p-2 border-t space-y-2",children:[s.jsx(Et,{placeholder:"Enter contact name...",value:o,onChange:ie=>c(ie.target.value)}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(de,{size:"sm",onClick:K,disabled:!o.trim()||I.isPending,children:"Add Contact"}),s.jsx(de,{size:"sm",variant:"outline",onClick:()=>{m(!1),c("")},children:"Cancel"})]})]})]})]})]})}),s.jsx(Sl,{control:W.control,name:"notes",render:({field:X})=>s.jsxs(cl,{children:[s.jsx(ul,{children:"Notes"}),s.jsx(dl,{children:s.jsx(mi,{placeholder:"Any notes about this transaction...",...X})})]})}),s.jsx(Sl,{control:W.control,name:"is_win",render:({field:X})=>s.jsxs(cl,{className:"flex items-center justify-between rounded-lg border p-3",children:[s.jsxs("div",{className:"space-y-0.5",children:[s.jsx(ul,{children:"Mark as Win 🏆"}),s.jsx("p",{className:"text-sm text-muted-foreground",children:"Highlight this as a notable success"})]}),s.jsx(dl,{children:s.jsx(ri,{checked:X.value,onCheckedChange:X.onChange})})]})}),s.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[s.jsx(de,{type:"button",variant:"outline",onClick:()=>e(!1),children:"Cancel"}),s.jsxs(de,{type:"submit",disabled:j.isPending||N.isPending,children:[r?"Update":"Add"," Transaction"]})]})]})})})]})})}var Wye="AlertDialog",[I7e]=Yo(Wye,[lue]),og=lue(),Gye=t=>{const{__scopeAlertDialog:e,...r}=t,n=og(e);return s.jsx(vD,{...n,...r,modal:!0})};Gye.displayName=Wye;var M7e="AlertDialogTrigger",O7e=D.forwardRef((t,e)=>{const{__scopeAlertDialog:r,...n}=t,i=og(r);return s.jsx(P8,{...i,...n,ref:e})});O7e.displayName=M7e;var R7e="AlertDialogPortal",Kye=t=>{const{__scopeAlertDialog:e,...r}=t,n=og(e);return s.jsx(_D,{...n,...r})};Kye.displayName=R7e;var D7e="AlertDialogOverlay",Zye=D.forwardRef((t,e)=>{const{__scopeAlertDialog:r,...n}=t,i=og(r);return s.jsx(Bj,{...i,...n,ref:e})});Zye.displayName=D7e;var l1="AlertDialogContent",[L7e,F7e]=I7e(l1),z7e=Tae("AlertDialogContent"),Yye=D.forwardRef((t,e)=>{const{__scopeAlertDialog:r,children:n,...i}=t,o=og(r),c=D.useRef(null),a=vs(e,c),m=D.useRef(null);return s.jsx(IRe,{contentName:l1,titleName:Xye,docsSlug:"alert-dialog",children:s.jsx(L7e,{scope:r,cancelRef:m,children:s.jsxs($j,{role:"alertdialog",...o,...i,ref:a,onOpenAutoFocus:Yr(i.onOpenAutoFocus,g=>{var _;g.preventDefault(),(_=m.current)==null||_.focus({preventScroll:!0})}),onPointerDownOutside:g=>g.preventDefault(),onInteractOutside:g=>g.preventDefault(),children:[s.jsx(z7e,{children:n}),s.jsx($7e,{contentRef:c})]})})})});Yye.displayName=l1;var Xye="AlertDialogTitle",Qye=D.forwardRef((t,e)=>{const{__scopeAlertDialog:r,...n}=t,i=og(r);return s.jsx(NT,{...i,...n,ref:e})});Qye.displayName=Xye;var Jye="AlertDialogDescription",exe=D.forwardRef((t,e)=>{const{__scopeAlertDialog:r,...n}=t,i=og(r);return s.jsx(CT,{...i,...n,ref:e})});exe.displayName=Jye;var B7e="AlertDialogAction",txe=D.forwardRef((t,e)=>{const{__scopeAlertDialog:r,...n}=t,i=og(r);return s.jsx(bD,{...i,...n,ref:e})});txe.displayName=B7e;var rxe="AlertDialogCancel",nxe=D.forwardRef((t,e)=>{const{__scopeAlertDialog:r,...n}=t,{cancelRef:i}=F7e(rxe,r),o=og(r),c=vs(e,i);return s.jsx(bD,{...o,...n,ref:c})});nxe.displayName=rxe;var $7e=({contentRef:t})=>{const e=`\`${l1}\` requires a description for the component to be accessible for screen reader users. You can add a description to the \`${l1}\` by passing a \`${Jye}\` component as a child, which also benefits sighted users by adding visible context to the dialog. Alternatively, you can use your own component as a description by assigning it an \`id\` and passing the same value to the \`aria-describedby\` prop in \`${l1}\`. If the description is confusing or duplicative for sighted users, you can use the \`@radix-ui/react-visually-hidden\` primitive as a wrapper around your description component. For more information, see https://radix-ui.com/primitives/docs/components/alert-dialog`;return D.useEffect(()=>{var n;document.getElementById((n=t.current)==null?void 0:n.getAttribute("aria-describedby"))||console.warn(e)},[e,t]),null},U7e=Gye,V7e=Kye,sxe=Zye,ixe=Yye,axe=txe,oxe=nxe,lxe=Qye,cxe=exe;const q7e=U7e,H7e=V7e,uxe=D.forwardRef(({className:t,...e},r)=>s.jsx(sxe,{className:ar("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",t),...e,ref:r}));uxe.displayName=sxe.displayName;const dxe=D.forwardRef(({className:t,...e},r)=>s.jsxs(H7e,{children:[s.jsx(uxe,{}),s.jsx(ixe,{ref:r,className:ar("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",t),...e})]}));dxe.displayName=ixe.displayName;const hxe=({className:t,...e})=>s.jsx("div",{className:ar("flex flex-col space-y-2 text-center sm:text-left",t),...e});hxe.displayName="AlertDialogHeader";const fxe=({className:t,...e})=>s.jsx("div",{className:ar("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",t),...e});fxe.displayName="AlertDialogFooter";const pxe=D.forwardRef(({className:t,...e},r)=>s.jsx(lxe,{ref:r,className:ar("text-lg font-semibold",t),...e}));pxe.displayName=lxe.displayName;const mxe=D.forwardRef(({className:t,...e},r)=>s.jsx(cxe,{ref:r,className:ar("text-sm text-muted-foreground",t),...e}));mxe.displayName=cxe.displayName;const gxe=D.forwardRef(({className:t,...e},r)=>s.jsx(axe,{ref:r,className:ar(sk(),t),...e}));gxe.displayName=axe.displayName;const yxe=D.forwardRef(({className:t,...e},r)=>s.jsx(oxe,{ref:r,className:ar(sk({variant:"outline"}),"mt-2 sm:mt-0",t),...e}));yxe.displayName=oxe.displayName;function xxe({transactions:t,showCommission:e,isLoading:r}){const[n,i]=D.useState(null),[o,c]=D.useState(null),[a,m]=D.useState(""),[g,_]=D.useState("all"),[j,N]=D.useState("all"),[C,P]=D.useState("all"),[A,I]=D.useState(!1),O=UBe(),R=Eq(),{data:z}=kq(),{data:W}=sg(),V=jH(),K=X=>{const{id:ie,created_at:he,updated_at:xe,lead_source:pe,client_type:ve,contact:ge,...ke}=X;R.mutate(ke)},Q=()=>{o&&(O.mutate(o),c(null))},te=t.filter(X=>{var ge,ke,Ce,Se;const ie=a===""||X.property_address.toLowerCase().includes(a.toLowerCase())||((ke=(ge=X.contact)==null?void 0:ge.first_name)==null?void 0:ke.toLowerCase().includes(a.toLowerCase()))||((Se=(Ce=X.contact)==null?void 0:Ce.last_name)==null?void 0:Se.toLowerCase().includes(a.toLowerCase())),he=g==="all"||X.transaction_type===g,xe=j==="all"||X.lead_source_id===j,pe=C==="all"||X.client_type_id===C,ve=!A||X.is_win;return ie&&he&&xe&&pe&&ve});return r?s.jsx(at,{children:s.jsx(ct,{className:"p-6 space-y-4",children:[1,2,3].map(X=>s.jsx(Dn,{className:"h-16 w-full"},X))})}):s.jsxs(s.Fragment,{children:[s.jsxs(at,{children:[s.jsx(xr,{className:"pb-3",children:s.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[s.jsxs(wr,{children:["Transactions (",te.length,")"]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs("div",{className:"relative",children:[s.jsx(ba,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),s.jsx(Et,{placeholder:"Search...",value:a,onChange:X=>m(X.target.value),className:"pl-8 w-[150px]"})]}),s.jsxs(Kn,{value:g,onValueChange:_,children:[s.jsx(qn,{className:"w-[100px]",children:s.jsx(Zn,{placeholder:"Type"})}),s.jsxs(Hn,{children:[s.jsx(_r,{value:"all",children:"All Types"}),s.jsx(_r,{value:"buyer",children:"Buyer"}),s.jsx(_r,{value:"seller",children:"Seller"})]})]}),s.jsxs(Kn,{value:j,onValueChange:N,children:[s.jsx(qn,{className:"w-[130px]",children:s.jsx(Zn,{placeholder:"Lead Source"})}),s.jsxs(Hn,{children:[s.jsx(_r,{value:"all",children:"All Sources"}),z==null?void 0:z.map(X=>s.jsx(_r,{value:X.id,children:X.name},X.id))]})]}),s.jsxs(de,{variant:A?"default":"outline",size:"sm",onClick:()=>I(!A),children:[s.jsx(Jw,{className:"h-4 w-4 mr-1"}),"Wins"]})]})]})}),s.jsx(ct,{children:te.length===0?s.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No transactions found"}):V?s.jsx("div",{className:"space-y-3",children:te.map(X=>s.jsxs(at,{className:"p-4",children:[s.jsxs("div",{className:"flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx("span",{className:"font-medium truncate",children:X.property_address}),X.is_win&&s.jsx(Jw,{className:"h-4 w-4 text-yellow-500 flex-shrink-0"})]}),s.jsxs("div",{className:"text-sm text-muted-foreground",children:[X.city,X.state?`, ${X.state}`:""]})]}),s.jsx(ir,{variant:X.transaction_type==="buyer"?"default":"secondary",children:X.transaction_type})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-3 text-sm",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-muted-foreground",children:"Close Date: "}),XZ(X.close_date)]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-muted-foreground",children:"Price: "}),fc(X.sale_price)]}),e&&X.commission_amount&&s.jsxs("div",{children:[s.jsx("span",{className:"text-muted-foreground",children:"Commission: "}),fc(X.commission_amount)]}),X.lead_source&&s.jsxs("div",{children:[s.jsx("span",{className:"text-muted-foreground",children:"Source: "}),X.lead_source.name]}),X.contact&&s.jsxs("div",{className:"col-span-2",children:[s.jsx("span",{className:"text-muted-foreground",children:"Client: "}),X.contact.first_name," ",X.contact.last_name]})]}),s.jsxs("div",{className:"flex justify-end gap-2 mt-3 pt-3 border-t",children:[s.jsx(de,{variant:"ghost",size:"sm",onClick:()=>i(X),children:s.jsx(P_,{className:"h-4 w-4"})}),s.jsx(de,{variant:"ghost",size:"sm",onClick:()=>K(X),children:s.jsx(ix,{className:"h-4 w-4"})}),s.jsx(de,{variant:"ghost",size:"sm",onClick:()=>c(X.id),children:s.jsx(oi,{className:"h-4 w-4 text-destructive"})})]})]},X.id))}):s.jsx("div",{className:"overflow-x-auto",children:s.jsxs(ni,{children:[s.jsx(si,{children:s.jsxs(Dr,{children:[s.jsx(Nt,{children:"Property"}),s.jsx(Nt,{children:"Type"}),s.jsx(Nt,{children:"Close Date"}),s.jsx(Nt,{children:"Sale Price"}),e&&s.jsx(Nt,{children:"Commission"}),s.jsx(Nt,{children:"Lead Source"}),s.jsx(Nt,{children:"Client"}),s.jsx(Nt,{className:"w-[50px]"})]})}),s.jsx(ii,{children:te.map(X=>{var ie;return s.jsxs(Dr,{children:[s.jsx(xt,{children:s.jsxs("div",{className:"flex items-center gap-2",children:[X.is_win&&s.jsx(Jw,{className:"h-4 w-4 text-yellow-500"}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium",children:X.property_address}),s.jsxs("div",{className:"text-sm text-muted-foreground",children:[X.city,X.state?`, ${X.state}`:""]})]})]})}),s.jsx(xt,{children:s.jsx(ir,{variant:X.transaction_type==="buyer"?"default":"secondary",children:X.transaction_type})}),s.jsx(xt,{children:XZ(X.close_date)}),s.jsx(xt,{children:fc(X.sale_price)}),e&&s.jsx(xt,{children:X.commission_amount?fc(X.commission_amount):"-"}),s.jsx(xt,{children:((ie=X.lead_source)==null?void 0:ie.name)||"-"}),s.jsx(xt,{children:X.contact?`${X.contact.first_name} ${X.contact.last_name||""}`.trim():"-"}),s.jsx(xt,{children:s.jsxs(rg,{children:[s.jsx(ng,{asChild:!0,children:s.jsx(de,{variant:"ghost",size:"icon",children:s.jsx(coe,{className:"h-4 w-4"})})}),s.jsxs(Op,{align:"end",children:[s.jsxs(Ro,{onClick:()=>i(X),children:[s.jsx(P_,{className:"h-4 w-4 mr-2"}),"Edit"]}),s.jsxs(Ro,{onClick:()=>K(X),children:[s.jsx(ix,{className:"h-4 w-4 mr-2"}),"Duplicate"]}),s.jsxs(Ro,{onClick:()=>c(X.id),className:"text-destructive",children:[s.jsx(oi,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})})]},X.id)})})]})})})]}),s.jsx(Hye,{open:!!n,onOpenChange:X=>!X&&i(null),transaction:n||void 0}),s.jsx(q7e,{open:!!o,onOpenChange:X=>!X&&c(null),children:s.jsxs(dxe,{children:[s.jsxs(hxe,{children:[s.jsx(pxe,{children:"Delete Transaction?"}),s.jsx(mxe,{children:"This action cannot be undone. This will permanently delete this transaction."})]}),s.jsxs(fxe,{children:[s.jsx(yxe,{children:"Cancel"}),s.jsx(gxe,{onClick:Q,className:"bg-destructive text-destructive-foreground",children:"Delete"})]})]})})]})}function vxe({goals:t,stats:e,year:r,showCommission:n}){const i=new Date().getMonth()+1,o=new Date().getFullYear()===r?i:12,c=12-o,a=(N,C)=>{if(!C||C===0)return null;const P=Math.min(N/C*100,100),A=Math.max(C-N,0),I=c>0?A/c:0,O=o/12*100,R=P>=O?"ahead":P>=O*.8?"on-track":"behind";return{percent:P,remaining:A,pace:I,status:R}},m=a(e.totalTransactions,t.transactions_goal),g=a(e.totalVolume,t.volume_goal),_=n?a(e.totalCommission,t.gci_goal):null,j=N=>{switch(N){case"ahead":return s.jsxs(ir,{className:"bg-green-500 text-white",children:[s.jsx(r0,{className:"h-3 w-3 mr-1"}),"Ahead"]});case"on-track":return s.jsxs(ir,{variant:"secondary",children:[s.jsx(xoe,{className:"h-3 w-3 mr-1"}),"On Track"]});case"behind":return s.jsxs(ir,{variant:"destructive",children:[s.jsx(Soe,{className:"h-3 w-3 mr-1"}),"Behind"]});default:return null}};return!t.transactions_goal&&!t.volume_goal&&!t.gci_goal?null:s.jsxs(at,{children:[s.jsx(xr,{className:"pb-3",children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(rD,{className:"h-5 w-5 text-primary"}),s.jsxs(wr,{children:[r," Goals Progress"]})]})}),s.jsx(ct,{children:s.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[t.transactions_goal&&m&&s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-sm font-medium",children:"Transactions"}),j(m.status)]}),s.jsx(vc,{value:m.percent,className:"h-2"}),s.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[s.jsxs("span",{children:[e.totalTransactions," of ",t.transactions_goal]}),s.jsxs("span",{children:[Math.round(m.percent),"%"]})]}),m.remaining>0&&c>0&&s.jsxs("p",{className:"text-xs text-muted-foreground",children:["Need ",Math.ceil(m.pace),"/month to hit goal"]})]}),t.volume_goal&&g&&s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-sm font-medium",children:"Volume"}),j(g.status)]}),s.jsx(vc,{value:g.percent,className:"h-2"}),s.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[s.jsxs("span",{children:[fc(e.totalVolume,!0)," of ",fc(t.volume_goal,!0)]}),s.jsxs("span",{children:[Math.round(g.percent),"%"]})]}),g.remaining>0&&c>0&&s.jsxs("p",{className:"text-xs text-muted-foreground",children:["Need ",fc(g.pace,!0),"/month"]})]}),n&&t.gci_goal&&_&&s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-sm font-medium",children:"GCI"}),j(_.status)]}),s.jsx(vc,{value:_.percent,className:"h-2"}),s.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[s.jsxs("span",{children:[fc(e.totalCommission,!0)," of ",fc(t.gci_goal,!0)]}),s.jsxs("span",{children:[Math.round(_.percent),"%"]})]}),_.remaining>0&&c>0&&s.jsxs("p",{className:"text-xs text-muted-foreground",children:["Need ",fc(_.pace,!0),"/month"]})]})]})})]})}var W7e=Array.isArray,Wu=W7e,G7e=typeof IC=="object"&&IC&&IC.Object===Object&&IC,_xe=G7e,K7e=_xe,Z7e=typeof self=="object"&&self&&self.Object===Object&&self,Y7e=K7e||Z7e||Function("return this")(),Dp=Y7e,X7e=Dp,Q7e=X7e.Symbol,VT=Q7e,ree=VT,bxe=Object.prototype,J7e=bxe.hasOwnProperty,eKe=bxe.toString,wC=ree?ree.toStringTag:void 0;function tKe(t){var e=J7e.call(t,wC),r=t[wC];try{t[wC]=void 0;var n=!0}catch{}var i=eKe.call(t);return n&&(e?t[wC]=r:delete t[wC]),i}var rKe=tKe,nKe=Object.prototype,sKe=nKe.toString;function iKe(t){return sKe.call(t)}var aKe=iKe,nee=VT,oKe=rKe,lKe=aKe,cKe="[object Null]",uKe="[object Undefined]",see=nee?nee.toStringTag:void 0;function dKe(t){return t==null?t===void 0?uKe:cKe:see&&see in Object(t)?oKe(t):lKe(t)}var lg=dKe;function hKe(t){return t!=null&&typeof t=="object"}var cg=hKe,fKe=lg,pKe=cg,mKe="[object Symbol]";function gKe(t){return typeof t=="symbol"||pKe(t)&&fKe(t)==mKe}var Kj=gKe,yKe=Wu,xKe=Kj,vKe=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,_Ke=/^\w*$/;function bKe(t,e){if(yKe(t))return!1;var r=typeof t;return r=="number"||r=="symbol"||r=="boolean"||t==null||xKe(t)?!0:_Ke.test(t)||!vKe.test(t)||e!=null&&t in Object(e)}var SH=bKe;function wKe(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}var kx=wKe;const Zj=sa(kx);var jKe=lg,SKe=kx,NKe="[object AsyncFunction]",CKe="[object Function]",kKe="[object GeneratorFunction]",TKe="[object Proxy]";function EKe(t){if(!SKe(t))return!1;var e=jKe(t);return e==CKe||e==kKe||e==NKe||e==TKe}var NH=EKe;const ti=sa(NH);var AKe=Dp,PKe=AKe["__core-js_shared__"],IKe=PKe,Jz=IKe,iee=function(){var t=/[^.]+$/.exec(Jz&&Jz.keys&&Jz.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}();function MKe(t){return!!iee&&iee in t}var OKe=MKe,RKe=Function.prototype,DKe=RKe.toString;function LKe(t){if(t!=null){try{return DKe.call(t)}catch{}try{return t+""}catch{}}return""}var wxe=LKe,FKe=NH,zKe=OKe,BKe=kx,$Ke=wxe,UKe=/[\\^$.*+?()[\]{}|]/g,VKe=/^\[object .+?Constructor\]$/,qKe=Function.prototype,HKe=Object.prototype,WKe=qKe.toString,GKe=HKe.hasOwnProperty,KKe=RegExp("^"+WKe.call(GKe).replace(UKe,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function ZKe(t){if(!BKe(t)||zKe(t))return!1;var e=FKe(t)?KKe:VKe;return e.test($Ke(t))}var YKe=ZKe;function XKe(t,e){return t==null?void 0:t[e]}var QKe=XKe,JKe=YKe,eZe=QKe;function tZe(t,e){var r=eZe(t,e);return JKe(r)?r:void 0}var c0=tZe,rZe=c0,nZe=rZe(Object,"create"),cL=nZe,aee=cL;function sZe(){this.__data__=aee?aee(null):{},this.size=0}var iZe=sZe;function aZe(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e}var oZe=aZe,lZe=cL,cZe="__lodash_hash_undefined__",uZe=Object.prototype,dZe=uZe.hasOwnProperty;function hZe(t){var e=this.__data__;if(lZe){var r=e[t];return r===cZe?void 0:r}return dZe.call(e,t)?e[t]:void 0}var fZe=hZe,pZe=cL,mZe=Object.prototype,gZe=mZe.hasOwnProperty;function yZe(t){var e=this.__data__;return pZe?e[t]!==void 0:gZe.call(e,t)}var xZe=yZe,vZe=cL,_Ze="__lodash_hash_undefined__";function bZe(t,e){var r=this.__data__;return this.size+=this.has(t)?0:1,r[t]=vZe&&e===void 0?_Ze:e,this}var wZe=bZe,jZe=iZe,SZe=oZe,NZe=fZe,CZe=xZe,kZe=wZe;function Yj(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e-1}var qZe=VZe,HZe=uL;function WZe(t,e){var r=this.__data__,n=HZe(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this}var GZe=WZe,KZe=AZe,ZZe=FZe,YZe=$Ze,XZe=qZe,QZe=GZe;function Xj(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e0?1:-1},e_=function(e){return W_(e)&&e.indexOf("%")===e.length-1},hn=function(e){return xXe(e)&&!qT(e)},wXe=function(e){return $i(e)},El=function(e){return hn(e)||W_(e)},jXe=0,HT=function(e){var r=++jXe;return"".concat(e||"").concat(r)},su=function(e,r){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;if(!hn(e)&&!W_(e))return n;var o;if(e_(e)){var c=e.indexOf("%");o=r*parseFloat(e.slice(0,c))/100}else o=+e;return qT(o)&&(o=n),i&&o>r&&(o=r),o},yy=function(e){if(!e)return null;var r=Object.keys(e);return r&&r.length?e[r[0]]:null},SXe=function(e){if(!Array.isArray(e))return!1;for(var r=e.length,n={},i=0;i=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function PXe(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}var fee={click:"onClick",mousedown:"onMouseDown",mouseup:"onMouseUp",mouseover:"onMouseOver",mousemove:"onMouseMove",mouseout:"onMouseOut",mouseenter:"onMouseEnter",mouseleave:"onMouseLeave",touchcancel:"onTouchCancel",touchend:"onTouchEnd",touchmove:"onTouchMove",touchstart:"onTouchStart",contextmenu:"onContextMenu",dblclick:"onDoubleClick"},Lm=function(e){return typeof e=="string"?e:e?e.displayName||e.name||"Component":""},pee=null,tB=null,RH=function t(e){if(e===pee&&Array.isArray(tB))return tB;var r=[];return D.Children.forEach(e,function(n){$i(n)||(fXe.isFragment(n)?r=r.concat(t(n.props.children)):r.push(n))}),tB=r,pee=e,r};function dh(t,e){var r=[],n=[];return Array.isArray(e)?n=e.map(function(i){return Lm(i)}):n=[Lm(e)],RH(t).forEach(function(i){var o=_d(i,"type.displayName")||_d(i,"type.name");n.indexOf(o)!==-1&&r.push(i)}),r}function od(t,e){var r=dh(t,e);return r&&r[0]}var mee=function(e){if(!e||!e.props)return!1;var r=e.props,n=r.width,i=r.height;return!(!hn(n)||n<=0||!hn(i)||i<=0)},IXe=["a","altGlyph","altGlyphDef","altGlyphItem","animate","animateColor","animateMotion","animateTransform","circle","clipPath","color-profile","cursor","defs","desc","ellipse","feBlend","feColormatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","filter","font","font-face","font-face-format","font-face-name","font-face-url","foreignObject","g","glyph","glyphRef","hkern","image","line","lineGradient","marker","mask","metadata","missing-glyph","mpath","path","pattern","polygon","polyline","radialGradient","rect","script","set","stop","style","svg","switch","symbol","text","textPath","title","tref","tspan","use","view","vkern"],MXe=function(e){return e&&e.type&&W_(e.type)&&IXe.indexOf(e.type)>=0},OXe=function(e,r,n,i){var o,c=(o=eB==null?void 0:eB[i])!==null&&o!==void 0?o:[];return r.startsWith("data-")||!ti(e)&&(i&&c.includes(r)||kXe.includes(r))||n&&OH.includes(r)},Ks=function(e,r,n){if(!e||typeof e=="function"||typeof e=="boolean")return null;var i=e;if(D.isValidElement(e)&&(i=e.props),!Zj(i))return null;var o={};return Object.keys(i).forEach(function(c){var a;OXe((a=i)===null||a===void 0?void 0:a[c],c,r,n)&&(o[c]=i[c])}),o},xU=function t(e,r){if(e===r)return!0;var n=D.Children.count(e);if(n!==D.Children.count(r))return!1;if(n===0)return!0;if(n===1)return gee(Array.isArray(e)?e[0]:e,Array.isArray(r)?r[0]:r);for(var i=0;i=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function zXe(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}function _U(t){var e=t.children,r=t.width,n=t.height,i=t.viewBox,o=t.className,c=t.style,a=t.title,m=t.desc,g=FXe(t,LXe),_=i||{width:r,height:n,x:0,y:0},j=Ci("recharts-surface",o);return Ve.createElement("svg",vU({},Ks(g,!0,"svg"),{className:j,width:r,height:n,style:c,viewBox:"".concat(_.x," ").concat(_.y," ").concat(_.width," ").concat(_.height)}),Ve.createElement("title",null,a),Ve.createElement("desc",null,m),e)}var BXe=["children","className"];function bU(){return bU=Object.assign?Object.assign.bind():function(t){for(var e=1;e=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function UXe(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}var Na=Ve.forwardRef(function(t,e){var r=t.children,n=t.className,i=$Xe(t,BXe),o=Ci("recharts-layer",n);return Ve.createElement("g",bU({className:o},Ks(i,!0),{ref:e}),r)}),wf=function(e,r){for(var n=arguments.length,i=new Array(n>2?n-2:0),o=2;oi?0:i+e),r=r>i?i:r,r<0&&(r+=i),i=e>r?0:r-e>>>0,e>>>=0;for(var o=Array(i);++n=n?t:HXe(t,e,r)}var GXe=WXe,KXe="\\ud800-\\udfff",ZXe="\\u0300-\\u036f",YXe="\\ufe20-\\ufe2f",XXe="\\u20d0-\\u20ff",QXe=ZXe+YXe+XXe,JXe="\\ufe0e\\ufe0f",eQe="\\u200d",tQe=RegExp("["+eQe+KXe+QXe+JXe+"]");function rQe(t){return tQe.test(t)}var Ixe=rQe;function nQe(t){return t.split("")}var sQe=nQe,Mxe="\\ud800-\\udfff",iQe="\\u0300-\\u036f",aQe="\\ufe20-\\ufe2f",oQe="\\u20d0-\\u20ff",lQe=iQe+aQe+oQe,cQe="\\ufe0e\\ufe0f",uQe="["+Mxe+"]",wU="["+lQe+"]",jU="\\ud83c[\\udffb-\\udfff]",dQe="(?:"+wU+"|"+jU+")",Oxe="[^"+Mxe+"]",Rxe="(?:\\ud83c[\\udde6-\\uddff]){2}",Dxe="[\\ud800-\\udbff][\\udc00-\\udfff]",hQe="\\u200d",Lxe=dQe+"?",Fxe="["+cQe+"]?",fQe="(?:"+hQe+"(?:"+[Oxe,Rxe,Dxe].join("|")+")"+Fxe+Lxe+")*",pQe=Fxe+Lxe+fQe,mQe="(?:"+[Oxe+wU+"?",wU,Rxe,Dxe,uQe].join("|")+")",gQe=RegExp(jU+"(?="+jU+")|"+mQe+pQe,"g");function yQe(t){return t.match(gQe)||[]}var xQe=yQe,vQe=sQe,_Qe=Ixe,bQe=xQe;function wQe(t){return _Qe(t)?bQe(t):vQe(t)}var jQe=wQe,SQe=GXe,NQe=Ixe,CQe=jQe,kQe=Cxe;function TQe(t){return function(e){e=kQe(e);var r=NQe(e)?CQe(e):void 0,n=r?r[0]:e.charAt(0),i=r?SQe(r,1).join(""):e.slice(1);return n[t]()+i}}var EQe=TQe,AQe=EQe,PQe=AQe("toUpperCase"),IQe=PQe;const SL=sa(IQe);function Ha(t){return function(){return t}}const zxe=Math.cos,LO=Math.sin,Pf=Math.sqrt,FO=Math.PI,NL=2*FO,SU=Math.PI,NU=2*SU,Dv=1e-6,MQe=NU-Dv;function Bxe(t){this._+=t[0];for(let e=1,r=t.length;e=0))throw new Error(`invalid digits: ${t}`);if(e>15)return Bxe;const r=10**e;return function(n){this._+=n[0];for(let i=1,o=n.length;iDv)if(!(Math.abs(j*m-g*_)>Dv)||!o)this._append`L${this._x1=e},${this._y1=r}`;else{let C=n-c,P=i-a,A=m*m+g*g,I=C*C+P*P,O=Math.sqrt(A),R=Math.sqrt(N),z=o*Math.tan((SU-Math.acos((A+N-I)/(2*O*R)))/2),W=z/R,V=z/O;Math.abs(W-1)>Dv&&this._append`L${e+W*_},${r+W*j}`,this._append`A${o},${o},0,0,${+(j*C>_*P)},${this._x1=e+V*m},${this._y1=r+V*g}`}}arc(e,r,n,i,o,c){if(e=+e,r=+r,n=+n,c=!!c,n<0)throw new Error(`negative radius: ${n}`);let a=n*Math.cos(i),m=n*Math.sin(i),g=e+a,_=r+m,j=1^c,N=c?i-o:o-i;this._x1===null?this._append`M${g},${_}`:(Math.abs(this._x1-g)>Dv||Math.abs(this._y1-_)>Dv)&&this._append`L${g},${_}`,n&&(N<0&&(N=N%NU+NU),N>MQe?this._append`A${n},${n},0,1,${j},${e-a},${r-m}A${n},${n},0,1,${j},${this._x1=g},${this._y1=_}`:N>Dv&&this._append`A${n},${n},0,${+(N>=SU)},${j},${this._x1=e+n*Math.cos(o)},${this._y1=r+n*Math.sin(o)}`)}rect(e,r,n,i){this._append`M${this._x0=this._x1=+e},${this._y0=this._y1=+r}h${n=+n}v${+i}h${-n}Z`}toString(){return this._}}function DH(t){let e=3;return t.digits=function(r){if(!arguments.length)return e;if(r==null)e=null;else{const n=Math.floor(r);if(!(n>=0))throw new RangeError(`invalid digits: ${r}`);e=n}return t},()=>new RQe(e)}function LH(t){return typeof t=="object"&&"length"in t?t:Array.from(t)}function $xe(t){this._context=t}$xe.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;default:this._context.lineTo(t,e);break}}};function CL(t){return new $xe(t)}function Uxe(t){return t[0]}function Vxe(t){return t[1]}function qxe(t,e){var r=Ha(!0),n=null,i=CL,o=null,c=DH(a);t=typeof t=="function"?t:t===void 0?Uxe:Ha(t),e=typeof e=="function"?e:e===void 0?Vxe:Ha(e);function a(m){var g,_=(m=LH(m)).length,j,N=!1,C;for(n==null&&(o=i(C=c())),g=0;g<=_;++g)!(g<_&&r(j=m[g],g,m))===N&&((N=!N)?o.lineStart():o.lineEnd()),N&&o.point(+t(j,g,m),+e(j,g,m));if(C)return o=null,C+""||null}return a.x=function(m){return arguments.length?(t=typeof m=="function"?m:Ha(+m),a):t},a.y=function(m){return arguments.length?(e=typeof m=="function"?m:Ha(+m),a):e},a.defined=function(m){return arguments.length?(r=typeof m=="function"?m:Ha(!!m),a):r},a.curve=function(m){return arguments.length?(i=m,n!=null&&(o=i(n)),a):i},a.context=function(m){return arguments.length?(m==null?n=o=null:o=i(n=m),a):n},a}function KP(t,e,r){var n=null,i=Ha(!0),o=null,c=CL,a=null,m=DH(g);t=typeof t=="function"?t:t===void 0?Uxe:Ha(+t),e=typeof e=="function"?e:Ha(e===void 0?0:+e),r=typeof r=="function"?r:r===void 0?Vxe:Ha(+r);function g(j){var N,C,P,A=(j=LH(j)).length,I,O=!1,R,z=new Array(A),W=new Array(A);for(o==null&&(a=c(R=m())),N=0;N<=A;++N){if(!(N=C;--P)a.point(z[P],W[P]);a.lineEnd(),a.areaEnd()}O&&(z[N]=+t(I,N,j),W[N]=+e(I,N,j),a.point(n?+n(I,N,j):z[N],r?+r(I,N,j):W[N]))}if(R)return a=null,R+""||null}function _(){return qxe().defined(i).curve(c).context(o)}return g.x=function(j){return arguments.length?(t=typeof j=="function"?j:Ha(+j),n=null,g):t},g.x0=function(j){return arguments.length?(t=typeof j=="function"?j:Ha(+j),g):t},g.x1=function(j){return arguments.length?(n=j==null?null:typeof j=="function"?j:Ha(+j),g):n},g.y=function(j){return arguments.length?(e=typeof j=="function"?j:Ha(+j),r=null,g):e},g.y0=function(j){return arguments.length?(e=typeof j=="function"?j:Ha(+j),g):e},g.y1=function(j){return arguments.length?(r=j==null?null:typeof j=="function"?j:Ha(+j),g):r},g.lineX0=g.lineY0=function(){return _().x(t).y(e)},g.lineY1=function(){return _().x(t).y(r)},g.lineX1=function(){return _().x(n).y(e)},g.defined=function(j){return arguments.length?(i=typeof j=="function"?j:Ha(!!j),g):i},g.curve=function(j){return arguments.length?(c=j,o!=null&&(a=c(o)),g):c},g.context=function(j){return arguments.length?(j==null?o=a=null:a=c(o=j),g):o},g}class Hxe{constructor(e,r){this._context=e,this._x=r}areaStart(){this._line=0}areaEnd(){this._line=NaN}lineStart(){this._point=0}lineEnd(){(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line}point(e,r){switch(e=+e,r=+r,this._point){case 0:{this._point=1,this._line?this._context.lineTo(e,r):this._context.moveTo(e,r);break}case 1:this._point=2;default:{this._x?this._context.bezierCurveTo(this._x0=(this._x0+e)/2,this._y0,this._x0,r,e,r):this._context.bezierCurveTo(this._x0,this._y0=(this._y0+r)/2,e,this._y0,e,r);break}}this._x0=e,this._y0=r}}function DQe(t){return new Hxe(t,!0)}function LQe(t){return new Hxe(t,!1)}const FH={draw(t,e){const r=Pf(e/FO);t.moveTo(r,0),t.arc(0,0,r,0,NL)}},FQe={draw(t,e){const r=Pf(e/5)/2;t.moveTo(-3*r,-r),t.lineTo(-r,-r),t.lineTo(-r,-3*r),t.lineTo(r,-3*r),t.lineTo(r,-r),t.lineTo(3*r,-r),t.lineTo(3*r,r),t.lineTo(r,r),t.lineTo(r,3*r),t.lineTo(-r,3*r),t.lineTo(-r,r),t.lineTo(-3*r,r),t.closePath()}},Wxe=Pf(1/3),zQe=Wxe*2,BQe={draw(t,e){const r=Pf(e/zQe),n=r*Wxe;t.moveTo(0,-r),t.lineTo(n,0),t.lineTo(0,r),t.lineTo(-n,0),t.closePath()}},$Qe={draw(t,e){const r=Pf(e),n=-r/2;t.rect(n,n,r,r)}},UQe=.8908130915292852,Gxe=LO(FO/10)/LO(7*FO/10),VQe=LO(NL/10)*Gxe,qQe=-zxe(NL/10)*Gxe,HQe={draw(t,e){const r=Pf(e*UQe),n=VQe*r,i=qQe*r;t.moveTo(0,-r),t.lineTo(n,i);for(let o=1;o<5;++o){const c=NL*o/5,a=zxe(c),m=LO(c);t.lineTo(m*r,-a*r),t.lineTo(a*n-m*i,m*n+a*i)}t.closePath()}},rB=Pf(3),WQe={draw(t,e){const r=-Pf(e/(rB*3));t.moveTo(0,r*2),t.lineTo(-rB*r,-r),t.lineTo(rB*r,-r),t.closePath()}},Hd=-.5,Wd=Pf(3)/2,CU=1/Pf(12),GQe=(CU/2+1)*3,KQe={draw(t,e){const r=Pf(e/GQe),n=r/2,i=r*CU,o=n,c=r*CU+r,a=-o,m=c;t.moveTo(n,i),t.lineTo(o,c),t.lineTo(a,m),t.lineTo(Hd*n-Wd*i,Wd*n+Hd*i),t.lineTo(Hd*o-Wd*c,Wd*o+Hd*c),t.lineTo(Hd*a-Wd*m,Wd*a+Hd*m),t.lineTo(Hd*n+Wd*i,Hd*i-Wd*n),t.lineTo(Hd*o+Wd*c,Hd*c-Wd*o),t.lineTo(Hd*a+Wd*m,Hd*m-Wd*a),t.closePath()}};function ZQe(t,e){let r=null,n=DH(i);t=typeof t=="function"?t:Ha(t||FH),e=typeof e=="function"?e:Ha(e===void 0?64:+e);function i(){let o;if(r||(r=o=n()),t.apply(this,arguments).draw(r,+e.apply(this,arguments)),o)return r=null,o+""||null}return i.type=function(o){return arguments.length?(t=typeof o=="function"?o:Ha(o),i):t},i.size=function(o){return arguments.length?(e=typeof o=="function"?o:Ha(+o),i):e},i.context=function(o){return arguments.length?(r=o??null,i):r},i}function zO(){}function BO(t,e,r){t._context.bezierCurveTo((2*t._x0+t._x1)/3,(2*t._y0+t._y1)/3,(t._x0+2*t._x1)/3,(t._y0+2*t._y1)/3,(t._x0+4*t._x1+e)/6,(t._y0+4*t._y1+r)/6)}function Kxe(t){this._context=t}Kxe.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){switch(this._point){case 3:BO(this,this._x1,this._y1);case 2:this._context.lineTo(this._x1,this._y1);break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;break;case 2:this._point=3,this._context.lineTo((5*this._x0+this._x1)/6,(5*this._y0+this._y1)/6);default:BO(this,t,e);break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}};function YQe(t){return new Kxe(t)}function Zxe(t){this._context=t}Zxe.prototype={areaStart:zO,areaEnd:zO,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._y0=this._y1=this._y2=this._y3=this._y4=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:{this._context.moveTo(this._x2,this._y2),this._context.closePath();break}case 2:{this._context.moveTo((this._x2+2*this._x3)/3,(this._y2+2*this._y3)/3),this._context.lineTo((this._x3+2*this._x2)/3,(this._y3+2*this._y2)/3),this._context.closePath();break}case 3:{this.point(this._x2,this._y2),this.point(this._x3,this._y3),this.point(this._x4,this._y4);break}}},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._x2=t,this._y2=e;break;case 1:this._point=2,this._x3=t,this._y3=e;break;case 2:this._point=3,this._x4=t,this._y4=e,this._context.moveTo((this._x0+4*this._x1+t)/6,(this._y0+4*this._y1+e)/6);break;default:BO(this,t,e);break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}};function XQe(t){return new Zxe(t)}function Yxe(t){this._context=t}Yxe.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===3)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3;var r=(this._x0+4*this._x1+t)/6,n=(this._y0+4*this._y1+e)/6;this._line?this._context.lineTo(r,n):this._context.moveTo(r,n);break;case 3:this._point=4;default:BO(this,t,e);break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}};function QQe(t){return new Yxe(t)}function Xxe(t){this._context=t}Xxe.prototype={areaStart:zO,areaEnd:zO,lineStart:function(){this._point=0},lineEnd:function(){this._point&&this._context.closePath()},point:function(t,e){t=+t,e=+e,this._point?this._context.lineTo(t,e):(this._point=1,this._context.moveTo(t,e))}};function JQe(t){return new Xxe(t)}function xee(t){return t<0?-1:1}function vee(t,e,r){var n=t._x1-t._x0,i=e-t._x1,o=(t._y1-t._y0)/(n||i<0&&-0),c=(r-t._y1)/(i||n<0&&-0),a=(o*i+c*n)/(n+i);return(xee(o)+xee(c))*Math.min(Math.abs(o),Math.abs(c),.5*Math.abs(a))||0}function _ee(t,e){var r=t._x1-t._x0;return r?(3*(t._y1-t._y0)/r-e)/2:e}function nB(t,e,r){var n=t._x0,i=t._y0,o=t._x1,c=t._y1,a=(o-n)/3;t._context.bezierCurveTo(n+a,i+a*e,o-a,c-a*r,o,c)}function $O(t){this._context=t}$O.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=this._t0=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x1,this._y1);break;case 3:nB(this,this._t0,_ee(this,this._t0));break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){var r=NaN;if(t=+t,e=+e,!(t===this._x1&&e===this._y1)){switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;break;case 2:this._point=3,nB(this,_ee(this,r=vee(this,t,e)),r);break;default:nB(this,this._t0,r=vee(this,t,e));break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e,this._t0=r}}};function Qxe(t){this._context=new Jxe(t)}(Qxe.prototype=Object.create($O.prototype)).point=function(t,e){$O.prototype.point.call(this,e,t)};function Jxe(t){this._context=t}Jxe.prototype={moveTo:function(t,e){this._context.moveTo(e,t)},closePath:function(){this._context.closePath()},lineTo:function(t,e){this._context.lineTo(e,t)},bezierCurveTo:function(t,e,r,n,i,o){this._context.bezierCurveTo(e,t,n,r,o,i)}};function eJe(t){return new $O(t)}function tJe(t){return new Qxe(t)}function eve(t){this._context=t}eve.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=[],this._y=[]},lineEnd:function(){var t=this._x,e=this._y,r=t.length;if(r)if(this._line?this._context.lineTo(t[0],e[0]):this._context.moveTo(t[0],e[0]),r===2)this._context.lineTo(t[1],e[1]);else for(var n=bee(t),i=bee(e),o=0,c=1;c=0;--e)i[e]=(c[e]-i[e+1])/o[e];for(o[r-1]=(t[r]+i[r-1])/2,e=0;e=0&&(this._t=1-this._t,this._line=1-this._line)},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;default:{if(this._t<=0)this._context.lineTo(this._x,e),this._context.lineTo(t,e);else{var r=this._x*(1-this._t)+t*this._t;this._context.lineTo(r,this._y),this._context.lineTo(r,e)}break}}this._x=t,this._y=e}};function nJe(t){return new kL(t,.5)}function sJe(t){return new kL(t,0)}function iJe(t){return new kL(t,1)}function tj(t,e){if((c=t.length)>1)for(var r=1,n,i,o=t[e[0]],c,a=o.length;r=0;)r[e]=e;return r}function aJe(t,e){return t[e]}function oJe(t){const e=[];return e.key=t,e}function lJe(){var t=Ha([]),e=kU,r=tj,n=aJe;function i(o){var c=Array.from(t.apply(this,arguments),oJe),a,m=c.length,g=-1,_;for(const j of o)for(a=0,++g;a0){for(var r,n,i=0,o=t[0].length,c;i0){for(var r=0,n=t[e[0]],i,o=n.length;r0)||!((o=(i=t[e[0]]).length)>0))){for(var r=0,n=1,i,o,c;n=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function yJe(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}var tve={symbolCircle:FH,symbolCross:FQe,symbolDiamond:BQe,symbolSquare:$Qe,symbolStar:HQe,symbolTriangle:WQe,symbolWye:KQe},xJe=Math.PI/180,vJe=function(e){var r="symbol".concat(SL(e));return tve[r]||FH},_Je=function(e,r,n){if(r==="area")return e;switch(n){case"cross":return 5*e*e/9;case"diamond":return .5*e*e/Math.sqrt(3);case"square":return e*e;case"star":{var i=18*xJe;return 1.25*e*e*(Math.tan(i)-Math.tan(i*2)*Math.pow(Math.tan(i),2))}case"triangle":return Math.sqrt(3)*e*e/4;case"wye":return(21-10*Math.sqrt(3))*e*e/8;default:return Math.PI*e*e/4}},bJe=function(e,r){tve["symbol".concat(SL(e))]=r},zH=function(e){var r=e.type,n=r===void 0?"circle":r,i=e.size,o=i===void 0?64:i,c=e.sizeType,a=c===void 0?"area":c,m=gJe(e,hJe),g=jee(jee({},m),{},{type:n,size:o,sizeType:a}),_=function(){var I=vJe(n),O=ZQe().type(I).size(_Je(o,a,n));return O()},j=g.className,N=g.cx,C=g.cy,P=Ks(g,!0);return N===+N&&C===+C&&o===+o?Ve.createElement("path",TU({},P,{className:Ci("recharts-symbols",j),transform:"translate(".concat(N,", ").concat(C,")"),d:_()})):null};zH.registerSymbol=bJe;function rj(t){"@babel/helpers - typeof";return rj=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},rj(t)}function EU(){return EU=Object.assign?Object.assign.bind():function(t){for(var e=1;e`);var R=C.inactive?g:C.color;return Ve.createElement("li",EU({className:I,style:j,key:"legend-item-".concat(P)},G_(n.props,C,P)),Ve.createElement(_U,{width:c,height:c,viewBox:_,style:N},n.renderIcon(C)),Ve.createElement("span",{className:"recharts-legend-item-text",style:{color:R}},A?A(O,C,P):O))})}},{key:"render",value:function(){var n=this.props,i=n.payload,o=n.layout,c=n.align;if(!i||!i.length)return null;var a={padding:0,margin:0,textAlign:o==="horizontal"?c:"left"};return Ve.createElement("ul",{className:"recharts-default-legend",style:a},this.renderItems())}}])}(D.PureComponent);jk(BH,"displayName","Legend");jk(BH,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"middle",inactiveColor:"#ccc"});var PJe=dL;function IJe(){this.__data__=new PJe,this.size=0}var MJe=IJe;function OJe(t){var e=this.__data__,r=e.delete(t);return this.size=e.size,r}var RJe=OJe;function DJe(t){return this.__data__.get(t)}var LJe=DJe;function FJe(t){return this.__data__.has(t)}var zJe=FJe,BJe=dL,$Je=kH,UJe=TH,VJe=200;function qJe(t,e){var r=this.__data__;if(r instanceof BJe){var n=r.__data__;if(!$Je||n.lengtha))return!1;var g=o.get(t),_=o.get(e);if(g&&_)return g==e&&_==t;var j=-1,N=!0,C=r&fet?new cet:void 0;for(o.set(t,e),o.set(e,t);++j-1&&t%1==0&&t-1&&t%1==0&&t<=xtt}var qH=vtt,_tt=lg,btt=qH,wtt=cg,jtt="[object Arguments]",Stt="[object Array]",Ntt="[object Boolean]",Ctt="[object Date]",ktt="[object Error]",Ttt="[object Function]",Ett="[object Map]",Att="[object Number]",Ptt="[object Object]",Itt="[object RegExp]",Mtt="[object Set]",Ott="[object String]",Rtt="[object WeakMap]",Dtt="[object ArrayBuffer]",Ltt="[object DataView]",Ftt="[object Float32Array]",ztt="[object Float64Array]",Btt="[object Int8Array]",$tt="[object Int16Array]",Utt="[object Int32Array]",Vtt="[object Uint8Array]",qtt="[object Uint8ClampedArray]",Htt="[object Uint16Array]",Wtt="[object Uint32Array]",to={};to[Ftt]=to[ztt]=to[Btt]=to[$tt]=to[Utt]=to[Vtt]=to[qtt]=to[Htt]=to[Wtt]=!0;to[jtt]=to[Stt]=to[Dtt]=to[Ntt]=to[Ltt]=to[Ctt]=to[ktt]=to[Ttt]=to[Ett]=to[Att]=to[Ptt]=to[Itt]=to[Mtt]=to[Ott]=to[Rtt]=!1;function Gtt(t){return wtt(t)&&btt(t.length)&&!!to[_tt(t)]}var Ktt=Gtt;function Ztt(t){return function(e){return t(e)}}var hve=Ztt,HO={exports:{}};HO.exports;(function(t,e){var r=_xe,n=e&&!e.nodeType&&e,i=n&&!0&&t&&!t.nodeType&&t,o=i&&i.exports===n,c=o&&r.process,a=function(){try{var m=i&&i.require&&i.require("util").types;return m||c&&c.binding&&c.binding("util")}catch{}}();t.exports=a})(HO,HO.exports);var Ytt=HO.exports,Xtt=Ktt,Qtt=hve,Aee=Ytt,Pee=Aee&&Aee.isTypedArray,Jtt=Pee?Qtt(Pee):Xtt,fve=Jtt,ert=ntt,trt=UH,rrt=Wu,nrt=dve,srt=VH,irt=fve,art=Object.prototype,ort=art.hasOwnProperty;function lrt(t,e){var r=rrt(t),n=!r&&trt(t),i=!r&&!n&&nrt(t),o=!r&&!n&&!i&&irt(t),c=r||n||i||o,a=c?ert(t.length,String):[],m=a.length;for(var g in t)(e||ort.call(t,g))&&!(c&&(g=="length"||i&&(g=="offset"||g=="parent")||o&&(g=="buffer"||g=="byteLength"||g=="byteOffset")||srt(g,m)))&&a.push(g);return a}var crt=lrt,urt=Object.prototype;function drt(t){var e=t&&t.constructor,r=typeof e=="function"&&e.prototype||urt;return t===r}var hrt=drt;function frt(t,e){return function(r){return t(e(r))}}var pve=frt,prt=pve,mrt=prt(Object.keys,Object),grt=mrt,yrt=hrt,xrt=grt,vrt=Object.prototype,_rt=vrt.hasOwnProperty;function brt(t){if(!yrt(t))return xrt(t);var e=[];for(var r in Object(t))_rt.call(t,r)&&r!="constructor"&&e.push(r);return e}var wrt=brt,jrt=NH,Srt=qH;function Nrt(t){return t!=null&&Srt(t.length)&&!jrt(t)}var WT=Nrt,Crt=crt,krt=wrt,Trt=WT;function Ert(t){return Trt(t)?Crt(t):krt(t)}var TL=Ert,Art=Het,Prt=ttt,Irt=TL;function Mrt(t){return Art(t,Irt,Prt)}var Ort=Mrt,Iee=Ort,Rrt=1,Drt=Object.prototype,Lrt=Drt.hasOwnProperty;function Frt(t,e,r,n,i,o){var c=r&Rrt,a=Iee(t),m=a.length,g=Iee(e),_=g.length;if(m!=_&&!c)return!1;for(var j=m;j--;){var N=a[j];if(!(c?N in e:Lrt.call(e,N)))return!1}var C=o.get(t),P=o.get(e);if(C&&P)return C==e&&P==t;var A=!0;o.set(t,e),o.set(e,t);for(var I=c;++j-1}var Dst=Rst;function Lst(t,e,r){for(var n=-1,i=t==null?0:t.length;++n=Qst){var g=e?null:Yst(t);if(g)return Xst(g);c=!1,i=Zst,m=new Wst}else m=e?[]:a;e:for(;++n=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function pit(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}function mit(t){return t.value}function git(t,e){if(Ve.isValidElement(t))return Ve.cloneElement(t,e);if(typeof t=="function")return Ve.createElement(t,e);e.ref;var r=fit(e,iit);return Ve.createElement(BH,r)}var Kee=1,u1=function(t){function e(){var r;ait(this,e);for(var n=arguments.length,i=new Array(n),o=0;oKee||Math.abs(i.height-this.lastBoundingBox.height)>Kee)&&(this.lastBoundingBox.width=i.width,this.lastBoundingBox.height=i.height,n&&n(i)):(this.lastBoundingBox.width!==-1||this.lastBoundingBox.height!==-1)&&(this.lastBoundingBox.width=-1,this.lastBoundingBox.height=-1,n&&n(null))}},{key:"getBBoxSnapshot",value:function(){return this.lastBoundingBox.width>=0&&this.lastBoundingBox.height>=0?ym({},this.lastBoundingBox):{width:0,height:0}}},{key:"getDefaultPosition",value:function(n){var i=this.props,o=i.layout,c=i.align,a=i.verticalAlign,m=i.margin,g=i.chartWidth,_=i.chartHeight,j,N;if(!n||(n.left===void 0||n.left===null)&&(n.right===void 0||n.right===null))if(c==="center"&&o==="vertical"){var C=this.getBBoxSnapshot();j={left:((g||0)-C.width)/2}}else j=c==="right"?{right:m&&m.right||0}:{left:m&&m.left||0};if(!n||(n.top===void 0||n.top===null)&&(n.bottom===void 0||n.bottom===null))if(a==="middle"){var P=this.getBBoxSnapshot();N={top:((_||0)-P.height)/2}}else N=a==="bottom"?{bottom:m&&m.bottom||0}:{top:m&&m.top||0};return ym(ym({},j),N)}},{key:"render",value:function(){var n=this,i=this.props,o=i.content,c=i.width,a=i.height,m=i.wrapperStyle,g=i.payloadUniqBy,_=i.payload,j=ym(ym({position:"absolute",width:c||"auto",height:a||"auto"},this.getDefaultPosition(m)),m);return Ve.createElement("div",{className:"recharts-legend-wrapper",style:j,ref:function(C){n.wrapperNode=C}},git(o,ym(ym({},this.props),{},{payload:bve(_,g,mit)})))}}],[{key:"getWithHeight",value:function(n,i){var o=ym(ym({},this.defaultProps),n.props),c=o.layout;return c==="vertical"&&hn(n.props.height)?{height:n.props.height}:c==="horizontal"?{width:n.props.width||i}:null}}])}(D.PureComponent);EL(u1,"displayName","Legend");EL(u1,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"bottom"});var Zee=VT,yit=UH,xit=Wu,Yee=Zee?Zee.isConcatSpreadable:void 0;function vit(t){return xit(t)||yit(t)||!!(Yee&&t&&t[Yee])}var _it=vit,bit=cve,wit=_it;function Sve(t,e,r,n,i){var o=-1,c=t.length;for(r||(r=wit),i||(i=[]);++o0&&r(a)?e>1?Sve(a,e-1,r,n,i):bit(i,a):n||(i[i.length]=a)}return i}var Nve=Sve;function jit(t){return function(e,r,n){for(var i=-1,o=Object(e),c=n(e),a=c.length;a--;){var m=c[t?a:++i];if(r(o[m],m,o)===!1)break}return e}}var Sit=jit,Nit=Sit,Cit=Nit(),kit=Cit,Tit=kit,Eit=TL;function Ait(t,e){return t&&Tit(t,e,Eit)}var Cve=Ait,Pit=WT;function Iit(t,e){return function(r,n){if(r==null)return r;if(!Pit(r))return t(r,n);for(var i=r.length,o=e?i:-1,c=Object(r);(e?o--:++oe||o&&c&&m&&!a&&!g||n&&c&&m||!r&&m||!i)return 1;if(!n&&!o&&!g&&t=a)return m;var g=r[n];return m*(g=="desc"?-1:1)}}return t.index-e.index}var Wit=Hit,oB=AH,Git=PH,Kit=Lp,Zit=kve,Yit=$it,Xit=hve,Qit=Wit,Jit=tS,eat=Wu;function tat(t,e,r){e.length?e=oB(e,function(o){return eat(o)?function(c){return Git(c,o.length===1?o[0]:o)}:o}):e=[Jit];var n=-1;e=oB(e,Xit(Kit));var i=Zit(t,function(o,c,a){var m=oB(e,function(g){return g(o)});return{criteria:m,index:++n,value:o}});return Yit(i,function(o,c){return Qit(o,c,r)})}var rat=tat;function nat(t,e,r){switch(r.length){case 0:return t.call(e);case 1:return t.call(e,r[0]);case 2:return t.call(e,r[0],r[1]);case 3:return t.call(e,r[0],r[1],r[2])}return t.apply(e,r)}var sat=nat,iat=sat,Qee=Math.max;function aat(t,e,r){return e=Qee(e===void 0?t.length-1:e,0),function(){for(var n=arguments,i=-1,o=Qee(n.length-e,0),c=Array(o);++i0){if(++e>=gat)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}var _at=vat,bat=mat,wat=_at,jat=wat(bat),Sat=jat,Nat=tS,Cat=oat,kat=Sat;function Tat(t,e){return kat(Cat(t,e,Nat),t+"")}var Eat=Tat,Aat=CH,Pat=WT,Iat=VH,Mat=kx;function Oat(t,e,r){if(!Mat(r))return!1;var n=typeof e;return(n=="number"?Pat(r)&&Iat(e,r.length):n=="string"&&e in r)?Aat(r[e],t):!1}var AL=Oat,Rat=Nve,Dat=rat,Lat=Eat,ete=AL,Fat=Lat(function(t,e){if(t==null)return[];var r=e.length;return r>1&&ete(t,e[0],e[1])?e=[]:r>2&&ete(e[0],e[1],e[2])&&(e=[e[0]]),Dat(t,Rat(e,1),[])}),zat=Fat;const GH=sa(zat);function Sk(t){"@babel/helpers - typeof";return Sk=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Sk(t)}function LU(){return LU=Object.assign?Object.assign.bind():function(t){for(var e=1;et.length)&&(e=t.length);for(var r=0,n=new Array(e);r=e.x),"".concat(jC,"-left"),hn(r)&&e&&hn(e.x)&&r=e.y),"".concat(jC,"-top"),hn(n)&&e&&hn(e.y)&&nA?Math.max(_,m[n]):Math.max(j,m[n])}function eot(t){var e=t.translateX,r=t.translateY,n=t.useTranslate3d;return{transform:n?"translate3d(".concat(e,"px, ").concat(r,"px, 0)"):"translate(".concat(e,"px, ").concat(r,"px)")}}function tot(t){var e=t.allowEscapeViewBox,r=t.coordinate,n=t.offsetTopLeft,i=t.position,o=t.reverseDirection,c=t.tooltipBox,a=t.useTranslate3d,m=t.viewBox,g,_,j;return c.height>0&&c.width>0&&r?(_=nte({allowEscapeViewBox:e,coordinate:r,key:"x",offsetTopLeft:n,position:i,reverseDirection:o,tooltipDimension:c.width,viewBox:m,viewBoxDimension:m.width}),j=nte({allowEscapeViewBox:e,coordinate:r,key:"y",offsetTopLeft:n,position:i,reverseDirection:o,tooltipDimension:c.height,viewBox:m,viewBoxDimension:m.height}),g=eot({translateX:_,translateY:j,useTranslate3d:a})):g=Qat,{cssProperties:g,cssClasses:Jat({translateX:_,translateY:j,coordinate:r})}}function sj(t){"@babel/helpers - typeof";return sj=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},sj(t)}function ste(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function ite(t){for(var e=1;eate||Math.abs(n.height-this.state.lastBoundingBox.height)>ate)&&this.setState({lastBoundingBox:{width:n.width,height:n.height}})}else(this.state.lastBoundingBox.width!==-1||this.state.lastBoundingBox.height!==-1)&&this.setState({lastBoundingBox:{width:-1,height:-1}})}},{key:"componentDidMount",value:function(){document.addEventListener("keydown",this.handleKeyDown),this.updateBBox()}},{key:"componentWillUnmount",value:function(){document.removeEventListener("keydown",this.handleKeyDown)}},{key:"componentDidUpdate",value:function(){var n,i;this.props.active&&this.updateBBox(),this.state.dismissed&&(((n=this.props.coordinate)===null||n===void 0?void 0:n.x)!==this.state.dismissedAtCoordinate.x||((i=this.props.coordinate)===null||i===void 0?void 0:i.y)!==this.state.dismissedAtCoordinate.y)&&(this.state.dismissed=!1)}},{key:"render",value:function(){var n=this,i=this.props,o=i.active,c=i.allowEscapeViewBox,a=i.animationDuration,m=i.animationEasing,g=i.children,_=i.coordinate,j=i.hasPayload,N=i.isAnimationActive,C=i.offset,P=i.position,A=i.reverseDirection,I=i.useTranslate3d,O=i.viewBox,R=i.wrapperStyle,z=tot({allowEscapeViewBox:c,coordinate:_,offsetTopLeft:C,position:P,reverseDirection:A,tooltipBox:this.state.lastBoundingBox,useTranslate3d:I,viewBox:O}),W=z.cssClasses,V=z.cssProperties,K=ite(ite({transition:N&&o?"transform ".concat(a,"ms ").concat(m):void 0},V),{},{pointerEvents:"none",visibility:!this.state.dismissed&&o&&j?"visible":"hidden",position:"absolute",top:0,left:0},R);return Ve.createElement("div",{tabIndex:-1,className:W,style:K,ref:function(te){n.wrapperNode=te}},g)}}])}(D.PureComponent),dot=function(){return!(typeof window<"u"&&window.document&&window.document.createElement&&window.setTimeout)},rS={isSsr:dot()};function ij(t){"@babel/helpers - typeof";return ij=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},ij(t)}function ote(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function lte(t){for(var e=1;e0;return Ve.createElement(uot,{allowEscapeViewBox:c,animationDuration:a,animationEasing:m,isAnimationActive:N,active:o,coordinate:_,hasPayload:K,offset:C,position:I,reverseDirection:O,useTranslate3d:R,viewBox:z,wrapperStyle:W},bot(g,lte(lte({},this.props),{},{payload:V})))}}])}(D.PureComponent);KH(lf,"displayName","Tooltip");KH(lf,"defaultProps",{accessibilityLayer:!1,allowEscapeViewBox:{x:!1,y:!1},animationDuration:400,animationEasing:"ease",contentStyle:{},coordinate:{x:0,y:0},cursor:!0,cursorStyle:{},filterNull:!0,isAnimationActive:!rS.isSsr,itemStyle:{},labelStyle:{},offset:10,reverseDirection:{x:!1,y:!1},separator:" : ",trigger:"hover",useTranslate3d:!1,viewBox:{x:0,y:0,height:0,width:0},wrapperStyle:{}});var wot=Dp,jot=function(){return wot.Date.now()},Sot=jot,Not=/\s/;function Cot(t){for(var e=t.length;e--&&Not.test(t.charAt(e)););return e}var kot=Cot,Tot=kot,Eot=/^\s+/;function Aot(t){return t&&t.slice(0,Tot(t)+1).replace(Eot,"")}var Pot=Aot,Iot=Pot,cte=kx,Mot=Kj,ute=NaN,Oot=/^[-+]0x[0-9a-f]+$/i,Rot=/^0b[01]+$/i,Dot=/^0o[0-7]+$/i,Lot=parseInt;function Fot(t){if(typeof t=="number")return t;if(Mot(t))return ute;if(cte(t)){var e=typeof t.valueOf=="function"?t.valueOf():t;t=cte(e)?e+"":e}if(typeof t!="string")return t===0?t:+t;t=Iot(t);var r=Rot.test(t);return r||Dot.test(t)?Lot(t.slice(2),r?2:8):Oot.test(t)?ute:+t}var Mve=Fot,zot=kx,cB=Sot,dte=Mve,Bot="Expected a function",$ot=Math.max,Uot=Math.min;function Vot(t,e,r){var n,i,o,c,a,m,g=0,_=!1,j=!1,N=!0;if(typeof t!="function")throw new TypeError(Bot);e=dte(e)||0,zot(r)&&(_=!!r.leading,j="maxWait"in r,o=j?$ot(dte(r.maxWait)||0,e):o,N="trailing"in r?!!r.trailing:N);function C(K){var Q=n,te=i;return n=i=void 0,g=K,c=t.apply(te,Q),c}function P(K){return g=K,a=setTimeout(O,e),_?C(K):c}function A(K){var Q=K-m,te=K-g,X=e-Q;return j?Uot(X,o-te):X}function I(K){var Q=K-m,te=K-g;return m===void 0||Q>=e||Q<0||j&&te>=o}function O(){var K=cB();if(I(K))return R(K);a=setTimeout(O,A(K))}function R(K){return a=void 0,N&&n?C(K):(n=i=void 0,c)}function z(){a!==void 0&&clearTimeout(a),g=0,n=m=i=a=void 0}function W(){return a===void 0?c:R(cB())}function V(){var K=cB(),Q=I(K);if(n=arguments,i=this,m=K,Q){if(a===void 0)return P(m);if(j)return clearTimeout(a),a=setTimeout(O,e),C(m)}return a===void 0&&(a=setTimeout(O,e)),c}return V.cancel=z,V.flush=W,V}var qot=Vot,Hot=qot,Wot=kx,Got="Expected a function";function Kot(t,e,r){var n=!0,i=!0;if(typeof t!="function")throw new TypeError(Got);return Wot(r)&&(n="leading"in r?!!r.leading:n,i="trailing"in r?!!r.trailing:i),Hot(t,e,{leading:n,maxWait:e,trailing:i})}var Zot=Kot;const Ove=sa(Zot);function Ck(t){"@babel/helpers - typeof";return Ck=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Ck(t)}function hte(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function XP(t){for(var e=1;et.length)&&(e=t.length);for(var r=0,n=new Array(e);r0&&(pe=Ove(pe,A,{trailing:!0,leading:!1}));var ve=new ResizeObserver(pe),ge=V.current.getBoundingClientRect(),ke=ge.width,Ce=ge.height;return he(ke,Ce),ve.observe(V.current),function(){ve.disconnect()}},[he,A]);var xe=D.useMemo(function(){var pe=X.containerWidth,ve=X.containerHeight;if(pe<0||ve<0)return null;wf(e_(c)||e_(m),`The width(%s) and height(%s) are both fixed numbers, maybe you don't need to use a ResponsiveContainer.`,c,m),wf(!r||r>0,"The aspect(%s) must be greater than zero.",r);var ge=e_(c)?pe:c,ke=e_(m)?ve:m;r&&r>0&&(ge?ke=ge/r:ke&&(ge=ke*r),N&&ke>N&&(ke=N)),wf(ge>0||ke>0,`The width(%s) and height(%s) of chart should be greater than 0, please check the style of container, or the props width(%s) and height(%s), or add a minWidth(%s) or minHeight(%s) or use aspect(%s) to control the height and width.`,ge,ke,c,m,_,j,r);var Ce=!Array.isArray(C)&&Lm(C.type).endsWith("Chart");return Ve.Children.map(C,function(Se){return Ve.isValidElement(Se)?D.cloneElement(Se,XP({width:ge,height:ke},Ce?{style:XP({height:"100%",width:"100%",maxHeight:ke,maxWidth:ge},Se.props.style)}:{})):Se})},[r,C,m,N,j,_,X,c]);return Ve.createElement("div",{id:I?"".concat(I):void 0,className:Ci("recharts-responsive-container",O),style:XP(XP({},W),{},{width:c,height:m,minWidth:_,minHeight:j,maxHeight:N}),ref:V},xe)}),PL=function(e){return null};PL.displayName="Cell";function kk(t){"@babel/helpers - typeof";return kk=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},kk(t)}function pte(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function UU(t){for(var e=1;e1&&arguments[1]!==void 0?arguments[1]:{};if(e==null||rS.isSsr)return{width:0,height:0};var n=clt(r),i=JSON.stringify({text:e,copyStyle:n});if(gw.widthCache[i])return gw.widthCache[i];try{var o=document.getElementById(mte);o||(o=document.createElement("span"),o.setAttribute("id",mte),o.setAttribute("aria-hidden","true"),document.body.appendChild(o));var c=UU(UU({},llt),n);Object.assign(o.style,c),o.textContent="".concat(e);var a=o.getBoundingClientRect(),m={width:a.width,height:a.height};return gw.widthCache[i]=m,++gw.cacheCount>olt&&(gw.cacheCount=0,gw.widthCache={}),m}catch{return{width:0,height:0}}},ult=function(e){return{top:e.top+window.scrollY-document.documentElement.clientTop,left:e.left+window.scrollX-document.documentElement.clientLeft}};function Tk(t){"@babel/helpers - typeof";return Tk=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Tk(t)}function ZO(t,e){return plt(t)||flt(t,e)||hlt(t,e)||dlt()}function dlt(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function hlt(t,e){if(t){if(typeof t=="string")return gte(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set")return Array.from(t);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return gte(t,e)}}function gte(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function Tlt(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}function wte(t,e){return Ilt(t)||Plt(t,e)||Alt(t,e)||Elt()}function Elt(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Alt(t,e){if(t){if(typeof t=="string")return jte(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set")return Array.from(t);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return jte(t,e)}}function jte(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r0&&arguments[0]!==void 0?arguments[0]:[];return ge.reduce(function(ke,Ce){var Se=Ce.word,je=Ce.width,et=ke[ke.length-1];if(et&&(i==null||o||et.width+je+nCe.width?ke:Ce})};if(!_)return C;for(var A="…",I=function(ge){var ke=j.slice(0,ge),Ce=Fve({breakAll:g,style:m,children:ke+A}).wordsWithComputedWidth,Se=N(Ce),je=Se.length>c||P(Se).width>Number(i);return[je,Se]},O=0,R=j.length-1,z=0,W;O<=R&&z<=j.length-1;){var V=Math.floor((O+R)/2),K=V-1,Q=I(K),te=wte(Q,2),X=te[0],ie=te[1],he=I(V),xe=wte(he,1),pe=xe[0];if(!X&&!pe&&(O=V+1),X&&pe&&(R=V-1),!X&&pe){W=ie;break}z++}return W||C},Ste=function(e){var r=$i(e)?[]:e.toString().split(Lve);return[{words:r}]},Olt=function(e){var r=e.width,n=e.scaleToFit,i=e.children,o=e.style,c=e.breakAll,a=e.maxLines;if((r||n)&&!rS.isSsr){var m,g,_=Fve({breakAll:c,children:i,style:o});if(_){var j=_.wordsWithComputedWidth,N=_.spaceWidth;m=j,g=N}else return Ste(i);return Mlt({breakAll:c,children:i,maxLines:a,style:o},m,g,r,n)}return Ste(i)},Nte="#808080",K_=function(e){var r=e.x,n=r===void 0?0:r,i=e.y,o=i===void 0?0:i,c=e.lineHeight,a=c===void 0?"1em":c,m=e.capHeight,g=m===void 0?"0.71em":m,_=e.scaleToFit,j=_===void 0?!1:_,N=e.textAnchor,C=N===void 0?"start":N,P=e.verticalAnchor,A=P===void 0?"end":P,I=e.fill,O=I===void 0?Nte:I,R=bte(e,Clt),z=D.useMemo(function(){return Olt({breakAll:R.breakAll,children:R.children,maxLines:R.maxLines,scaleToFit:j,style:R.style,width:R.width})},[R.breakAll,R.children,R.maxLines,j,R.style,R.width]),W=R.dx,V=R.dy,K=R.angle,Q=R.className,te=R.breakAll,X=bte(R,klt);if(!El(n)||!El(o))return null;var ie=n+(hn(W)?W:0),he=o+(hn(V)?V:0),xe;switch(A){case"start":xe=uB("calc(".concat(g,")"));break;case"middle":xe=uB("calc(".concat((z.length-1)/2," * -").concat(a," + (").concat(g," / 2))"));break;default:xe=uB("calc(".concat(z.length-1," * -").concat(a,")"));break}var pe=[];if(j){var ve=z[0].width,ge=R.width;pe.push("scale(".concat((hn(ge)?ge/ve:1)/ve,")"))}return K&&pe.push("rotate(".concat(K,", ").concat(ie,", ").concat(he,")")),pe.length&&(X.transform=pe.join(" ")),Ve.createElement("text",VU({},Ks(X,!0),{x:ie,y:he,className:Ci("recharts-text",Q),textAnchor:C,fill:O.includes("url")?Nte:O}),z.map(function(ke,Ce){var Se=ke.words.join(te?"":" ");return Ve.createElement("tspan",{x:ie,dy:Ce===0?xe:a,key:"".concat(Se,"-").concat(Ce)},Se)}))};function Jy(t,e){return t==null||e==null?NaN:te?1:t>=e?0:NaN}function Rlt(t,e){return t==null||e==null?NaN:et?1:e>=t?0:NaN}function ZH(t){let e,r,n;t.length!==2?(e=Jy,r=(a,m)=>Jy(t(a),m),n=(a,m)=>t(a)-m):(e=t===Jy||t===Rlt?t:Dlt,r=t,n=t);function i(a,m,g=0,_=a.length){if(g<_){if(e(m,m)!==0)return _;do{const j=g+_>>>1;r(a[j],m)<0?g=j+1:_=j}while(g<_)}return g}function o(a,m,g=0,_=a.length){if(g<_){if(e(m,m)!==0)return _;do{const j=g+_>>>1;r(a[j],m)<=0?g=j+1:_=j}while(g<_)}return g}function c(a,m,g=0,_=a.length){const j=i(a,m,g,_-1);return j>g&&n(a[j-1],m)>-n(a[j],m)?j-1:j}return{left:i,center:c,right:o}}function Dlt(){return 0}function zve(t){return t===null?NaN:+t}function*Llt(t,e){for(let r of t)r!=null&&(r=+r)>=r&&(yield r)}const Flt=ZH(Jy),GT=Flt.right;ZH(zve).center;class Cte extends Map{constructor(e,r=$lt){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:r}}),e!=null)for(const[n,i]of e)this.set(n,i)}get(e){return super.get(kte(this,e))}has(e){return super.has(kte(this,e))}set(e,r){return super.set(zlt(this,e),r)}delete(e){return super.delete(Blt(this,e))}}function kte({_intern:t,_key:e},r){const n=e(r);return t.has(n)?t.get(n):r}function zlt({_intern:t,_key:e},r){const n=e(r);return t.has(n)?t.get(n):(t.set(n,r),r)}function Blt({_intern:t,_key:e},r){const n=e(r);return t.has(n)&&(r=t.get(n),t.delete(n)),r}function $lt(t){return t!==null&&typeof t=="object"?t.valueOf():t}function Ult(t=Jy){if(t===Jy)return Bve;if(typeof t!="function")throw new TypeError("compare is not a function");return(e,r)=>{const n=t(e,r);return n||n===0?n:(t(r,r)===0)-(t(e,e)===0)}}function Bve(t,e){return(t==null||!(t>=t))-(e==null||!(e>=e))||(te?1:0)}const Vlt=Math.sqrt(50),qlt=Math.sqrt(10),Hlt=Math.sqrt(2);function YO(t,e,r){const n=(e-t)/Math.max(0,r),i=Math.floor(Math.log10(n)),o=n/Math.pow(10,i),c=o>=Vlt?10:o>=qlt?5:o>=Hlt?2:1;let a,m,g;return i<0?(g=Math.pow(10,-i)/c,a=Math.round(t*g),m=Math.round(e*g),a/ge&&--m,g=-g):(g=Math.pow(10,i)*c,a=Math.round(t/g),m=Math.round(e/g),a*ge&&--m),m0))return[];if(t===e)return[t];const n=e=i))return[];const a=o-i+1,m=new Array(a);if(n)if(c<0)for(let g=0;g=n)&&(r=n);return r}function Ete(t,e){let r;for(const n of t)n!=null&&(r>n||r===void 0&&n>=n)&&(r=n);return r}function $ve(t,e,r=0,n=1/0,i){if(e=Math.floor(e),r=Math.floor(Math.max(0,r)),n=Math.floor(Math.min(t.length-1,n)),!(r<=e&&e<=n))return t;for(i=i===void 0?Bve:Ult(i);n>r;){if(n-r>600){const m=n-r+1,g=e-r+1,_=Math.log(m),j=.5*Math.exp(2*_/3),N=.5*Math.sqrt(_*j*(m-j)/m)*(g-m/2<0?-1:1),C=Math.max(r,Math.floor(e-g*j/m+N)),P=Math.min(n,Math.floor(e+(m-g)*j/m+N));$ve(t,e,C,P,i)}const o=t[e];let c=r,a=n;for(SC(t,r,e),i(t[n],o)>0&&SC(t,r,n);c0;)--a}i(t[r],o)===0?SC(t,r,a):(++a,SC(t,a,n)),a<=e&&(r=a+1),e<=a&&(n=a-1)}return t}function SC(t,e,r){const n=t[e];t[e]=t[r],t[r]=n}function Wlt(t,e,r){if(t=Float64Array.from(Llt(t)),!(!(n=t.length)||isNaN(e=+e))){if(e<=0||n<2)return Ete(t);if(e>=1)return Tte(t);var n,i=(n-1)*e,o=Math.floor(i),c=Tte($ve(t,o).subarray(0,o+1)),a=Ete(t.subarray(o+1));return c+(a-c)*(i-o)}}function Glt(t,e,r=zve){if(!(!(n=t.length)||isNaN(e=+e))){if(e<=0||n<2)return+r(t[0],0,t);if(e>=1)return+r(t[n-1],n-1,t);var n,i=(n-1)*e,o=Math.floor(i),c=+r(t[o],o,t),a=+r(t[o+1],o+1,t);return c+(a-c)*(i-o)}}function Klt(t,e,r){t=+t,e=+e,r=(i=arguments.length)<2?(e=t,t=0,1):i<3?1:+r;for(var n=-1,i=Math.max(0,Math.ceil((e-t)/r))|0,o=new Array(i);++n>8&15|e>>4&240,e>>4&15|e&240,(e&15)<<4|e&15,1):r===8?JP(e>>24&255,e>>16&255,e>>8&255,(e&255)/255):r===4?JP(e>>12&15|e>>8&240,e>>8&15|e>>4&240,e>>4&15|e&240,((e&15)<<4|e&15)/255):null):(e=Ylt.exec(t))?new Ru(e[1],e[2],e[3],1):(e=Xlt.exec(t))?new Ru(e[1]*255/100,e[2]*255/100,e[3]*255/100,1):(e=Qlt.exec(t))?JP(e[1],e[2],e[3],e[4]):(e=Jlt.exec(t))?JP(e[1]*255/100,e[2]*255/100,e[3]*255/100,e[4]):(e=ect.exec(t))?Dte(e[1],e[2]/100,e[3]/100,1):(e=tct.exec(t))?Dte(e[1],e[2]/100,e[3]/100,e[4]):Ate.hasOwnProperty(t)?Mte(Ate[t]):t==="transparent"?new Ru(NaN,NaN,NaN,0):null}function Mte(t){return new Ru(t>>16&255,t>>8&255,t&255,1)}function JP(t,e,r,n){return n<=0&&(t=e=r=NaN),new Ru(t,e,r,n)}function sct(t){return t instanceof KT||(t=Ik(t)),t?(t=t.rgb(),new Ru(t.r,t.g,t.b,t.opacity)):new Ru}function KU(t,e,r,n){return arguments.length===1?sct(t):new Ru(t,e,r,n??1)}function Ru(t,e,r,n){this.r=+t,this.g=+e,this.b=+r,this.opacity=+n}XH(Ru,KU,Vve(KT,{brighter(t){return t=t==null?XO:Math.pow(XO,t),new Ru(this.r*t,this.g*t,this.b*t,this.opacity)},darker(t){return t=t==null?Ak:Math.pow(Ak,t),new Ru(this.r*t,this.g*t,this.b*t,this.opacity)},rgb(){return this},clamp(){return new Ru(w_(this.r),w_(this.g),w_(this.b),QO(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:Ote,formatHex:Ote,formatHex8:ict,formatRgb:Rte,toString:Rte}));function Ote(){return`#${t_(this.r)}${t_(this.g)}${t_(this.b)}`}function ict(){return`#${t_(this.r)}${t_(this.g)}${t_(this.b)}${t_((isNaN(this.opacity)?1:this.opacity)*255)}`}function Rte(){const t=QO(this.opacity);return`${t===1?"rgb(":"rgba("}${w_(this.r)}, ${w_(this.g)}, ${w_(this.b)}${t===1?")":`, ${t})`}`}function QO(t){return isNaN(t)?1:Math.max(0,Math.min(1,t))}function w_(t){return Math.max(0,Math.min(255,Math.round(t)||0))}function t_(t){return t=w_(t),(t<16?"0":"")+t.toString(16)}function Dte(t,e,r,n){return n<=0?t=e=r=NaN:r<=0||r>=1?t=e=NaN:e<=0&&(t=NaN),new pf(t,e,r,n)}function qve(t){if(t instanceof pf)return new pf(t.h,t.s,t.l,t.opacity);if(t instanceof KT||(t=Ik(t)),!t)return new pf;if(t instanceof pf)return t;t=t.rgb();var e=t.r/255,r=t.g/255,n=t.b/255,i=Math.min(e,r,n),o=Math.max(e,r,n),c=NaN,a=o-i,m=(o+i)/2;return a?(e===o?c=(r-n)/a+(r0&&m<1?0:c,new pf(c,a,m,t.opacity)}function act(t,e,r,n){return arguments.length===1?qve(t):new pf(t,e,r,n??1)}function pf(t,e,r,n){this.h=+t,this.s=+e,this.l=+r,this.opacity=+n}XH(pf,act,Vve(KT,{brighter(t){return t=t==null?XO:Math.pow(XO,t),new pf(this.h,this.s,this.l*t,this.opacity)},darker(t){return t=t==null?Ak:Math.pow(Ak,t),new pf(this.h,this.s,this.l*t,this.opacity)},rgb(){var t=this.h%360+(this.h<0)*360,e=isNaN(t)||isNaN(this.s)?0:this.s,r=this.l,n=r+(r<.5?r:1-r)*e,i=2*r-n;return new Ru(dB(t>=240?t-240:t+120,i,n),dB(t,i,n),dB(t<120?t+240:t-120,i,n),this.opacity)},clamp(){return new pf(Lte(this.h),eI(this.s),eI(this.l),QO(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const t=QO(this.opacity);return`${t===1?"hsl(":"hsla("}${Lte(this.h)}, ${eI(this.s)*100}%, ${eI(this.l)*100}%${t===1?")":`, ${t})`}`}}));function Lte(t){return t=(t||0)%360,t<0?t+360:t}function eI(t){return Math.max(0,Math.min(1,t||0))}function dB(t,e,r){return(t<60?e+(r-e)*t/60:t<180?r:t<240?e+(r-e)*(240-t)/60:e)*255}const QH=t=>()=>t;function oct(t,e){return function(r){return t+r*e}}function lct(t,e,r){return t=Math.pow(t,r),e=Math.pow(e,r)-t,r=1/r,function(n){return Math.pow(t+n*e,r)}}function cct(t){return(t=+t)==1?Hve:function(e,r){return r-e?lct(e,r,t):QH(isNaN(e)?r:e)}}function Hve(t,e){var r=e-t;return r?oct(t,r):QH(isNaN(t)?e:t)}const Fte=function t(e){var r=cct(e);function n(i,o){var c=r((i=KU(i)).r,(o=KU(o)).r),a=r(i.g,o.g),m=r(i.b,o.b),g=Hve(i.opacity,o.opacity);return function(_){return i.r=c(_),i.g=a(_),i.b=m(_),i.opacity=g(_),i+""}}return n.gamma=t,n}(1);function uct(t,e){e||(e=[]);var r=t?Math.min(e.length,t.length):0,n=e.slice(),i;return function(o){for(i=0;ir&&(o=e.slice(r,o),a[c]?a[c]+=o:a[++c]=o),(n=n[0])===(i=i[0])?a[c]?a[c]+=i:a[++c]=i:(a[++c]=null,m.push({i:c,x:JO(n,i)})),r=hB.lastIndex;return re&&(r=t,t=e,e=r),function(n){return Math.max(t,Math.min(e,n))}}function bct(t,e,r){var n=t[0],i=t[1],o=e[0],c=e[1];return i2?wct:bct,m=g=null,j}function j(N){return N==null||isNaN(N=+N)?o:(m||(m=a(t.map(n),e,r)))(n(c(N)))}return j.invert=function(N){return c(i((g||(g=a(e,t.map(n),JO)))(N)))},j.domain=function(N){return arguments.length?(t=Array.from(N,eR),_()):t.slice()},j.range=function(N){return arguments.length?(e=Array.from(N),_()):e.slice()},j.rangeRound=function(N){return e=Array.from(N),r=JH,_()},j.clamp=function(N){return arguments.length?(c=N?!0:iu,_()):c!==iu},j.interpolate=function(N){return arguments.length?(r=N,_()):r},j.unknown=function(N){return arguments.length?(o=N,j):o},function(N,C){return n=N,i=C,_()}}function eW(){return IL()(iu,iu)}function jct(t){return Math.abs(t=Math.round(t))>=1e21?t.toLocaleString("en").replace(/,/g,""):t.toString(10)}function tR(t,e){if((r=(t=e?t.toExponential(e-1):t.toExponential()).indexOf("e"))<0)return null;var r,n=t.slice(0,r);return[n.length>1?n[0]+n.slice(2):n,+t.slice(r+1)]}function aj(t){return t=tR(Math.abs(t)),t?t[1]:NaN}function Sct(t,e){return function(r,n){for(var i=r.length,o=[],c=0,a=t[0],m=0;i>0&&a>0&&(m+a+1>n&&(a=Math.max(1,n-m)),o.push(r.substring(i-=a,i+a)),!((m+=a+1)>n));)a=t[c=(c+1)%t.length];return o.reverse().join(e)}}function Nct(t){return function(e){return e.replace(/[0-9]/g,function(r){return t[+r]})}}var Cct=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function Mk(t){if(!(e=Cct.exec(t)))throw new Error("invalid format: "+t);var e;return new tW({fill:e[1],align:e[2],sign:e[3],symbol:e[4],zero:e[5],width:e[6],comma:e[7],precision:e[8]&&e[8].slice(1),trim:e[9],type:e[10]})}Mk.prototype=tW.prototype;function tW(t){this.fill=t.fill===void 0?" ":t.fill+"",this.align=t.align===void 0?">":t.align+"",this.sign=t.sign===void 0?"-":t.sign+"",this.symbol=t.symbol===void 0?"":t.symbol+"",this.zero=!!t.zero,this.width=t.width===void 0?void 0:+t.width,this.comma=!!t.comma,this.precision=t.precision===void 0?void 0:+t.precision,this.trim=!!t.trim,this.type=t.type===void 0?"":t.type+""}tW.prototype.toString=function(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(this.width===void 0?"":Math.max(1,this.width|0))+(this.comma?",":"")+(this.precision===void 0?"":"."+Math.max(0,this.precision|0))+(this.trim?"~":"")+this.type};function kct(t){e:for(var e=t.length,r=1,n=-1,i;r0&&(n=0);break}return n>0?t.slice(0,n)+t.slice(i+1):t}var Wve;function Tct(t,e){var r=tR(t,e);if(!r)return t+"";var n=r[0],i=r[1],o=i-(Wve=Math.max(-8,Math.min(8,Math.floor(i/3)))*3)+1,c=n.length;return o===c?n:o>c?n+new Array(o-c+1).join("0"):o>0?n.slice(0,o)+"."+n.slice(o):"0."+new Array(1-o).join("0")+tR(t,Math.max(0,e+o-1))[0]}function Bte(t,e){var r=tR(t,e);if(!r)return t+"";var n=r[0],i=r[1];return i<0?"0."+new Array(-i).join("0")+n:n.length>i+1?n.slice(0,i+1)+"."+n.slice(i+1):n+new Array(i-n.length+2).join("0")}const $te={"%":(t,e)=>(t*100).toFixed(e),b:t=>Math.round(t).toString(2),c:t=>t+"",d:jct,e:(t,e)=>t.toExponential(e),f:(t,e)=>t.toFixed(e),g:(t,e)=>t.toPrecision(e),o:t=>Math.round(t).toString(8),p:(t,e)=>Bte(t*100,e),r:Bte,s:Tct,X:t=>Math.round(t).toString(16).toUpperCase(),x:t=>Math.round(t).toString(16)};function Ute(t){return t}var Vte=Array.prototype.map,qte=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function Ect(t){var e=t.grouping===void 0||t.thousands===void 0?Ute:Sct(Vte.call(t.grouping,Number),t.thousands+""),r=t.currency===void 0?"":t.currency[0]+"",n=t.currency===void 0?"":t.currency[1]+"",i=t.decimal===void 0?".":t.decimal+"",o=t.numerals===void 0?Ute:Nct(Vte.call(t.numerals,String)),c=t.percent===void 0?"%":t.percent+"",a=t.minus===void 0?"−":t.minus+"",m=t.nan===void 0?"NaN":t.nan+"";function g(j){j=Mk(j);var N=j.fill,C=j.align,P=j.sign,A=j.symbol,I=j.zero,O=j.width,R=j.comma,z=j.precision,W=j.trim,V=j.type;V==="n"?(R=!0,V="g"):$te[V]||(z===void 0&&(z=12),W=!0,V="g"),(I||N==="0"&&C==="=")&&(I=!0,N="0",C="=");var K=A==="$"?r:A==="#"&&/[boxX]/.test(V)?"0"+V.toLowerCase():"",Q=A==="$"?n:/[%p]/.test(V)?c:"",te=$te[V],X=/[defgprs%]/.test(V);z=z===void 0?6:/[gprs]/.test(V)?Math.max(1,Math.min(21,z)):Math.max(0,Math.min(20,z));function ie(he){var xe=K,pe=Q,ve,ge,ke;if(V==="c")pe=te(he)+pe,he="";else{he=+he;var Ce=he<0||1/he<0;if(he=isNaN(he)?m:te(Math.abs(he),z),W&&(he=kct(he)),Ce&&+he==0&&P!=="+"&&(Ce=!1),xe=(Ce?P==="("?P:a:P==="-"||P==="("?"":P)+xe,pe=(V==="s"?qte[8+Wve/3]:"")+pe+(Ce&&P==="("?")":""),X){for(ve=-1,ge=he.length;++veke||ke>57){pe=(ke===46?i+he.slice(ve+1):he.slice(ve))+pe,he=he.slice(0,ve);break}}}R&&!I&&(he=e(he,1/0));var Se=xe.length+he.length+pe.length,je=Se>1)+xe+he+pe+je.slice(Se);break;default:he=je+xe+he+pe;break}return o(he)}return ie.toString=function(){return j+""},ie}function _(j,N){var C=g((j=Mk(j),j.type="f",j)),P=Math.max(-8,Math.min(8,Math.floor(aj(N)/3)))*3,A=Math.pow(10,-P),I=qte[8+P/3];return function(O){return C(A*O)+I}}return{format:g,formatPrefix:_}}var tI,rW,Gve;Act({thousands:",",grouping:[3],currency:["$",""]});function Act(t){return tI=Ect(t),rW=tI.format,Gve=tI.formatPrefix,tI}function Pct(t){return Math.max(0,-aj(Math.abs(t)))}function Ict(t,e){return Math.max(0,Math.max(-8,Math.min(8,Math.floor(aj(e)/3)))*3-aj(Math.abs(t)))}function Mct(t,e){return t=Math.abs(t),e=Math.abs(e)-t,Math.max(0,aj(e)-aj(t))+1}function Kve(t,e,r,n){var i=WU(t,e,r),o;switch(n=Mk(n??",f"),n.type){case"s":{var c=Math.max(Math.abs(t),Math.abs(e));return n.precision==null&&!isNaN(o=Ict(i,c))&&(n.precision=o),Gve(n,c)}case"":case"e":case"g":case"p":case"r":{n.precision==null&&!isNaN(o=Mct(i,Math.max(Math.abs(t),Math.abs(e))))&&(n.precision=o-(n.type==="e"));break}case"f":case"%":{n.precision==null&&!isNaN(o=Pct(i))&&(n.precision=o-(n.type==="%")*2);break}}return rW(n)}function Tx(t){var e=t.domain;return t.ticks=function(r){var n=e();return qU(n[0],n[n.length-1],r??10)},t.tickFormat=function(r,n){var i=e();return Kve(i[0],i[i.length-1],r??10,n)},t.nice=function(r){r==null&&(r=10);var n=e(),i=0,o=n.length-1,c=n[i],a=n[o],m,g,_=10;for(a0;){if(g=HU(c,a,r),g===m)return n[i]=c,n[o]=a,e(n);if(g>0)c=Math.floor(c/g)*g,a=Math.ceil(a/g)*g;else if(g<0)c=Math.ceil(c*g)/g,a=Math.floor(a*g)/g;else break;m=g}return t},t}function rR(){var t=eW();return t.copy=function(){return ZT(t,rR())},bh.apply(t,arguments),Tx(t)}function Zve(t){var e;function r(n){return n==null||isNaN(n=+n)?e:n}return r.invert=r,r.domain=r.range=function(n){return arguments.length?(t=Array.from(n,eR),r):t.slice()},r.unknown=function(n){return arguments.length?(e=n,r):e},r.copy=function(){return Zve(t).unknown(e)},t=arguments.length?Array.from(t,eR):[0,1],Tx(r)}function Yve(t,e){t=t.slice();var r=0,n=t.length-1,i=t[r],o=t[n],c;return oMath.pow(t,e)}function Fct(t){return t===Math.E?Math.log:t===10&&Math.log10||t===2&&Math.log2||(t=Math.log(t),e=>Math.log(e)/t)}function Gte(t){return(e,r)=>-t(-e,r)}function nW(t){const e=t(Hte,Wte),r=e.domain;let n=10,i,o;function c(){return i=Fct(n),o=Lct(n),r()[0]<0?(i=Gte(i),o=Gte(o),t(Oct,Rct)):t(Hte,Wte),e}return e.base=function(a){return arguments.length?(n=+a,c()):n},e.domain=function(a){return arguments.length?(r(a),c()):r()},e.ticks=a=>{const m=r();let g=m[0],_=m[m.length-1];const j=_0){for(;N<=C;++N)for(P=1;P_)break;O.push(A)}}else for(;N<=C;++N)for(P=n-1;P>=1;--P)if(A=N>0?P/o(-N):P*o(N),!(A_)break;O.push(A)}O.length*2{if(a==null&&(a=10),m==null&&(m=n===10?"s":","),typeof m!="function"&&(!(n%1)&&(m=Mk(m)).precision==null&&(m.trim=!0),m=rW(m)),a===1/0)return m;const g=Math.max(1,n*a/e.ticks().length);return _=>{let j=_/o(Math.round(i(_)));return j*nr(Yve(r(),{floor:a=>o(Math.floor(i(a))),ceil:a=>o(Math.ceil(i(a)))})),e}function Xve(){const t=nW(IL()).domain([1,10]);return t.copy=()=>ZT(t,Xve()).base(t.base()),bh.apply(t,arguments),t}function Kte(t){return function(e){return Math.sign(e)*Math.log1p(Math.abs(e/t))}}function Zte(t){return function(e){return Math.sign(e)*Math.expm1(Math.abs(e))*t}}function sW(t){var e=1,r=t(Kte(e),Zte(e));return r.constant=function(n){return arguments.length?t(Kte(e=+n),Zte(e)):e},Tx(r)}function Qve(){var t=sW(IL());return t.copy=function(){return ZT(t,Qve()).constant(t.constant())},bh.apply(t,arguments)}function Yte(t){return function(e){return e<0?-Math.pow(-e,t):Math.pow(e,t)}}function zct(t){return t<0?-Math.sqrt(-t):Math.sqrt(t)}function Bct(t){return t<0?-t*t:t*t}function iW(t){var e=t(iu,iu),r=1;function n(){return r===1?t(iu,iu):r===.5?t(zct,Bct):t(Yte(r),Yte(1/r))}return e.exponent=function(i){return arguments.length?(r=+i,n()):r},Tx(e)}function aW(){var t=iW(IL());return t.copy=function(){return ZT(t,aW()).exponent(t.exponent())},bh.apply(t,arguments),t}function $ct(){return aW.apply(null,arguments).exponent(.5)}function Xte(t){return Math.sign(t)*t*t}function Uct(t){return Math.sign(t)*Math.sqrt(Math.abs(t))}function Jve(){var t=eW(),e=[0,1],r=!1,n;function i(o){var c=Uct(t(o));return isNaN(c)?n:r?Math.round(c):c}return i.invert=function(o){return t.invert(Xte(o))},i.domain=function(o){return arguments.length?(t.domain(o),i):t.domain()},i.range=function(o){return arguments.length?(t.range((e=Array.from(o,eR)).map(Xte)),i):e.slice()},i.rangeRound=function(o){return i.range(o).round(!0)},i.round=function(o){return arguments.length?(r=!!o,i):r},i.clamp=function(o){return arguments.length?(t.clamp(o),i):t.clamp()},i.unknown=function(o){return arguments.length?(n=o,i):n},i.copy=function(){return Jve(t.domain(),e).round(r).clamp(t.clamp()).unknown(n)},bh.apply(i,arguments),Tx(i)}function e_e(){var t=[],e=[],r=[],n;function i(){var c=0,a=Math.max(1,e.length);for(r=new Array(a-1);++c0?r[a-1]:t[0],a=r?[n[r-1],e]:[n[g-1],n[g]]},c.unknown=function(m){return arguments.length&&(o=m),c},c.thresholds=function(){return n.slice()},c.copy=function(){return t_e().domain([t,e]).range(i).unknown(o)},bh.apply(Tx(c),arguments)}function r_e(){var t=[.5],e=[0,1],r,n=1;function i(o){return o!=null&&o<=o?e[GT(t,o,0,n)]:r}return i.domain=function(o){return arguments.length?(t=Array.from(o),n=Math.min(t.length,e.length-1),i):t.slice()},i.range=function(o){return arguments.length?(e=Array.from(o),n=Math.min(t.length,e.length-1),i):e.slice()},i.invertExtent=function(o){var c=e.indexOf(o);return[t[c-1],t[c]]},i.unknown=function(o){return arguments.length?(r=o,i):r},i.copy=function(){return r_e().domain(t).range(e).unknown(r)},bh.apply(i,arguments)}const fB=new Date,pB=new Date;function Pl(t,e,r,n){function i(o){return t(o=arguments.length===0?new Date:new Date(+o)),o}return i.floor=o=>(t(o=new Date(+o)),o),i.ceil=o=>(t(o=new Date(o-1)),e(o,1),t(o),o),i.round=o=>{const c=i(o),a=i.ceil(o);return o-c(e(o=new Date(+o),c==null?1:Math.floor(c)),o),i.range=(o,c,a)=>{const m=[];if(o=i.ceil(o),a=a==null?1:Math.floor(a),!(o0))return m;let g;do m.push(g=new Date(+o)),e(o,a),t(o);while(gPl(c=>{if(c>=c)for(;t(c),!o(c);)c.setTime(c-1)},(c,a)=>{if(c>=c)if(a<0)for(;++a<=0;)for(;e(c,-1),!o(c););else for(;--a>=0;)for(;e(c,1),!o(c););}),r&&(i.count=(o,c)=>(fB.setTime(+o),pB.setTime(+c),t(fB),t(pB),Math.floor(r(fB,pB))),i.every=o=>(o=Math.floor(o),!isFinite(o)||!(o>0)?null:o>1?i.filter(n?c=>n(c)%o===0:c=>i.count(0,c)%o===0):i)),i}const nR=Pl(()=>{},(t,e)=>{t.setTime(+t+e)},(t,e)=>e-t);nR.every=t=>(t=Math.floor(t),!isFinite(t)||!(t>0)?null:t>1?Pl(e=>{e.setTime(Math.floor(e/t)*t)},(e,r)=>{e.setTime(+e+r*t)},(e,r)=>(r-e)/t):nR);nR.range;const Pm=1e3,ah=Pm*60,Im=ah*60,Zm=Im*24,oW=Zm*7,Qte=Zm*30,mB=Zm*365,r_=Pl(t=>{t.setTime(t-t.getMilliseconds())},(t,e)=>{t.setTime(+t+e*Pm)},(t,e)=>(e-t)/Pm,t=>t.getUTCSeconds());r_.range;const lW=Pl(t=>{t.setTime(t-t.getMilliseconds()-t.getSeconds()*Pm)},(t,e)=>{t.setTime(+t+e*ah)},(t,e)=>(e-t)/ah,t=>t.getMinutes());lW.range;const cW=Pl(t=>{t.setUTCSeconds(0,0)},(t,e)=>{t.setTime(+t+e*ah)},(t,e)=>(e-t)/ah,t=>t.getUTCMinutes());cW.range;const uW=Pl(t=>{t.setTime(t-t.getMilliseconds()-t.getSeconds()*Pm-t.getMinutes()*ah)},(t,e)=>{t.setTime(+t+e*Im)},(t,e)=>(e-t)/Im,t=>t.getHours());uW.range;const dW=Pl(t=>{t.setUTCMinutes(0,0,0)},(t,e)=>{t.setTime(+t+e*Im)},(t,e)=>(e-t)/Im,t=>t.getUTCHours());dW.range;const YT=Pl(t=>t.setHours(0,0,0,0),(t,e)=>t.setDate(t.getDate()+e),(t,e)=>(e-t-(e.getTimezoneOffset()-t.getTimezoneOffset())*ah)/Zm,t=>t.getDate()-1);YT.range;const ML=Pl(t=>{t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCDate(t.getUTCDate()+e)},(t,e)=>(e-t)/Zm,t=>t.getUTCDate()-1);ML.range;const n_e=Pl(t=>{t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCDate(t.getUTCDate()+e)},(t,e)=>(e-t)/Zm,t=>Math.floor(t/Zm));n_e.range;function u0(t){return Pl(e=>{e.setDate(e.getDate()-(e.getDay()+7-t)%7),e.setHours(0,0,0,0)},(e,r)=>{e.setDate(e.getDate()+r*7)},(e,r)=>(r-e-(r.getTimezoneOffset()-e.getTimezoneOffset())*ah)/oW)}const OL=u0(0),sR=u0(1),Vct=u0(2),qct=u0(3),oj=u0(4),Hct=u0(5),Wct=u0(6);OL.range;sR.range;Vct.range;qct.range;oj.range;Hct.range;Wct.range;function d0(t){return Pl(e=>{e.setUTCDate(e.getUTCDate()-(e.getUTCDay()+7-t)%7),e.setUTCHours(0,0,0,0)},(e,r)=>{e.setUTCDate(e.getUTCDate()+r*7)},(e,r)=>(r-e)/oW)}const RL=d0(0),iR=d0(1),Gct=d0(2),Kct=d0(3),lj=d0(4),Zct=d0(5),Yct=d0(6);RL.range;iR.range;Gct.range;Kct.range;lj.range;Zct.range;Yct.range;const hW=Pl(t=>{t.setDate(1),t.setHours(0,0,0,0)},(t,e)=>{t.setMonth(t.getMonth()+e)},(t,e)=>e.getMonth()-t.getMonth()+(e.getFullYear()-t.getFullYear())*12,t=>t.getMonth());hW.range;const fW=Pl(t=>{t.setUTCDate(1),t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCMonth(t.getUTCMonth()+e)},(t,e)=>e.getUTCMonth()-t.getUTCMonth()+(e.getUTCFullYear()-t.getUTCFullYear())*12,t=>t.getUTCMonth());fW.range;const Ym=Pl(t=>{t.setMonth(0,1),t.setHours(0,0,0,0)},(t,e)=>{t.setFullYear(t.getFullYear()+e)},(t,e)=>e.getFullYear()-t.getFullYear(),t=>t.getFullYear());Ym.every=t=>!isFinite(t=Math.floor(t))||!(t>0)?null:Pl(e=>{e.setFullYear(Math.floor(e.getFullYear()/t)*t),e.setMonth(0,1),e.setHours(0,0,0,0)},(e,r)=>{e.setFullYear(e.getFullYear()+r*t)});Ym.range;const Xm=Pl(t=>{t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCFullYear(t.getUTCFullYear()+e)},(t,e)=>e.getUTCFullYear()-t.getUTCFullYear(),t=>t.getUTCFullYear());Xm.every=t=>!isFinite(t=Math.floor(t))||!(t>0)?null:Pl(e=>{e.setUTCFullYear(Math.floor(e.getUTCFullYear()/t)*t),e.setUTCMonth(0,1),e.setUTCHours(0,0,0,0)},(e,r)=>{e.setUTCFullYear(e.getUTCFullYear()+r*t)});Xm.range;function s_e(t,e,r,n,i,o){const c=[[r_,1,Pm],[r_,5,5*Pm],[r_,15,15*Pm],[r_,30,30*Pm],[o,1,ah],[o,5,5*ah],[o,15,15*ah],[o,30,30*ah],[i,1,Im],[i,3,3*Im],[i,6,6*Im],[i,12,12*Im],[n,1,Zm],[n,2,2*Zm],[r,1,oW],[e,1,Qte],[e,3,3*Qte],[t,1,mB]];function a(g,_,j){const N=_I).right(c,N);if(C===c.length)return t.every(WU(g/mB,_/mB,j));if(C===0)return nR.every(Math.max(WU(g,_,j),1));const[P,A]=c[N/c[C-1][2]53)return null;"w"in Pe||(Pe.w=1),"Z"in Pe?(jt=yB(NC(Pe.y,0,1)),$t=jt.getUTCDay(),jt=$t>4||$t===0?iR.ceil(jt):iR(jt),jt=ML.offset(jt,(Pe.V-1)*7),Pe.y=jt.getUTCFullYear(),Pe.m=jt.getUTCMonth(),Pe.d=jt.getUTCDate()+(Pe.w+6)%7):(jt=gB(NC(Pe.y,0,1)),$t=jt.getDay(),jt=$t>4||$t===0?sR.ceil(jt):sR(jt),jt=YT.offset(jt,(Pe.V-1)*7),Pe.y=jt.getFullYear(),Pe.m=jt.getMonth(),Pe.d=jt.getDate()+(Pe.w+6)%7)}else("W"in Pe||"U"in Pe)&&("w"in Pe||(Pe.w="u"in Pe?Pe.u%7:"W"in Pe?1:0),$t="Z"in Pe?yB(NC(Pe.y,0,1)).getUTCDay():gB(NC(Pe.y,0,1)).getDay(),Pe.m=0,Pe.d="W"in Pe?(Pe.w+6)%7+Pe.W*7-($t+5)%7:Pe.w+Pe.U*7-($t+6)%7);return"Z"in Pe?(Pe.H+=Pe.Z/100|0,Pe.M+=Pe.Z%100,yB(Pe)):gB(Pe)}}function te(Oe,Ie,Be,Pe){for(var ut=0,jt=Ie.length,$t=Be.length,Ht,Lt;ut=$t)return-1;if(Ht=Ie.charCodeAt(ut++),Ht===37){if(Ht=Ie.charAt(ut++),Lt=V[Ht in Jte?Ie.charAt(ut++):Ht],!Lt||(Pe=Lt(Oe,Be,Pe))<0)return-1}else if(Ht!=Be.charCodeAt(Pe++))return-1}return Pe}function X(Oe,Ie,Be){var Pe=g.exec(Ie.slice(Be));return Pe?(Oe.p=_.get(Pe[0].toLowerCase()),Be+Pe[0].length):-1}function ie(Oe,Ie,Be){var Pe=C.exec(Ie.slice(Be));return Pe?(Oe.w=P.get(Pe[0].toLowerCase()),Be+Pe[0].length):-1}function he(Oe,Ie,Be){var Pe=j.exec(Ie.slice(Be));return Pe?(Oe.w=N.get(Pe[0].toLowerCase()),Be+Pe[0].length):-1}function xe(Oe,Ie,Be){var Pe=O.exec(Ie.slice(Be));return Pe?(Oe.m=R.get(Pe[0].toLowerCase()),Be+Pe[0].length):-1}function pe(Oe,Ie,Be){var Pe=A.exec(Ie.slice(Be));return Pe?(Oe.m=I.get(Pe[0].toLowerCase()),Be+Pe[0].length):-1}function ve(Oe,Ie,Be){return te(Oe,e,Ie,Be)}function ge(Oe,Ie,Be){return te(Oe,r,Ie,Be)}function ke(Oe,Ie,Be){return te(Oe,n,Ie,Be)}function Ce(Oe){return c[Oe.getDay()]}function Se(Oe){return o[Oe.getDay()]}function je(Oe){return m[Oe.getMonth()]}function et(Oe){return a[Oe.getMonth()]}function bt(Oe){return i[+(Oe.getHours()>=12)]}function _e(Oe){return 1+~~(Oe.getMonth()/3)}function Ye(Oe){return c[Oe.getUTCDay()]}function pt(Oe){return o[Oe.getUTCDay()]}function nt(Oe){return m[Oe.getUTCMonth()]}function Qt(Oe){return a[Oe.getUTCMonth()]}function gt(Oe){return i[+(Oe.getUTCHours()>=12)]}function Me(Oe){return 1+~~(Oe.getUTCMonth()/3)}return{format:function(Oe){var Ie=K(Oe+="",z);return Ie.toString=function(){return Oe},Ie},parse:function(Oe){var Ie=Q(Oe+="",!1);return Ie.toString=function(){return Oe},Ie},utcFormat:function(Oe){var Ie=K(Oe+="",W);return Ie.toString=function(){return Oe},Ie},utcParse:function(Oe){var Ie=Q(Oe+="",!0);return Ie.toString=function(){return Oe},Ie}}}var Jte={"-":"",_:" ",0:"0"},Jl=/^\s*\d+/,rut=/^%/,nut=/[\\^$*+?|[\]().{}]/g;function fa(t,e,r){var n=t<0?"-":"",i=(n?-t:t)+"",o=i.length;return n+(o[e.toLowerCase(),r]))}function iut(t,e,r){var n=Jl.exec(e.slice(r,r+1));return n?(t.w=+n[0],r+n[0].length):-1}function aut(t,e,r){var n=Jl.exec(e.slice(r,r+1));return n?(t.u=+n[0],r+n[0].length):-1}function out(t,e,r){var n=Jl.exec(e.slice(r,r+2));return n?(t.U=+n[0],r+n[0].length):-1}function lut(t,e,r){var n=Jl.exec(e.slice(r,r+2));return n?(t.V=+n[0],r+n[0].length):-1}function cut(t,e,r){var n=Jl.exec(e.slice(r,r+2));return n?(t.W=+n[0],r+n[0].length):-1}function ere(t,e,r){var n=Jl.exec(e.slice(r,r+4));return n?(t.y=+n[0],r+n[0].length):-1}function tre(t,e,r){var n=Jl.exec(e.slice(r,r+2));return n?(t.y=+n[0]+(+n[0]>68?1900:2e3),r+n[0].length):-1}function uut(t,e,r){var n=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(e.slice(r,r+6));return n?(t.Z=n[1]?0:-(n[2]+(n[3]||"00")),r+n[0].length):-1}function dut(t,e,r){var n=Jl.exec(e.slice(r,r+1));return n?(t.q=n[0]*3-3,r+n[0].length):-1}function hut(t,e,r){var n=Jl.exec(e.slice(r,r+2));return n?(t.m=n[0]-1,r+n[0].length):-1}function rre(t,e,r){var n=Jl.exec(e.slice(r,r+2));return n?(t.d=+n[0],r+n[0].length):-1}function fut(t,e,r){var n=Jl.exec(e.slice(r,r+3));return n?(t.m=0,t.d=+n[0],r+n[0].length):-1}function nre(t,e,r){var n=Jl.exec(e.slice(r,r+2));return n?(t.H=+n[0],r+n[0].length):-1}function put(t,e,r){var n=Jl.exec(e.slice(r,r+2));return n?(t.M=+n[0],r+n[0].length):-1}function mut(t,e,r){var n=Jl.exec(e.slice(r,r+2));return n?(t.S=+n[0],r+n[0].length):-1}function gut(t,e,r){var n=Jl.exec(e.slice(r,r+3));return n?(t.L=+n[0],r+n[0].length):-1}function yut(t,e,r){var n=Jl.exec(e.slice(r,r+6));return n?(t.L=Math.floor(n[0]/1e3),r+n[0].length):-1}function xut(t,e,r){var n=rut.exec(e.slice(r,r+1));return n?r+n[0].length:-1}function vut(t,e,r){var n=Jl.exec(e.slice(r));return n?(t.Q=+n[0],r+n[0].length):-1}function _ut(t,e,r){var n=Jl.exec(e.slice(r));return n?(t.s=+n[0],r+n[0].length):-1}function sre(t,e){return fa(t.getDate(),e,2)}function but(t,e){return fa(t.getHours(),e,2)}function wut(t,e){return fa(t.getHours()%12||12,e,2)}function jut(t,e){return fa(1+YT.count(Ym(t),t),e,3)}function i_e(t,e){return fa(t.getMilliseconds(),e,3)}function Sut(t,e){return i_e(t,e)+"000"}function Nut(t,e){return fa(t.getMonth()+1,e,2)}function Cut(t,e){return fa(t.getMinutes(),e,2)}function kut(t,e){return fa(t.getSeconds(),e,2)}function Tut(t){var e=t.getDay();return e===0?7:e}function Eut(t,e){return fa(OL.count(Ym(t)-1,t),e,2)}function a_e(t){var e=t.getDay();return e>=4||e===0?oj(t):oj.ceil(t)}function Aut(t,e){return t=a_e(t),fa(oj.count(Ym(t),t)+(Ym(t).getDay()===4),e,2)}function Put(t){return t.getDay()}function Iut(t,e){return fa(sR.count(Ym(t)-1,t),e,2)}function Mut(t,e){return fa(t.getFullYear()%100,e,2)}function Out(t,e){return t=a_e(t),fa(t.getFullYear()%100,e,2)}function Rut(t,e){return fa(t.getFullYear()%1e4,e,4)}function Dut(t,e){var r=t.getDay();return t=r>=4||r===0?oj(t):oj.ceil(t),fa(t.getFullYear()%1e4,e,4)}function Lut(t){var e=t.getTimezoneOffset();return(e>0?"-":(e*=-1,"+"))+fa(e/60|0,"0",2)+fa(e%60,"0",2)}function ire(t,e){return fa(t.getUTCDate(),e,2)}function Fut(t,e){return fa(t.getUTCHours(),e,2)}function zut(t,e){return fa(t.getUTCHours()%12||12,e,2)}function But(t,e){return fa(1+ML.count(Xm(t),t),e,3)}function o_e(t,e){return fa(t.getUTCMilliseconds(),e,3)}function $ut(t,e){return o_e(t,e)+"000"}function Uut(t,e){return fa(t.getUTCMonth()+1,e,2)}function Vut(t,e){return fa(t.getUTCMinutes(),e,2)}function qut(t,e){return fa(t.getUTCSeconds(),e,2)}function Hut(t){var e=t.getUTCDay();return e===0?7:e}function Wut(t,e){return fa(RL.count(Xm(t)-1,t),e,2)}function l_e(t){var e=t.getUTCDay();return e>=4||e===0?lj(t):lj.ceil(t)}function Gut(t,e){return t=l_e(t),fa(lj.count(Xm(t),t)+(Xm(t).getUTCDay()===4),e,2)}function Kut(t){return t.getUTCDay()}function Zut(t,e){return fa(iR.count(Xm(t)-1,t),e,2)}function Yut(t,e){return fa(t.getUTCFullYear()%100,e,2)}function Xut(t,e){return t=l_e(t),fa(t.getUTCFullYear()%100,e,2)}function Qut(t,e){return fa(t.getUTCFullYear()%1e4,e,4)}function Jut(t,e){var r=t.getUTCDay();return t=r>=4||r===0?lj(t):lj.ceil(t),fa(t.getUTCFullYear()%1e4,e,4)}function edt(){return"+0000"}function are(){return"%"}function ore(t){return+t}function lre(t){return Math.floor(+t/1e3)}var yw,c_e,u_e;tdt({dateTime:"%x, %X",date:"%-m/%-d/%Y",time:"%-I:%M:%S %p",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});function tdt(t){return yw=tut(t),c_e=yw.format,yw.parse,u_e=yw.utcFormat,yw.utcParse,yw}function rdt(t){return new Date(t)}function ndt(t){return t instanceof Date?+t:+new Date(+t)}function pW(t,e,r,n,i,o,c,a,m,g){var _=eW(),j=_.invert,N=_.domain,C=g(".%L"),P=g(":%S"),A=g("%I:%M"),I=g("%I %p"),O=g("%a %d"),R=g("%b %d"),z=g("%B"),W=g("%Y");function V(K){return(m(K)e(i/(t.length-1)))},r.quantiles=function(n){return Array.from({length:n+1},(i,o)=>Wlt(t,o/n))},r.copy=function(){return p_e(e).domain(t)},ug.apply(r,arguments)}function LL(){var t=0,e=.5,r=1,n=1,i,o,c,a,m,g=iu,_,j=!1,N;function C(A){return isNaN(A=+A)?N:(A=.5+((A=+_(A))-o)*(n*Ae}var x_e=udt,ddt=FL,hdt=x_e,fdt=tS;function pdt(t){return t&&t.length?ddt(t,fdt,hdt):void 0}var mdt=pdt;const zL=sa(mdt);function gdt(t,e){return tt.e^o.s<0?1:-1;for(n=o.d.length,i=t.d.length,e=0,r=nt.d[e]^o.s<0?1:-1;return n===i?0:n>i^o.s<0?1:-1};Yn.decimalPlaces=Yn.dp=function(){var t=this,e=t.d.length-1,r=(e-t.e)*no;if(e=t.d[e],e)for(;e%10==0;e/=10)r--;return r<0?0:r};Yn.dividedBy=Yn.div=function(t){return Fm(this,new this.constructor(t))};Yn.dividedToIntegerBy=Yn.idiv=function(t){var e=this,r=e.constructor;return Da(Fm(e,new r(t),0,1),r.precision)};Yn.equals=Yn.eq=function(t){return!this.cmp(t)};Yn.exponent=function(){return ml(this)};Yn.greaterThan=Yn.gt=function(t){return this.cmp(t)>0};Yn.greaterThanOrEqualTo=Yn.gte=function(t){return this.cmp(t)>=0};Yn.isInteger=Yn.isint=function(){return this.e>this.d.length-2};Yn.isNegative=Yn.isneg=function(){return this.s<0};Yn.isPositive=Yn.ispos=function(){return this.s>0};Yn.isZero=function(){return this.s===0};Yn.lessThan=Yn.lt=function(t){return this.cmp(t)<0};Yn.lessThanOrEqualTo=Yn.lte=function(t){return this.cmp(t)<1};Yn.logarithm=Yn.log=function(t){var e,r=this,n=r.constructor,i=n.precision,o=i+5;if(t===void 0)t=new n(10);else if(t=new n(t),t.s<1||t.eq(pd))throw Error(yh+"NaN");if(r.s<1)throw Error(yh+(r.s?"NaN":"-Infinity"));return r.eq(pd)?new n(0):(mo=!1,e=Fm(Ok(r,o),Ok(t,o),o),mo=!0,Da(e,i))};Yn.minus=Yn.sub=function(t){var e=this;return t=new e.constructor(t),e.s==t.s?j_e(e,t):b_e(e,(t.s=-t.s,t))};Yn.modulo=Yn.mod=function(t){var e,r=this,n=r.constructor,i=n.precision;if(t=new n(t),!t.s)throw Error(yh+"NaN");return r.s?(mo=!1,e=Fm(r,t,0,1).times(t),mo=!0,r.minus(e)):Da(new n(r),i)};Yn.naturalExponential=Yn.exp=function(){return w_e(this)};Yn.naturalLogarithm=Yn.ln=function(){return Ok(this)};Yn.negated=Yn.neg=function(){var t=new this.constructor(this);return t.s=-t.s||0,t};Yn.plus=Yn.add=function(t){var e=this;return t=new e.constructor(t),e.s==t.s?b_e(e,t):j_e(e,(t.s=-t.s,t))};Yn.precision=Yn.sd=function(t){var e,r,n,i=this;if(t!==void 0&&t!==!!t&&t!==1&&t!==0)throw Error(j_+t);if(e=ml(i)+1,n=i.d.length-1,r=n*no+1,n=i.d[n],n){for(;n%10==0;n/=10)r--;for(n=i.d[0];n>=10;n/=10)r++}return t&&e>r?e:r};Yn.squareRoot=Yn.sqrt=function(){var t,e,r,n,i,o,c,a=this,m=a.constructor;if(a.s<1){if(!a.s)return new m(0);throw Error(yh+"NaN")}for(t=ml(a),mo=!1,i=Math.sqrt(+a),i==0||i==1/0?(e=fp(a.d),(e.length+t)%2==0&&(e+="0"),i=Math.sqrt(e),t=iS((t+1)/2)-(t<0||t%2),i==1/0?e="5e"+t:(e=i.toExponential(),e=e.slice(0,e.indexOf("e")+1)+t),n=new m(e)):n=new m(i.toString()),r=m.precision,i=c=r+3;;)if(o=n,n=o.plus(Fm(a,o,c+2)).times(.5),fp(o.d).slice(0,c)===(e=fp(n.d)).slice(0,c)){if(e=e.slice(c-3,c+1),i==c&&e=="4999"){if(Da(o,r+1,0),o.times(o).eq(a)){n=o;break}}else if(e!="9999")break;c+=4}return mo=!0,Da(n,r)};Yn.times=Yn.mul=function(t){var e,r,n,i,o,c,a,m,g,_=this,j=_.constructor,N=_.d,C=(t=new j(t)).d;if(!_.s||!t.s)return new j(0);for(t.s*=_.s,r=_.e+t.e,m=N.length,g=C.length,m=0;){for(e=0,i=m+n;i>n;)a=o[i]+C[n]*N[i-n-1]+e,o[i--]=a%Bl|0,e=a/Bl|0;o[i]=(o[i]+e)%Bl|0}for(;!o[--c];)o.pop();return e?++r:o.shift(),t.d=o,t.e=r,mo?Da(t,j.precision):t};Yn.toDecimalPlaces=Yn.todp=function(t,e){var r=this,n=r.constructor;return r=new n(r),t===void 0?r:(Ap(t,0,sS),e===void 0?e=n.rounding:Ap(e,0,8),Da(r,t+ml(r)+1,e))};Yn.toExponential=function(t,e){var r,n=this,i=n.constructor;return t===void 0?r=Z_(n,!0):(Ap(t,0,sS),e===void 0?e=i.rounding:Ap(e,0,8),n=Da(new i(n),t+1,e),r=Z_(n,!0,t+1)),r};Yn.toFixed=function(t,e){var r,n,i=this,o=i.constructor;return t===void 0?Z_(i):(Ap(t,0,sS),e===void 0?e=o.rounding:Ap(e,0,8),n=Da(new o(i),t+ml(i)+1,e),r=Z_(n.abs(),!1,t+ml(n)+1),i.isneg()&&!i.isZero()?"-"+r:r)};Yn.toInteger=Yn.toint=function(){var t=this,e=t.constructor;return Da(new e(t),ml(t)+1,e.rounding)};Yn.toNumber=function(){return+this};Yn.toPower=Yn.pow=function(t){var e,r,n,i,o,c,a=this,m=a.constructor,g=12,_=+(t=new m(t));if(!t.s)return new m(pd);if(a=new m(a),!a.s){if(t.s<1)throw Error(yh+"Infinity");return a}if(a.eq(pd))return a;if(n=m.precision,t.eq(pd))return Da(a,n);if(e=t.e,r=t.d.length-1,c=e>=r,o=a.s,c){if((r=_<0?-_:_)<=__e){for(i=new m(pd),e=Math.ceil(n/no+4),mo=!1;r%2&&(i=i.times(a),dre(i.d,e)),r=iS(r/2),r!==0;)a=a.times(a),dre(a.d,e);return mo=!0,t.s<0?new m(pd).div(i):Da(i,n)}}else if(o<0)throw Error(yh+"NaN");return o=o<0&&t.d[Math.max(e,r)]&1?-1:1,a.s=1,mo=!1,i=t.times(Ok(a,n+g)),mo=!0,i=w_e(i),i.s=o,i};Yn.toPrecision=function(t,e){var r,n,i=this,o=i.constructor;return t===void 0?(r=ml(i),n=Z_(i,r<=o.toExpNeg||r>=o.toExpPos)):(Ap(t,1,sS),e===void 0?e=o.rounding:Ap(e,0,8),i=Da(new o(i),t,e),r=ml(i),n=Z_(i,t<=r||r<=o.toExpNeg,t)),n};Yn.toSignificantDigits=Yn.tosd=function(t,e){var r=this,n=r.constructor;return t===void 0?(t=n.precision,e=n.rounding):(Ap(t,1,sS),e===void 0?e=n.rounding:Ap(e,0,8)),Da(new n(r),t,e)};Yn.toString=Yn.valueOf=Yn.val=Yn.toJSON=Yn[Symbol.for("nodejs.util.inspect.custom")]=function(){var t=this,e=ml(t),r=t.constructor;return Z_(t,e<=r.toExpNeg||e>=r.toExpPos)};function b_e(t,e){var r,n,i,o,c,a,m,g,_=t.constructor,j=_.precision;if(!t.s||!e.s)return e.s||(e=new _(t)),mo?Da(e,j):e;if(m=t.d,g=e.d,c=t.e,i=e.e,m=m.slice(),o=c-i,o){for(o<0?(n=m,o=-o,a=g.length):(n=g,i=c,a=m.length),c=Math.ceil(j/no),a=c>a?c+1:a+1,o>a&&(o=a,n.length=1),n.reverse();o--;)n.push(0);n.reverse()}for(a=m.length,o=g.length,a-o<0&&(o=a,n=g,g=m,m=n),r=0;o;)r=(m[--o]=m[o]+g[o]+r)/Bl|0,m[o]%=Bl;for(r&&(m.unshift(r),++i),a=m.length;m[--a]==0;)m.pop();return e.d=m,e.e=i,mo?Da(e,j):e}function Ap(t,e,r){if(t!==~~t||tr)throw Error(j_+t)}function fp(t){var e,r,n,i=t.length-1,o="",c=t[0];if(i>0){for(o+=c,e=1;ec?1:-1;else for(a=m=0;ai[a]?1:-1;break}return m}function r(n,i,o){for(var c=0;o--;)n[o]-=c,c=n[o]1;)n.shift()}return function(n,i,o,c){var a,m,g,_,j,N,C,P,A,I,O,R,z,W,V,K,Q,te,X=n.constructor,ie=n.s==i.s?1:-1,he=n.d,xe=i.d;if(!n.s)return new X(n);if(!i.s)throw Error(yh+"Division by zero");for(m=n.e-i.e,Q=xe.length,V=he.length,C=new X(ie),P=C.d=[],g=0;xe[g]==(he[g]||0);)++g;if(xe[g]>(he[g]||0)&&--m,o==null?R=o=X.precision:c?R=o+(ml(n)-ml(i))+1:R=o,R<0)return new X(0);if(R=R/no+2|0,g=0,Q==1)for(_=0,xe=xe[0],R++;(g1&&(xe=t(xe,_),he=t(he,_),Q=xe.length,V=he.length),W=Q,A=he.slice(0,Q),I=A.length;I=Bl/2&&++K;do _=0,a=e(xe,A,Q,I),a<0?(O=A[0],Q!=I&&(O=O*Bl+(A[1]||0)),_=O/K|0,_>1?(_>=Bl&&(_=Bl-1),j=t(xe,_),N=j.length,I=A.length,a=e(j,A,N,I),a==1&&(_--,r(j,Q16)throw Error(yW+ml(t));if(!t.s)return new _(pd);for(mo=!1,a=j,c=new _(.03125);t.abs().gte(.1);)t=t.times(c),g+=5;for(n=Math.log(Fv(2,g))/Math.LN10*2+5|0,a+=n,r=i=o=new _(pd),_.precision=a;;){if(i=Da(i.times(t),a),r=r.times(++m),c=o.plus(Fm(i,r,a)),fp(c.d).slice(0,a)===fp(o.d).slice(0,a)){for(;g--;)o=Da(o.times(o),a);return _.precision=j,e==null?(mo=!0,Da(o,j)):o}o=c}}function ml(t){for(var e=t.e*no,r=t.d[0];r>=10;r/=10)e++;return e}function xB(t,e,r){if(e>t.LN10.sd())throw mo=!0,r&&(t.precision=r),Error(yh+"LN10 precision limit exceeded");return Da(new t(t.LN10),e)}function dy(t){for(var e="";t--;)e+="0";return e}function Ok(t,e){var r,n,i,o,c,a,m,g,_,j=1,N=10,C=t,P=C.d,A=C.constructor,I=A.precision;if(C.s<1)throw Error(yh+(C.s?"NaN":"-Infinity"));if(C.eq(pd))return new A(0);if(e==null?(mo=!1,g=I):g=e,C.eq(10))return e==null&&(mo=!0),xB(A,g);if(g+=N,A.precision=g,r=fp(P),n=r.charAt(0),o=ml(C),Math.abs(o)<15e14){for(;n<7&&n!=1||n==1&&r.charAt(1)>3;)C=C.times(t),r=fp(C.d),n=r.charAt(0),j++;o=ml(C),n>1?(C=new A("0."+r),o++):C=new A(n+"."+r.slice(1))}else return m=xB(A,g+2,I).times(o+""),C=Ok(new A(n+"."+r.slice(1)),g-N).plus(m),A.precision=I,e==null?(mo=!0,Da(C,I)):C;for(a=c=C=Fm(C.minus(pd),C.plus(pd),g),_=Da(C.times(C),g),i=3;;){if(c=Da(c.times(_),g),m=a.plus(Fm(c,new A(i),g)),fp(m.d).slice(0,g)===fp(a.d).slice(0,g))return a=a.times(2),o!==0&&(a=a.plus(xB(A,g+2,I).times(o+""))),a=Fm(a,new A(j),g),A.precision=I,e==null?(mo=!0,Da(a,I)):a;a=m,i+=2}}function ure(t,e){var r,n,i;for((r=e.indexOf("."))>-1&&(e=e.replace(".","")),(n=e.search(/e/i))>0?(r<0&&(r=n),r+=+e.slice(n+1),e=e.substring(0,n)):r<0&&(r=e.length),n=0;e.charCodeAt(n)===48;)++n;for(i=e.length;e.charCodeAt(i-1)===48;)--i;if(e=e.slice(n,i),e){if(i-=n,r=r-n-1,t.e=iS(r/no),t.d=[],n=(r+1)%no,r<0&&(n+=no),naR||t.e<-aR))throw Error(yW+r)}else t.s=0,t.e=0,t.d=[0];return t}function Da(t,e,r){var n,i,o,c,a,m,g,_,j=t.d;for(c=1,o=j[0];o>=10;o/=10)c++;if(n=e-c,n<0)n+=no,i=e,g=j[_=0];else{if(_=Math.ceil((n+1)/no),o=j.length,_>=o)return t;for(g=o=j[_],c=1;o>=10;o/=10)c++;n%=no,i=n-no+c}if(r!==void 0&&(o=Fv(10,c-i-1),a=g/o%10|0,m=e<0||j[_+1]!==void 0||g%o,m=r<4?(a||m)&&(r==0||r==(t.s<0?3:2)):a>5||a==5&&(r==4||m||r==6&&(n>0?i>0?g/Fv(10,c-i):0:j[_-1])%10&1||r==(t.s<0?8:7))),e<1||!j[0])return m?(o=ml(t),j.length=1,e=e-o-1,j[0]=Fv(10,(no-e%no)%no),t.e=iS(-e/no)||0):(j.length=1,j[0]=t.e=t.s=0),t;if(n==0?(j.length=_,o=1,_--):(j.length=_+1,o=Fv(10,no-n),j[_]=i>0?(g/Fv(10,c-i)%Fv(10,i)|0)*o:0),m)for(;;)if(_==0){(j[0]+=o)==Bl&&(j[0]=1,++t.e);break}else{if(j[_]+=o,j[_]!=Bl)break;j[_--]=0,o=1}for(n=j.length;j[--n]===0;)j.pop();if(mo&&(t.e>aR||t.e<-aR))throw Error(yW+ml(t));return t}function j_e(t,e){var r,n,i,o,c,a,m,g,_,j,N=t.constructor,C=N.precision;if(!t.s||!e.s)return e.s?e.s=-e.s:e=new N(t),mo?Da(e,C):e;if(m=t.d,j=e.d,n=e.e,g=t.e,m=m.slice(),c=g-n,c){for(_=c<0,_?(r=m,c=-c,a=j.length):(r=j,n=g,a=m.length),i=Math.max(Math.ceil(C/no),a)+2,c>i&&(c=i,r.length=1),r.reverse(),i=c;i--;)r.push(0);r.reverse()}else{for(i=m.length,a=j.length,_=i0;--i)m[a++]=0;for(i=j.length;i>c;){if(m[--i]0?o=o.charAt(0)+"."+o.slice(1)+dy(n):c>1&&(o=o.charAt(0)+"."+o.slice(1)),o=o+(i<0?"e":"e+")+i):i<0?(o="0."+dy(-i-1)+o,r&&(n=r-c)>0&&(o+=dy(n))):i>=c?(o+=dy(i+1-c),r&&(n=r-i-1)>0&&(o=o+"."+dy(n))):((n=i+1)0&&(i+1===c&&(o+="."),o+=dy(n))),t.s<0?"-"+o:o}function dre(t,e){if(t.length>e)return t.length=e,!0}function S_e(t){var e,r,n;function i(o){var c=this;if(!(c instanceof i))return new i(o);if(c.constructor=i,o instanceof i){c.s=o.s,c.e=o.e,c.d=(o=o.d)?o.slice():o;return}if(typeof o=="number"){if(o*0!==0)throw Error(j_+o);if(o>0)c.s=1;else if(o<0)o=-o,c.s=-1;else{c.s=0,c.e=0,c.d=[0];return}if(o===~~o&&o<1e7){c.e=0,c.d=[o];return}return ure(c,o.toString())}else if(typeof o!="string")throw Error(j_+o);if(o.charCodeAt(0)===45?(o=o.slice(1),c.s=-1):c.s=1,Ldt.test(o))ure(c,o);else throw Error(j_+o)}if(i.prototype=Yn,i.ROUND_UP=0,i.ROUND_DOWN=1,i.ROUND_CEIL=2,i.ROUND_FLOOR=3,i.ROUND_HALF_UP=4,i.ROUND_HALF_DOWN=5,i.ROUND_HALF_EVEN=6,i.ROUND_HALF_CEIL=7,i.ROUND_HALF_FLOOR=8,i.clone=S_e,i.config=i.set=Fdt,t===void 0&&(t={}),t)for(n=["precision","rounding","toExpNeg","toExpPos","LN10"],e=0;e=i[e+1]&&n<=i[e+2])this[r]=n;else throw Error(j_+r+": "+n);if((n=t[r="LN10"])!==void 0)if(n==Math.LN10)this[r]=new this(n);else throw Error(j_+r+": "+n);return this}var xW=S_e(Ddt);pd=new xW(1);const Pa=xW;function zdt(t){return Vdt(t)||Udt(t)||$dt(t)||Bdt()}function Bdt(){throw new TypeError(`Invalid attempt to spread non-iterable instance. In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function $dt(t,e){if(t){if(typeof t=="string")return XU(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set")return Array.from(t);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return XU(t,e)}}function Udt(t){if(typeof Symbol<"u"&&Symbol.iterator in Object(t))return Array.from(t)}function Vdt(t){if(Array.isArray(t))return XU(t)}function XU(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r=e?r.apply(void 0,i):t(e-c,hre(function(){for(var a=arguments.length,m=new Array(a),g=0;gt.length)&&(e=t.length);for(var r=0,n=new Array(e);r"u"||!(Symbol.iterator in Object(t)))){var r=[],n=!0,i=!1,o=void 0;try{for(var c=t[Symbol.iterator](),a;!(n=(a=c.next()).done)&&(r.push(a.value),!(e&&r.length===e));n=!0);}catch(m){i=!0,o=m}finally{try{!n&&c.return!=null&&c.return()}finally{if(i)throw o}}return r}}function sht(t){if(Array.isArray(t))return t}function E_e(t){var e=Rk(t,2),r=e[0],n=e[1],i=r,o=n;return r>n&&(i=n,o=r),[i,o]}function A_e(t,e,r){if(t.lte(0))return new Pa(0);var n=VL.getDigitCount(t.toNumber()),i=new Pa(10).pow(n),o=t.div(i),c=n!==1?.05:.1,a=new Pa(Math.ceil(o.div(c).toNumber())).add(r).mul(c),m=a.mul(i);return e?m:new Pa(Math.ceil(m))}function iht(t,e,r){var n=1,i=new Pa(t);if(!i.isint()&&r){var o=Math.abs(t);o<1?(n=new Pa(10).pow(VL.getDigitCount(t)-1),i=new Pa(Math.floor(i.div(n).toNumber())).mul(n)):o>1&&(i=new Pa(Math.floor(t)))}else t===0?i=new Pa(Math.floor((e-1)/2)):r||(i=new Pa(Math.floor(t)));var c=Math.floor((e-1)/2),a=Gdt(Wdt(function(m){return i.add(new Pa(m-c).mul(n)).toNumber()}),QU);return a(0,e)}function P_e(t,e,r,n){var i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:0;if(!Number.isFinite((e-t)/(r-1)))return{step:new Pa(0),tickMin:new Pa(0),tickMax:new Pa(0)};var o=A_e(new Pa(e).sub(t).div(r-1),n,i),c;t<=0&&e>=0?c=new Pa(0):(c=new Pa(t).add(e).div(2),c=c.sub(new Pa(c).mod(o)));var a=Math.ceil(c.sub(t).div(o).toNumber()),m=Math.ceil(new Pa(e).sub(c).div(o).toNumber()),g=a+m+1;return g>r?P_e(t,e,r,n,i+1):(g0?m+(r-g):m,a=e>0?a:a+(r-g)),{step:o,tickMin:c.sub(new Pa(a).mul(o)),tickMax:c.add(new Pa(m).mul(o))})}function aht(t){var e=Rk(t,2),r=e[0],n=e[1],i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:6,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,c=Math.max(i,2),a=E_e([r,n]),m=Rk(a,2),g=m[0],_=m[1];if(g===-1/0||_===1/0){var j=_===1/0?[g].concat(eV(QU(0,i-1).map(function(){return 1/0}))):[].concat(eV(QU(0,i-1).map(function(){return-1/0})),[_]);return r>n?JU(j):j}if(g===_)return iht(g,i,o);var N=P_e(g,_,c,o),C=N.step,P=N.tickMin,A=N.tickMax,I=VL.rangeStep(P,A.add(new Pa(.1).mul(C)),C);return r>n?JU(I):I}function oht(t,e){var r=Rk(t,2),n=r[0],i=r[1],o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,c=E_e([n,i]),a=Rk(c,2),m=a[0],g=a[1];if(m===-1/0||g===1/0)return[n,i];if(m===g)return[m];var _=Math.max(e,2),j=A_e(new Pa(g).sub(m).div(_-1),o,0),N=[].concat(eV(VL.rangeStep(new Pa(m),new Pa(g).sub(new Pa(.99).mul(j)),j)),[g]);return n>i?JU(N):N}var lht=k_e(aht),cht=k_e(oht),uht="Invariant failed";function Y_(t,e){throw new Error(uht)}var dht=["offset","layout","width","dataKey","data","dataPointFormatter","xAxis","yAxis"];function cj(t){"@babel/helpers - typeof";return cj=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},cj(t)}function oR(){return oR=Object.assign?Object.assign.bind():function(t){for(var e=1;et.length)&&(e=t.length);for(var r=0,n=new Array(e);r=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function xht(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}function vht(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function _ht(t,e){for(var r=0;rt.length)&&(e=t.length);for(var r=0,n=new Array(e);r1&&arguments[1]!==void 0?arguments[1]:[],i=arguments.length>2?arguments[2]:void 0,o=arguments.length>3?arguments[3]:void 0,c=-1,a=(r=n==null?void 0:n.length)!==null&&r!==void 0?r:0;if(a<=1)return 0;if(o&&o.axisType==="angleAxis"&&Math.abs(Math.abs(o.range[1]-o.range[0])-360)<=1e-6)for(var m=o.range,g=0;g0?i[g-1].coordinate:i[a-1].coordinate,j=i[g].coordinate,N=g>=a-1?i[0].coordinate:i[g+1].coordinate,C=void 0;if(nu(j-_)!==nu(N-j)){var P=[];if(nu(N-j)===nu(m[1]-m[0])){C=N;var A=j+m[1]-m[0];P[0]=Math.min(A,(A+_)/2),P[1]=Math.max(A,(A+_)/2)}else{C=_;var I=N+m[1]-m[0];P[0]=Math.min(j,(I+j)/2),P[1]=Math.max(j,(I+j)/2)}var O=[Math.min(j,(C+j)/2),Math.max(j,(C+j)/2)];if(e>O[0]&&e<=O[1]||e>=P[0]&&e<=P[1]){c=i[g].index;break}}else{var R=Math.min(_,N),z=Math.max(_,N);if(e>(R+j)/2&&e<=(z+j)/2){c=i[g].index;break}}}else for(var W=0;W0&&W(n[W].coordinate+n[W-1].coordinate)/2&&e<=(n[W].coordinate+n[W+1].coordinate)/2||W===a-1&&e>(n[W].coordinate+n[W-1].coordinate)/2){c=n[W].index;break}return c},vW=function(e){var r,n=e,i=n.type.displayName,o=(r=e.type)!==null&&r!==void 0&&r.defaultProps?Io(Io({},e.type.defaultProps),e.props):e.props,c=o.stroke,a=o.fill,m;switch(i){case"Line":m=c;break;case"Area":case"Radar":m=c&&c!=="none"?c:a;break;default:m=a;break}return m},Lht=function(e){var r=e.barSize,n=e.totalSize,i=e.stackGroups,o=i===void 0?{}:i;if(!o)return{};for(var c={},a=Object.keys(o),m=0,g=a.length;m=0});if(O&&O.length){var R=O[0].type.defaultProps,z=R!==void 0?Io(Io({},R),O[0].props):O[0].props,W=z.barSize,V=z[I];c[V]||(c[V]=[]);var K=$i(W)?r:W;c[V].push({item:O[0],stackList:O.slice(1),barSize:$i(K)?void 0:su(K,n,0)})}}return c},Fht=function(e){var r=e.barGap,n=e.barCategoryGap,i=e.bandSize,o=e.sizeList,c=o===void 0?[]:o,a=e.maxBarSize,m=c.length;if(m<1)return null;var g=su(r,i,0,!0),_,j=[];if(c[0].barSize===+c[0].barSize){var N=!1,C=i/m,P=c.reduce(function(W,V){return W+V.barSize||0},0);P+=(m-1)*g,P>=i&&(P-=(m-1)*g,g=0),P>=i&&C>0&&(N=!0,C*=.9,P=m*C);var A=(i-P)/2>>0,I={offset:A-g,size:0};_=c.reduce(function(W,V){var K={item:V.item,position:{offset:I.offset+I.size+g,size:N?C:V.barSize}},Q=[].concat(mre(W),[K]);return I=Q[Q.length-1].position,V.stackList&&V.stackList.length&&V.stackList.forEach(function(te){Q.push({item:te,position:I})}),Q},j)}else{var O=su(n,i,0,!0);i-2*O-(m-1)*g<=0&&(g=0);var R=(i-2*O-(m-1)*g)/m;R>1&&(R>>=0);var z=a===+a?Math.min(R,a):R;_=c.reduce(function(W,V,K){var Q=[].concat(mre(W),[{item:V.item,position:{offset:O+(R+g)*K+(R-z)/2,size:z}}]);return V.stackList&&V.stackList.length&&V.stackList.forEach(function(te){Q.push({item:te,position:Q[Q.length-1].position})}),Q},j)}return _},zht=function(e,r,n,i){var o=n.children,c=n.width,a=n.margin,m=c-(a.left||0)-(a.right||0),g=R_e({children:o,legendWidth:m});if(g){var _=i||{},j=_.width,N=_.height,C=g.align,P=g.verticalAlign,A=g.layout;if((A==="vertical"||A==="horizontal"&&P==="middle")&&C!=="center"&&hn(e[C]))return Io(Io({},e),{},h1({},C,e[C]+(j||0)));if((A==="horizontal"||A==="vertical"&&C==="center")&&P!=="middle"&&hn(e[P]))return Io(Io({},e),{},h1({},P,e[P]+(N||0)))}return e},Bht=function(e,r,n){return $i(r)?!0:e==="horizontal"?r==="yAxis":e==="vertical"||n==="x"?r==="xAxis":n==="y"?r==="yAxis":!0},D_e=function(e,r,n,i,o){var c=r.props.children,a=dh(c,qL).filter(function(g){return Bht(i,o,g.props.direction)});if(a&&a.length){var m=a.map(function(g){return g.props.dataKey});return e.reduce(function(g,_){var j=Mc(_,n);if($i(j))return g;var N=Array.isArray(j)?[BL(j),zL(j)]:[j,j],C=m.reduce(function(P,A){var I=Mc(_,A,0),O=N[0]-Math.abs(Array.isArray(I)?I[0]:I),R=N[1]+Math.abs(Array.isArray(I)?I[1]:I);return[Math.min(O,P[0]),Math.max(R,P[1])]},[1/0,-1/0]);return[Math.min(C[0],g[0]),Math.max(C[1],g[1])]},[1/0,-1/0])}return null},$ht=function(e,r,n,i,o){var c=r.map(function(a){return D_e(e,a,n,o,i)}).filter(function(a){return!$i(a)});return c&&c.length?c.reduce(function(a,m){return[Math.min(a[0],m[0]),Math.max(a[1],m[1])]},[1/0,-1/0]):null},L_e=function(e,r,n,i,o){var c=r.map(function(m){var g=m.props.dataKey;return n==="number"&&g&&D_e(e,m,g,i)||S2(e,g,n,o)});if(n==="number")return c.reduce(function(m,g){return[Math.min(m[0],g[0]),Math.max(m[1],g[1])]},[1/0,-1/0]);var a={};return c.reduce(function(m,g){for(var _=0,j=g.length;_=2?nu(a[0]-a[1])*2*g:g,r&&(e.ticks||e.niceTicks)){var _=(e.ticks||e.niceTicks).map(function(j){var N=o?o.indexOf(j):j;return{coordinate:i(N)+g,value:j,offset:g}});return _.filter(function(j){return!qT(j.coordinate)})}return e.isCategorical&&e.categoricalDomain?e.categoricalDomain.map(function(j,N){return{coordinate:i(j)+g,value:j,index:N,offset:g}}):i.ticks&&!n?i.ticks(e.tickCount).map(function(j){return{coordinate:i(j)+g,value:j,offset:g}}):i.domain().map(function(j,N){return{coordinate:i(j)+g,value:o?o[j]:j,index:N,offset:g}})},vB=new WeakMap,rI=function(e,r){if(typeof r!="function")return e;vB.has(e)||vB.set(e,new WeakMap);var n=vB.get(e);if(n.has(r))return n.get(r);var i=function(){e.apply(void 0,arguments),r.apply(void 0,arguments)};return n.set(r,i),i},B_e=function(e,r,n){var i=e.scale,o=e.type,c=e.layout,a=e.axisType;if(i==="auto")return c==="radial"&&a==="radiusAxis"?{scale:Ek(),realScaleType:"band"}:c==="radial"&&a==="angleAxis"?{scale:rR(),realScaleType:"linear"}:o==="category"&&r&&(r.indexOf("LineChart")>=0||r.indexOf("AreaChart")>=0||r.indexOf("ComposedChart")>=0&&!n)?{scale:j2(),realScaleType:"point"}:o==="category"?{scale:Ek(),realScaleType:"band"}:{scale:rR(),realScaleType:"linear"};if(W_(i)){var m="scale".concat(SL(i));return{scale:(cre[m]||j2)(),realScaleType:cre[m]?m:"point"}}return ti(i)?{scale:i}:{scale:j2(),realScaleType:"point"}},yre=1e-4,$_e=function(e){var r=e.domain();if(!(!r||r.length<=2)){var n=r.length,i=e.range(),o=Math.min(i[0],i[1])-yre,c=Math.max(i[0],i[1])+yre,a=e(r[0]),m=e(r[n-1]);(ac||mc)&&e.domain([r[0],r[n-1]])}},Uht=function(e,r){if(!e)return null;for(var n=0,i=e.length;ni)&&(o[1]=i),o[0]>i&&(o[0]=i),o[1]=0?(e[a][n][0]=o,e[a][n][1]=o+m,o=e[a][n][1]):(e[a][n][0]=c,e[a][n][1]=c+m,c=e[a][n][1])}},Hht=function(e){var r=e.length;if(!(r<=0))for(var n=0,i=e[0].length;n=0?(e[c][n][0]=o,e[c][n][1]=o+a,o=e[c][n][1]):(e[c][n][0]=0,e[c][n][1]=0)}},Wht={sign:qht,expand:cJe,none:tj,silhouette:uJe,wiggle:dJe,positive:Hht},Ght=function(e,r,n){var i=r.map(function(a){return a.props.dataKey}),o=Wht[n],c=lJe().keys(i).value(function(a,m){return+Mc(a,m,0)}).order(kU).offset(o);return c(e)},Kht=function(e,r,n,i,o,c){if(!e)return null;var a=c?r.reverse():r,m={},g=a.reduce(function(j,N){var C,P=(C=N.type)!==null&&C!==void 0&&C.defaultProps?Io(Io({},N.type.defaultProps),N.props):N.props,A=P.stackId,I=P.hide;if(I)return j;var O=P[n],R=j[O]||{hasStack:!1,stackGroups:{}};if(El(A)){var z=R.stackGroups[A]||{numericAxisId:n,cateAxisId:i,items:[]};z.items.push(N),R.hasStack=!0,R.stackGroups[A]=z}else R.stackGroups[HT("_stackId_")]={numericAxisId:n,cateAxisId:i,items:[N]};return Io(Io({},j),{},h1({},O,R))},m),_={};return Object.keys(g).reduce(function(j,N){var C=g[N];if(C.hasStack){var P={};C.stackGroups=Object.keys(C.stackGroups).reduce(function(A,I){var O=C.stackGroups[I];return Io(Io({},A),{},h1({},I,{numericAxisId:n,cateAxisId:i,items:O.items,stackedData:Ght(e,O.items,o)}))},P)}return Io(Io({},j),{},h1({},N,C))},_)},U_e=function(e,r){var n=r.realScaleType,i=r.type,o=r.tickCount,c=r.originalDomain,a=r.allowDecimals,m=n||r.scale;if(m!=="auto"&&m!=="linear")return null;if(o&&i==="number"&&c&&(c[0]==="auto"||c[1]==="auto")){var g=e.domain();if(!g.length)return null;var _=lht(g,o,a);return e.domain([BL(_),zL(_)]),{niceTicks:_}}if(o&&i==="number"){var j=e.domain(),N=cht(j,o,a);return{niceTicks:N}}return null},xre=function(e){var r=e.axis,n=e.ticks,i=e.offset,o=e.bandSize,c=e.entry,a=e.index;if(r.type==="category")return n[a]?n[a].coordinate+i:null;var m=Mc(c,r.dataKey,r.domain[a]);return $i(m)?null:r.scale(m)-o/2+i},Zht=function(e){var r=e.numericAxis,n=r.scale.domain();if(r.type==="number"){var i=Math.min(n[0],n[1]),o=Math.max(n[0],n[1]);return i<=0&&o>=0?0:o<0?o:i}return n[0]},Yht=function(e,r){var n,i=(n=e.type)!==null&&n!==void 0&&n.defaultProps?Io(Io({},e.type.defaultProps),e.props):e.props,o=i.stackId;if(El(o)){var c=r[o];if(c){var a=c.items.indexOf(e);return a>=0?c.stackedData[a]:null}}return null},Xht=function(e){return e.reduce(function(r,n){return[BL(n.concat([r[0]]).filter(hn)),zL(n.concat([r[1]]).filter(hn))]},[1/0,-1/0])},V_e=function(e,r,n){return Object.keys(e).reduce(function(i,o){var c=e[o],a=c.stackedData,m=a.reduce(function(g,_){var j=Xht(_.slice(r,n+1));return[Math.min(g[0],j[0]),Math.max(g[1],j[1])]},[1/0,-1/0]);return[Math.min(m[0],i[0]),Math.max(m[1],i[1])]},[1/0,-1/0]).map(function(i){return i===1/0||i===-1/0?0:i})},vre=/^dataMin[\s]*-[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,_re=/^dataMax[\s]*\+[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,sV=function(e,r,n){if(ti(e))return e(r,n);if(!Array.isArray(e))return r;var i=[];if(hn(e[0]))i[0]=n?e[0]:Math.min(e[0],r[0]);else if(vre.test(e[0])){var o=+vre.exec(e[0])[1];i[0]=r[0]-o}else ti(e[0])?i[0]=e[0](r[0]):i[0]=r[0];if(hn(e[1]))i[1]=n?e[1]:Math.max(e[1],r[1]);else if(_re.test(e[1])){var c=+_re.exec(e[1])[1];i[1]=r[1]+c}else ti(e[1])?i[1]=e[1](r[1]):i[1]=r[1];return i},cR=function(e,r,n){if(e&&e.scale&&e.scale.bandwidth){var i=e.scale.bandwidth();if(!n||i>0)return i}if(e&&r&&r.length>=2){for(var o=GH(r,function(j){return j.coordinate}),c=1/0,a=1,m=o.length;at.length)&&(e=t.length);for(var r=0,n=new Array(e);r2&&arguments[2]!==void 0?arguments[2]:{top:0,right:0,bottom:0,left:0};return Math.min(Math.abs(e-(n.left||0)-(n.right||0)),Math.abs(r-(n.top||0)-(n.bottom||0)))/2},aft=function(e,r,n,i,o){var c=e.width,a=e.height,m=e.startAngle,g=e.endAngle,_=su(e.cx,c,c/2),j=su(e.cy,a,a/2),N=W_e(c,a,n),C=su(e.innerRadius,N,0),P=su(e.outerRadius,N,N*.8),A=Object.keys(r);return A.reduce(function(I,O){var R=r[O],z=R.domain,W=R.reversed,V;if($i(R.range))i==="angleAxis"?V=[m,g]:i==="radiusAxis"&&(V=[C,P]),W&&(V=[V[1],V[0]]);else{V=R.range;var K=V,Q=eft(K,2);m=Q[0],g=Q[1]}var te=B_e(R,o),X=te.realScaleType,ie=te.scale;ie.domain(z).range(V),$_e(ie);var he=U_e(ie,jm(jm({},R),{},{realScaleType:X})),xe=jm(jm(jm({},R),he),{},{range:V,radius:P,realScaleType:X,scale:ie,cx:_,cy:j,innerRadius:C,outerRadius:P,startAngle:m,endAngle:g});return jm(jm({},I),{},H_e({},O,xe))},{})},oft=function(e,r){var n=e.x,i=e.y,o=r.x,c=r.y;return Math.sqrt(Math.pow(n-o,2)+Math.pow(i-c,2))},lft=function(e,r){var n=e.x,i=e.y,o=r.cx,c=r.cy,a=oft({x:n,y:i},{x:o,y:c});if(a<=0)return{radius:a};var m=(n-o)/a,g=Math.acos(m);return i>c&&(g=2*Math.PI-g),{radius:a,angle:ift(g),angleInRadian:g}},cft=function(e){var r=e.startAngle,n=e.endAngle,i=Math.floor(r/360),o=Math.floor(n/360),c=Math.min(i,o);return{startAngle:r-c*360,endAngle:n-c*360}},uft=function(e,r){var n=r.startAngle,i=r.endAngle,o=Math.floor(n/360),c=Math.floor(i/360),a=Math.min(o,c);return e+a*360},Sre=function(e,r){var n=e.x,i=e.y,o=lft({x:n,y:i},r),c=o.radius,a=o.angle,m=r.innerRadius,g=r.outerRadius;if(cg)return!1;if(c===0)return!0;var _=cft(r),j=_.startAngle,N=_.endAngle,C=a,P;if(j<=N){for(;C>N;)C-=360;for(;C=j&&C<=N}else{for(;C>j;)C-=360;for(;C=N&&C<=j}return P?jm(jm({},r),{},{radius:c,angle:uft(C,r)}):null},G_e=function(e){return!D.isValidElement(e)&&!ti(e)&&typeof e!="boolean"?e.className:""};function zk(t){"@babel/helpers - typeof";return zk=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},zk(t)}var dft=["offset"];function hft(t){return gft(t)||mft(t)||pft(t)||fft()}function fft(){throw new TypeError(`Invalid attempt to spread non-iterable instance. In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function pft(t,e){if(t){if(typeof t=="string")return iV(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set")return Array.from(t);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return iV(t,e)}}function mft(t){if(typeof Symbol<"u"&&t[Symbol.iterator]!=null||t["@@iterator"]!=null)return Array.from(t)}function gft(t){if(Array.isArray(t))return iV(t)}function iV(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function xft(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}function Nre(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function bl(t){for(var e=1;e=0?1:-1,z,W;i==="insideStart"?(z=C+R*c,W=A):i==="insideEnd"?(z=P-R*c,W=!A):i==="end"&&(z=P+R*c,W=A),W=O<=0?W:!W;var V=Ga(g,_,I,z),K=Ga(g,_,I,z+(W?1:-1)*359),Q="M".concat(V.x,",").concat(V.y,` A`).concat(I,",").concat(I,",0,1,").concat(W?0:1,`, `).concat(K.x,",").concat(K.y),te=$i(e.id)?HT("recharts-radial-line-"):e.id;return Ve.createElement("text",Bk({},n,{dominantBaseline:"central",className:Ci("recharts-radial-bar-label",a)}),Ve.createElement("defs",null,Ve.createElement("path",{id:te,d:Q})),Ve.createElement("textPath",{xlinkHref:"#".concat(te)},r))},Nft=function(e){var r=e.viewBox,n=e.offset,i=e.position,o=r,c=o.cx,a=o.cy,m=o.innerRadius,g=o.outerRadius,_=o.startAngle,j=o.endAngle,N=(_+j)/2;if(i==="outside"){var C=Ga(c,a,g+n,N),P=C.x,A=C.y;return{x:P,y:A,textAnchor:P>=c?"start":"end",verticalAnchor:"middle"}}if(i==="center")return{x:c,y:a,textAnchor:"middle",verticalAnchor:"middle"};if(i==="centerTop")return{x:c,y:a,textAnchor:"middle",verticalAnchor:"start"};if(i==="centerBottom")return{x:c,y:a,textAnchor:"middle",verticalAnchor:"end"};var I=(m+g)/2,O=Ga(c,a,I,N),R=O.x,z=O.y;return{x:R,y:z,textAnchor:"middle",verticalAnchor:"middle"}},Cft=function(e){var r=e.viewBox,n=e.parentViewBox,i=e.offset,o=e.position,c=r,a=c.x,m=c.y,g=c.width,_=c.height,j=_>=0?1:-1,N=j*i,C=j>0?"end":"start",P=j>0?"start":"end",A=g>=0?1:-1,I=A*i,O=A>0?"end":"start",R=A>0?"start":"end";if(o==="top"){var z={x:a+g/2,y:m-j*i,textAnchor:"middle",verticalAnchor:C};return bl(bl({},z),n?{height:Math.max(m-n.y,0),width:g}:{})}if(o==="bottom"){var W={x:a+g/2,y:m+_+N,textAnchor:"middle",verticalAnchor:P};return bl(bl({},W),n?{height:Math.max(n.y+n.height-(m+_),0),width:g}:{})}if(o==="left"){var V={x:a-I,y:m+_/2,textAnchor:O,verticalAnchor:"middle"};return bl(bl({},V),n?{width:Math.max(V.x-n.x,0),height:_}:{})}if(o==="right"){var K={x:a+g+I,y:m+_/2,textAnchor:R,verticalAnchor:"middle"};return bl(bl({},K),n?{width:Math.max(n.x+n.width-K.x,0),height:_}:{})}var Q=n?{width:g,height:_}:{};return o==="insideLeft"?bl({x:a+I,y:m+_/2,textAnchor:R,verticalAnchor:"middle"},Q):o==="insideRight"?bl({x:a+g-I,y:m+_/2,textAnchor:O,verticalAnchor:"middle"},Q):o==="insideTop"?bl({x:a+g/2,y:m+N,textAnchor:"middle",verticalAnchor:P},Q):o==="insideBottom"?bl({x:a+g/2,y:m+_-N,textAnchor:"middle",verticalAnchor:C},Q):o==="insideTopLeft"?bl({x:a+I,y:m+N,textAnchor:R,verticalAnchor:P},Q):o==="insideTopRight"?bl({x:a+g-I,y:m+N,textAnchor:O,verticalAnchor:P},Q):o==="insideBottomLeft"?bl({x:a+I,y:m+_-N,textAnchor:R,verticalAnchor:C},Q):o==="insideBottomRight"?bl({x:a+g-I,y:m+_-N,textAnchor:O,verticalAnchor:C},Q):Zj(o)&&(hn(o.x)||e_(o.x))&&(hn(o.y)||e_(o.y))?bl({x:a+su(o.x,g),y:m+su(o.y,_),textAnchor:"end",verticalAnchor:"end"},Q):bl({x:a+g/2,y:m+_/2,textAnchor:"middle",verticalAnchor:"middle"},Q)},kft=function(e){return"cx"in e&&hn(e.cx)};function Vl(t){var e=t.offset,r=e===void 0?5:e,n=yft(t,dft),i=bl({offset:r},n),o=i.viewBox,c=i.position,a=i.value,m=i.children,g=i.content,_=i.className,j=_===void 0?"":_,N=i.textBreakAll;if(!o||$i(a)&&$i(m)&&!D.isValidElement(g)&&!ti(g))return null;if(D.isValidElement(g))return D.cloneElement(g,i);var C;if(ti(g)){if(C=D.createElement(g,i),D.isValidElement(C))return C}else C=wft(i);var P=kft(o),A=Ks(i,!0);if(P&&(c==="insideStart"||c==="insideEnd"||c==="end"))return Sft(i,C,A);var I=P?Nft(i):Cft(i);return Ve.createElement(K_,Bk({className:Ci("recharts-label",j)},A,I,{breakAll:N}),C)}Vl.displayName="Label";var K_e=function(e){var r=e.cx,n=e.cy,i=e.angle,o=e.startAngle,c=e.endAngle,a=e.r,m=e.radius,g=e.innerRadius,_=e.outerRadius,j=e.x,N=e.y,C=e.top,P=e.left,A=e.width,I=e.height,O=e.clockWise,R=e.labelViewBox;if(R)return R;if(hn(A)&&hn(I)){if(hn(j)&&hn(N))return{x:j,y:N,width:A,height:I};if(hn(C)&&hn(P))return{x:C,y:P,width:A,height:I}}return hn(j)&&hn(N)?{x:j,y:N,width:0,height:0}:hn(r)&&hn(n)?{cx:r,cy:n,startAngle:o||i||0,endAngle:c||i||0,innerRadius:g||0,outerRadius:_||m||a||0,clockWise:O}:e.viewBox?e.viewBox:{}},Tft=function(e,r){return e?e===!0?Ve.createElement(Vl,{key:"label-implicit",viewBox:r}):El(e)?Ve.createElement(Vl,{key:"label-implicit",viewBox:r,value:e}):D.isValidElement(e)?e.type===Vl?D.cloneElement(e,{key:"label-implicit",viewBox:r}):Ve.createElement(Vl,{key:"label-implicit",content:e,viewBox:r}):ti(e)?Ve.createElement(Vl,{key:"label-implicit",content:e,viewBox:r}):Zj(e)?Ve.createElement(Vl,Bk({viewBox:r},e,{key:"label-implicit"})):null:null},Eft=function(e,r){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;if(!e||!e.children&&n&&!e.label)return null;var i=e.children,o=K_e(e),c=dh(i,Vl).map(function(m,g){return D.cloneElement(m,{viewBox:r||o,key:"label-".concat(g)})});if(!n)return c;var a=Tft(e.label,r||o);return[a].concat(hft(c))};Vl.parseViewBox=K_e;Vl.renderCallByParent=Eft;function Aft(t){var e=t==null?0:t.length;return e?t[e-1]:void 0}var Pft=Aft;const Ift=sa(Pft);function $k(t){"@babel/helpers - typeof";return $k=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},$k(t)}var Mft=["valueAccessor"],Oft=["data","dataKey","clockWise","id","textBreakAll"];function Rft(t){return zft(t)||Fft(t)||Lft(t)||Dft()}function Dft(){throw new TypeError(`Invalid attempt to spread non-iterable instance. In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Lft(t,e){if(t){if(typeof t=="string")return aV(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set")return Array.from(t);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return aV(t,e)}}function Fft(t){if(typeof Symbol<"u"&&t[Symbol.iterator]!=null||t["@@iterator"]!=null)return Array.from(t)}function zft(t){if(Array.isArray(t))return aV(t)}function aV(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function Vft(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}var qft=function(e){return Array.isArray(e.value)?Ift(e.value):e.value};function ex(t){var e=t.valueAccessor,r=e===void 0?qft:e,n=Tre(t,Mft),i=n.data,o=n.dataKey,c=n.clockWise,a=n.id,m=n.textBreakAll,g=Tre(n,Oft);return!i||!i.length?null:Ve.createElement(Na,{className:"recharts-label-list"},i.map(function(_,j){var N=$i(o)?r(_,j):Mc(_&&_.payload,o),C=$i(a)?{}:{id:"".concat(a,"-").concat(j)};return Ve.createElement(Vl,dR({},Ks(_,!0),g,C,{parentViewBox:_.parentViewBox,value:N,textBreakAll:m,viewBox:Vl.parseViewBox($i(c)?_:kre(kre({},_),{},{clockWise:c})),key:"label-".concat(j),index:j}))}))}ex.displayName="LabelList";function Hft(t,e){return t?t===!0?Ve.createElement(ex,{key:"labelList-implicit",data:e}):Ve.isValidElement(t)||ti(t)?Ve.createElement(ex,{key:"labelList-implicit",data:e,content:t}):Zj(t)?Ve.createElement(ex,dR({data:e},t,{key:"labelList-implicit"})):null:null}function Wft(t,e){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;if(!t||!t.children&&r&&!t.label)return null;var n=t.children,i=dh(n,ex).map(function(c,a){return D.cloneElement(c,{data:e,key:"labelList-".concat(a)})});if(!r)return i;var o=Hft(t.label,e);return[o].concat(Rft(i))}ex.renderCallByParent=Wft;function Uk(t){"@babel/helpers - typeof";return Uk=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Uk(t)}function oV(){return oV=Object.assign?Object.assign.bind():function(t){for(var e=1;e180),",").concat(+(c>g),`, `).concat(j.x,",").concat(j.y,` `);if(i>0){var C=Ga(r,n,i,c),P=Ga(r,n,i,g);N+="L ".concat(P.x,",").concat(P.y,` A `).concat(i,",").concat(i,`,0, `).concat(+(Math.abs(m)>180),",").concat(+(c<=g),`, `).concat(C.x,",").concat(C.y," Z")}else N+="L ".concat(r,",").concat(n," Z");return N},Xft=function(e){var r=e.cx,n=e.cy,i=e.innerRadius,o=e.outerRadius,c=e.cornerRadius,a=e.forceCornerRadius,m=e.cornerIsExternal,g=e.startAngle,_=e.endAngle,j=nu(_-g),N=nI({cx:r,cy:n,radius:o,angle:g,sign:j,cornerRadius:c,cornerIsExternal:m}),C=N.circleTangency,P=N.lineTangency,A=N.theta,I=nI({cx:r,cy:n,radius:o,angle:_,sign:-j,cornerRadius:c,cornerIsExternal:m}),O=I.circleTangency,R=I.lineTangency,z=I.theta,W=m?Math.abs(g-_):Math.abs(g-_)-A-z;if(W<0)return a?"M ".concat(P.x,",").concat(P.y,` a`).concat(c,",").concat(c,",0,0,1,").concat(c*2,`,0 a`).concat(c,",").concat(c,",0,0,1,").concat(-c*2,`,0 `):Z_e({cx:r,cy:n,innerRadius:i,outerRadius:o,startAngle:g,endAngle:_});var V="M ".concat(P.x,",").concat(P.y,` A`).concat(c,",").concat(c,",0,0,").concat(+(j<0),",").concat(C.x,",").concat(C.y,` A`).concat(o,",").concat(o,",0,").concat(+(W>180),",").concat(+(j<0),",").concat(O.x,",").concat(O.y,` A`).concat(c,",").concat(c,",0,0,").concat(+(j<0),",").concat(R.x,",").concat(R.y,` `);if(i>0){var K=nI({cx:r,cy:n,radius:i,angle:g,sign:j,isExternal:!0,cornerRadius:c,cornerIsExternal:m}),Q=K.circleTangency,te=K.lineTangency,X=K.theta,ie=nI({cx:r,cy:n,radius:i,angle:_,sign:-j,isExternal:!0,cornerRadius:c,cornerIsExternal:m}),he=ie.circleTangency,xe=ie.lineTangency,pe=ie.theta,ve=m?Math.abs(g-_):Math.abs(g-_)-X-pe;if(ve<0&&c===0)return"".concat(V,"L").concat(r,",").concat(n,"Z");V+="L".concat(xe.x,",").concat(xe.y,` A`).concat(c,",").concat(c,",0,0,").concat(+(j<0),",").concat(he.x,",").concat(he.y,` A`).concat(i,",").concat(i,",0,").concat(+(ve>180),",").concat(+(j>0),",").concat(Q.x,",").concat(Q.y,` A`).concat(c,",").concat(c,",0,0,").concat(+(j<0),",").concat(te.x,",").concat(te.y,"Z")}else V+="L".concat(r,",").concat(n,"Z");return V},Qft={cx:0,cy:0,innerRadius:0,outerRadius:0,startAngle:0,endAngle:0,cornerRadius:0,forceCornerRadius:!1,cornerIsExternal:!1},Y_e=function(e){var r=Are(Are({},Qft),e),n=r.cx,i=r.cy,o=r.innerRadius,c=r.outerRadius,a=r.cornerRadius,m=r.forceCornerRadius,g=r.cornerIsExternal,_=r.startAngle,j=r.endAngle,N=r.className;if(c0&&Math.abs(_-j)<360?I=Xft({cx:n,cy:i,innerRadius:o,outerRadius:c,cornerRadius:Math.min(A,P/2),forceCornerRadius:m,cornerIsExternal:g,startAngle:_,endAngle:j}):I=Z_e({cx:n,cy:i,innerRadius:o,outerRadius:c,startAngle:_,endAngle:j}),Ve.createElement("path",oV({},Ks(r,!0),{className:C,d:I,role:"img"}))};function Vk(t){"@babel/helpers - typeof";return Vk=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Vk(t)}function lV(){return lV=Object.assign?Object.assign.bind():function(t){for(var e=1;e0;)if(!r.equals(t[n],e[n],n,n,t,e,r))return!1;return!0}function ypt(t,e){return h0(t.getTime(),e.getTime())}function xpt(t,e){return t.name===e.name&&t.message===e.message&&t.cause===e.cause&&t.stack===e.stack}function vpt(t,e){return t===e}function Fre(t,e,r){var n=t.size;if(n!==e.size)return!1;if(!n)return!0;for(var i=new Array(n),o=t.entries(),c,a,m=0;(c=o.next())&&!c.done;){for(var g=e.entries(),_=!1,j=0;(a=g.next())&&!a.done;){if(i[j]){j++;continue}var N=c.value,C=a.value;if(r.equals(N[0],C[0],m,j,t,e,r)&&r.equals(N[1],C[1],N[0],C[0],t,e,r)){_=i[j]=!0;break}j++}if(!_)return!1;m++}return!0}var _pt=h0;function bpt(t,e,r){var n=Lre(t),i=n.length;if(Lre(e).length!==i)return!1;for(;i-- >0;)if(!e0e(t,e,r,n[i]))return!1;return!0}function AC(t,e,r){var n=Rre(t),i=n.length;if(Rre(e).length!==i)return!1;for(var o,c,a;i-- >0;)if(o=n[i],!e0e(t,e,r,o)||(c=Dre(t,o),a=Dre(e,o),(c||a)&&(!c||!a||c.configurable!==a.configurable||c.enumerable!==a.enumerable||c.writable!==a.writable)))return!1;return!0}function wpt(t,e){return h0(t.valueOf(),e.valueOf())}function jpt(t,e){return t.source===e.source&&t.flags===e.flags}function zre(t,e,r){var n=t.size;if(n!==e.size)return!1;if(!n)return!0;for(var i=new Array(n),o=t.values(),c,a;(c=o.next())&&!c.done;){for(var m=e.values(),g=!1,_=0;(a=m.next())&&!a.done;){if(!i[_]&&r.equals(c.value,a.value,c.value,a.value,t,e,r)){g=i[_]=!0;break}_++}if(!g)return!1}return!0}function Spt(t,e){var r=t.length;if(e.length!==r)return!1;for(;r-- >0;)if(t[r]!==e[r])return!1;return!0}function Npt(t,e){return t.hostname===e.hostname&&t.pathname===e.pathname&&t.protocol===e.protocol&&t.port===e.port&&t.hash===e.hash&&t.username===e.username&&t.password===e.password}function e0e(t,e,r,n){return(n===mpt||n===ppt||n===fpt)&&(t.$$typeof||e.$$typeof)?!0:hpt(e,n)&&r.equals(t[n],e[n],n,n,t,e,r)}var Cpt="[object Arguments]",kpt="[object Boolean]",Tpt="[object Date]",Ept="[object Error]",Apt="[object Map]",Ppt="[object Number]",Ipt="[object Object]",Mpt="[object RegExp]",Opt="[object Set]",Rpt="[object String]",Dpt="[object URL]",Lpt=Array.isArray,Bre=typeof ArrayBuffer=="function"&&ArrayBuffer.isView?ArrayBuffer.isView:null,$re=Object.assign,Fpt=Object.prototype.toString.call.bind(Object.prototype.toString);function zpt(t){var e=t.areArraysEqual,r=t.areDatesEqual,n=t.areErrorsEqual,i=t.areFunctionsEqual,o=t.areMapsEqual,c=t.areNumbersEqual,a=t.areObjectsEqual,m=t.arePrimitiveWrappersEqual,g=t.areRegExpsEqual,_=t.areSetsEqual,j=t.areTypedArraysEqual,N=t.areUrlsEqual;return function(P,A,I){if(P===A)return!0;if(P==null||A==null)return!1;var O=typeof P;if(O!==typeof A)return!1;if(O!=="object")return O==="number"?c(P,A,I):O==="function"?i(P,A,I):!1;var R=P.constructor;if(R!==A.constructor)return!1;if(R===Object)return a(P,A,I);if(Lpt(P))return e(P,A,I);if(Bre!=null&&Bre(P))return j(P,A,I);if(R===Date)return r(P,A,I);if(R===RegExp)return g(P,A,I);if(R===Map)return o(P,A,I);if(R===Set)return _(P,A,I);var z=Fpt(P);return z===Tpt?r(P,A,I):z===Mpt?g(P,A,I):z===Apt?o(P,A,I):z===Opt?_(P,A,I):z===Ipt?typeof P.then!="function"&&typeof A.then!="function"&&a(P,A,I):z===Dpt?N(P,A,I):z===Ept?n(P,A,I):z===Cpt?a(P,A,I):z===kpt||z===Ppt||z===Rpt?m(P,A,I):!1}}function Bpt(t){var e=t.circular,r=t.createCustomConfig,n=t.strict,i={areArraysEqual:n?AC:gpt,areDatesEqual:ypt,areErrorsEqual:xpt,areFunctionsEqual:vpt,areMapsEqual:n?Ore(Fre,AC):Fre,areNumbersEqual:_pt,areObjectsEqual:n?AC:bpt,arePrimitiveWrappersEqual:wpt,areRegExpsEqual:jpt,areSetsEqual:n?Ore(zre,AC):zre,areTypedArraysEqual:n?AC:Spt,areUrlsEqual:Npt};if(r&&(i=$re({},i,r(i))),e){var o=iI(i.areArraysEqual),c=iI(i.areMapsEqual),a=iI(i.areObjectsEqual),m=iI(i.areSetsEqual);i=$re({},i,{areArraysEqual:o,areMapsEqual:c,areObjectsEqual:a,areSetsEqual:m})}return i}function $pt(t){return function(e,r,n,i,o,c,a){return t(e,r,a)}}function Upt(t){var e=t.circular,r=t.comparator,n=t.createState,i=t.equals,o=t.strict;if(n)return function(m,g){var _=n(),j=_.cache,N=j===void 0?e?new WeakMap:void 0:j,C=_.meta;return r(m,g,{cache:N,equals:i,meta:C,strict:o})};if(e)return function(m,g){return r(m,g,{cache:new WeakMap,equals:i,meta:void 0,strict:o})};var c={cache:void 0,equals:i,meta:void 0,strict:o};return function(m,g){return r(m,g,c)}}var Vpt=Ax();Ax({strict:!0});Ax({circular:!0});Ax({circular:!0,strict:!0});Ax({createInternalComparator:function(){return h0}});Ax({strict:!0,createInternalComparator:function(){return h0}});Ax({circular:!0,createInternalComparator:function(){return h0}});Ax({circular:!0,createInternalComparator:function(){return h0},strict:!0});function Ax(t){t===void 0&&(t={});var e=t.circular,r=e===void 0?!1:e,n=t.createInternalComparator,i=t.createState,o=t.strict,c=o===void 0?!1:o,a=Bpt(t),m=zpt(a),g=n?n(m):$pt(m);return Upt({circular:r,comparator:m,createState:i,equals:g,strict:c})}function qpt(t){typeof requestAnimationFrame<"u"&&requestAnimationFrame(t)}function Ure(t){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,r=-1,n=function i(o){r<0&&(r=o),o-r>e?(t(o),r=-1):qpt(i)};requestAnimationFrame(n)}function uV(t){"@babel/helpers - typeof";return uV=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},uV(t)}function Hpt(t){return Zpt(t)||Kpt(t)||Gpt(t)||Wpt()}function Wpt(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Gpt(t,e){if(t){if(typeof t=="string")return Vre(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set")return Array.from(t);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Vre(t,e)}}function Vre(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);rt.length)&&(e=t.length);for(var r=0,n=new Array(e);r1?1:O<0?0:O},A=function(O){for(var R=O>1?1:O,z=R,W=0;W<8;++W){var V=j(z)-R,K=C(z);if(Math.abs(V-R)0&&arguments[0]!==void 0?arguments[0]:{},r=e.stiff,n=r===void 0?100:r,i=e.damping,o=i===void 0?8:i,c=e.dt,a=c===void 0?17:c,m=function(_,j,N){var C=-(_-j)*n,P=N*o,A=N+(C-P)*a/1e3,I=N*a/1e3+_;return Math.abs(I-j)t.length)&&(e=t.length);for(var r=0,n=new Array(e);r=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function Cmt(t,e){if(t==null)return{};var r={},n=Object.keys(t),i,o;for(o=0;o=0)&&(r[i]=t[i]);return r}function _B(t){return Amt(t)||Emt(t)||Tmt(t)||kmt()}function kmt(){throw new TypeError(`Invalid attempt to spread non-iterable instance. In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Tmt(t,e){if(t){if(typeof t=="string")return mV(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set")return Array.from(t);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return mV(t,e)}}function Emt(t){if(typeof Symbol<"u"&&t[Symbol.iterator]!=null||t["@@iterator"]!=null)return Array.from(t)}function Amt(t){if(Array.isArray(t))return mV(t)}function mV(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function pR(t){return pR=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},pR(t)}var Qm=function(t){Rmt(r,t);var e=Dmt(r);function r(n,i){var o;Pmt(this,r),o=e.call(this,n,i);var c=o.props,a=c.isActive,m=c.attributeName,g=c.from,_=c.to,j=c.steps,N=c.children,C=c.duration;if(o.handleStyleChange=o.handleStyleChange.bind(xV(o)),o.changeStyle=o.changeStyle.bind(xV(o)),!a||C<=0)return o.state={style:{}},typeof N=="function"&&(o.state={style:_}),yV(o);if(j&&j.length)o.state={style:j[0].style};else if(g){if(typeof N=="function")return o.state={style:g},yV(o);o.state={style:m?WC({},m,g):g}}else o.state={style:{}};return o}return Mmt(r,[{key:"componentDidMount",value:function(){var i=this.props,o=i.isActive,c=i.canBegin;this.mounted=!0,!(!o||!c)&&this.runAnimation(this.props)}},{key:"componentDidUpdate",value:function(i){var o=this.props,c=o.isActive,a=o.canBegin,m=o.attributeName,g=o.shouldReAnimate,_=o.to,j=o.from,N=this.state.style;if(a){if(!c){var C={style:m?WC({},m,_):_};this.state&&N&&(m&&N[m]!==_||!m&&N!==_)&&this.setState(C);return}if(!(Vpt(i.to,_)&&i.canBegin&&i.isActive)){var P=!i.canBegin||!i.isActive;this.manager&&this.manager.stop(),this.stopJSAnimation&&this.stopJSAnimation();var A=P||g?j:i.to;if(this.state&&N){var I={style:m?WC({},m,A):A};(m&&N[m]!==A||!m&&N!==A)&&this.setState(I)}this.runAnimation(Yh(Yh({},this.props),{},{from:A,begin:0}))}}}},{key:"componentWillUnmount",value:function(){this.mounted=!1;var i=this.props.onAnimationEnd;this.unSubscribe&&this.unSubscribe(),this.manager&&(this.manager.stop(),this.manager=null),this.stopJSAnimation&&this.stopJSAnimation(),i&&i()}},{key:"handleStyleChange",value:function(i){this.changeStyle(i)}},{key:"changeStyle",value:function(i){this.mounted&&this.setState({style:i})}},{key:"runJSAnimation",value:function(i){var o=this,c=i.from,a=i.to,m=i.duration,g=i.easing,_=i.begin,j=i.onAnimationEnd,N=i.onAnimationStart,C=jmt(c,a,hmt(g),m,this.changeStyle),P=function(){o.stopJSAnimation=C()};this.manager.start([N,_,P,m,j])}},{key:"runStepAnimation",value:function(i){var o=this,c=i.steps,a=i.begin,m=i.onAnimationStart,g=c[0],_=g.style,j=g.duration,N=j===void 0?0:j,C=function(A,I,O){if(O===0)return A;var R=I.duration,z=I.easing,W=z===void 0?"ease":z,V=I.style,K=I.properties,Q=I.onAnimationEnd,te=O>0?c[O-1]:I,X=K||Object.keys(V);if(typeof W=="function"||W==="spring")return[].concat(_B(A),[o.runJSAnimation.bind(o,{from:te.style,to:V,duration:R,easing:W}),R]);var ie=Wre(X,R,W),he=Yh(Yh(Yh({},te.style),V),{},{transition:ie});return[].concat(_B(A),[he,R,Q]).filter(emt)};return this.manager.start([m].concat(_B(c.reduce(C,[_,Math.max(N,a)])),[i.onAnimationEnd]))}},{key:"runAnimation",value:function(i){this.manager||(this.manager=Ypt());var o=i.begin,c=i.duration,a=i.attributeName,m=i.to,g=i.easing,_=i.onAnimationStart,j=i.onAnimationEnd,N=i.steps,C=i.children,P=this.manager;if(this.unSubscribe=P.subscribe(this.handleStyleChange),typeof g=="function"||typeof C=="function"||g==="spring"){this.runJSAnimation(i);return}if(N.length>1){this.runStepAnimation(i);return}var A=a?WC({},a,m):m,I=Wre(Object.keys(A),c,g);P.start([_,o,Yh(Yh({},A),{},{transition:I}),c,j])}},{key:"render",value:function(){var i=this.props,o=i.children;i.begin;var c=i.duration;i.attributeName,i.easing;var a=i.isActive;i.steps,i.from,i.to,i.canBegin,i.onAnimationEnd,i.shouldReAnimate,i.onAnimationReStart;var m=Nmt(i,Smt),g=D.Children.count(o),_=this.state.style;if(typeof o=="function")return o(_);if(!a||g===0||c<=0)return o;var j=function(C){var P=C.props,A=P.style,I=A===void 0?{}:A,O=P.className,R=D.cloneElement(C,Yh(Yh({},m),{},{style:Yh(Yh({},I),_),className:O}));return R};return g===1?j(D.Children.only(o)):Ve.createElement("div",null,D.Children.map(o,function(N){return j(N)}))}}]),r}(D.PureComponent);Qm.displayName="Animate";Qm.defaultProps={begin:0,duration:1e3,from:"",to:"",attributeName:"",easing:"ease",isActive:!0,canBegin:!0,steps:[],onAnimationEnd:function(){},onAnimationStart:function(){}};Qm.propTypes={from:va.oneOfType([va.object,va.string]),to:va.oneOfType([va.object,va.string]),attributeName:va.string,duration:va.number,begin:va.number,easing:va.oneOfType([va.string,va.func]),steps:va.arrayOf(va.shape({duration:va.number.isRequired,style:va.object.isRequired,easing:va.oneOfType([va.oneOf(["ease","ease-in","ease-out","ease-in-out","linear"]),va.func]),properties:va.arrayOf("string"),onAnimationEnd:va.func})),children:va.oneOfType([va.node,va.func]),isActive:va.bool,canBegin:va.bool,onAnimationEnd:va.func,shouldReAnimate:va.bool,onAnimationStart:va.func,onAnimationReStart:va.func};function Wk(t){"@babel/helpers - typeof";return Wk=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Wk(t)}function mR(){return mR=Object.assign?Object.assign.bind():function(t){for(var e=1;et.length)&&(e=t.length);for(var r=0,n=new Array(e);r=0?1:-1,m=n>=0?1:-1,g=i>=0&&n>=0||i<0&&n<0?1:0,_;if(c>0&&o instanceof Array){for(var j=[0,0,0,0],N=0,C=4;Nc?c:o[N];_="M".concat(e,",").concat(r+a*j[0]),j[0]>0&&(_+="A ".concat(j[0],",").concat(j[0],",0,0,").concat(g,",").concat(e+m*j[0],",").concat(r)),_+="L ".concat(e+n-m*j[1],",").concat(r),j[1]>0&&(_+="A ".concat(j[1],",").concat(j[1],",0,0,").concat(g,`, `).concat(e+n,",").concat(r+a*j[1])),_+="L ".concat(e+n,",").concat(r+i-a*j[2]),j[2]>0&&(_+="A ".concat(j[2],",").concat(j[2],",0,0,").concat(g,`, `).concat(e+n-m*j[2],",").concat(r+i)),_+="L ".concat(e+m*j[3],",").concat(r+i),j[3]>0&&(_+="A ".concat(j[3],",").concat(j[3],",0,0,").concat(g,`, `).concat(e,",").concat(r+i-a*j[3])),_+="Z"}else if(c>0&&o===+o&&o>0){var P=Math.min(c,o);_="M ".concat(e,",").concat(r+a*P,` A `).concat(P,",").concat(P,",0,0,").concat(g,",").concat(e+m*P,",").concat(r,` L `).concat(e+n-m*P,",").concat(r,` A `).concat(P,",").concat(P,",0,0,").concat(g,",").concat(e+n,",").concat(r+a*P,` L `).concat(e+n,",").concat(r+i-a*P,` A `).concat(P,",").concat(P,",0,0,").concat(g,",").concat(e+n-m*P,",").concat(r+i,` L `).concat(e+m*P,",").concat(r+i,` A `).concat(P,",").concat(P,",0,0,").concat(g,",").concat(e,",").concat(r+i-a*P," Z")}else _="M ".concat(e,",").concat(r," h ").concat(n," v ").concat(i," h ").concat(-n," Z");return _},Wmt=function(e,r){if(!e||!r)return!1;var n=e.x,i=e.y,o=r.x,c=r.y,a=r.width,m=r.height;if(Math.abs(a)>0&&Math.abs(m)>0){var g=Math.min(o,o+a),_=Math.max(o,o+a),j=Math.min(c,c+m),N=Math.max(c,c+m);return n>=g&&n<=_&&i>=j&&i<=N}return!1},Gmt={x:0,y:0,width:0,height:0,radius:0,isAnimationActive:!1,isUpdateAnimationActive:!1,animationBegin:0,animationDuration:1500,animationEasing:"ease"},_W=function(e){var r=ene(ene({},Gmt),e),n=D.useRef(),i=D.useState(-1),o=Fmt(i,2),c=o[0],a=o[1];D.useEffect(function(){if(n.current&&n.current.getTotalLength)try{var W=n.current.getTotalLength();W&&a(W)}catch{}},[]);var m=r.x,g=r.y,_=r.width,j=r.height,N=r.radius,C=r.className,P=r.animationEasing,A=r.animationDuration,I=r.animationBegin,O=r.isAnimationActive,R=r.isUpdateAnimationActive;if(m!==+m||g!==+g||_!==+_||j!==+j||_===0||j===0)return null;var z=Ci("recharts-rectangle",C);return R?Ve.createElement(Qm,{canBegin:c>0,from:{width:_,height:j,x:m,y:g},to:{width:_,height:j,x:m,y:g},duration:A,animationEasing:P,isActive:R},function(W){var V=W.width,K=W.height,Q=W.x,te=W.y;return Ve.createElement(Qm,{canBegin:c>0,from:"0px ".concat(c===-1?1:c,"px"),to:"".concat(c,"px 0px"),attributeName:"strokeDasharray",begin:I,duration:A,isActive:O,easing:P},Ve.createElement("path",mR({},Ks(r,!0),{className:z,d:tne(Q,te,V,K,N),ref:n})))}):Ve.createElement("path",mR({},Ks(r,!0),{className:z,d:tne(m,g,_,j,N)}))},Kmt=["points","className","baseLinePoints","connectNulls"];function Uw(){return Uw=Object.assign?Object.assign.bind():function(t){for(var e=1;e=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function Ymt(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}function rne(t){return egt(t)||Jmt(t)||Qmt(t)||Xmt()}function Xmt(){throw new TypeError(`Invalid attempt to spread non-iterable instance. In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Qmt(t,e){if(t){if(typeof t=="string")return vV(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set")return Array.from(t);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return vV(t,e)}}function Jmt(t){if(typeof Symbol<"u"&&t[Symbol.iterator]!=null||t["@@iterator"]!=null)return Array.from(t)}function egt(t){if(Array.isArray(t))return vV(t)}function vV(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r0&&arguments[0]!==void 0?arguments[0]:[],r=[[]];return e.forEach(function(n){nne(n)?r[r.length-1].push(n):r[r.length-1].length>0&&r.push([])}),nne(e[0])&&r[r.length-1].push(e[0]),r[r.length-1].length<=0&&(r=r.slice(0,-1)),r},C2=function(e,r){var n=tgt(e);r&&(n=[n.reduce(function(o,c){return[].concat(rne(o),rne(c))},[])]);var i=n.map(function(o){return o.reduce(function(c,a,m){return"".concat(c).concat(m===0?"M":"L").concat(a.x,",").concat(a.y)},"")}).join("");return n.length===1?"".concat(i,"Z"):i},rgt=function(e,r,n){var i=C2(e,n);return"".concat(i.slice(-1)==="Z"?i.slice(0,-1):i,"L").concat(C2(r.reverse(),n).slice(1))},ngt=function(e){var r=e.points,n=e.className,i=e.baseLinePoints,o=e.connectNulls,c=Zmt(e,Kmt);if(!r||!r.length)return null;var a=Ci("recharts-polygon",n);if(i&&i.length){var m=c.stroke&&c.stroke!=="none",g=rgt(r,i,o);return Ve.createElement("g",{className:a},Ve.createElement("path",Uw({},Ks(c,!0),{fill:g.slice(-1)==="Z"?c.fill:"none",stroke:"none",d:g})),m?Ve.createElement("path",Uw({},Ks(c,!0),{fill:"none",d:C2(r,o)})):null,m?Ve.createElement("path",Uw({},Ks(c,!0),{fill:"none",d:C2(i,o)})):null)}var _=C2(r,o);return Ve.createElement("path",Uw({},Ks(c,!0),{fill:_.slice(-1)==="Z"?c.fill:"none",className:a,d:_}))};function _V(){return _V=Object.assign?Object.assign.bind():function(t){for(var e=1;e=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function ugt(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}var dgt=function(e,r,n,i,o,c){return"M".concat(e,",").concat(o,"v").concat(i,"M").concat(c,",").concat(r,"h").concat(n)},hgt=function(e){var r=e.x,n=r===void 0?0:r,i=e.y,o=i===void 0?0:i,c=e.top,a=c===void 0?0:c,m=e.left,g=m===void 0?0:m,_=e.width,j=_===void 0?0:_,N=e.height,C=N===void 0?0:N,P=e.className,A=cgt(e,sgt),I=igt({x:n,y:o,top:a,left:g,width:j,height:C},A);return!hn(n)||!hn(o)||!hn(j)||!hn(C)||!hn(a)||!hn(g)?null:Ve.createElement("path",bV({},Ks(I,!0),{className:Ci("recharts-cross",P),d:dgt(n,o,j,C,a,g)}))},fgt=FL,pgt=x_e,mgt=Lp;function ggt(t,e){return t&&t.length?fgt(t,mgt(e),pgt):void 0}var ygt=ggt;const xgt=sa(ygt);var vgt=FL,_gt=Lp,bgt=v_e;function wgt(t,e){return t&&t.length?vgt(t,_gt(e),bgt):void 0}var jgt=wgt;const Sgt=sa(jgt);var Ngt=["cx","cy","angle","ticks","axisLine"],Cgt=["ticks","tick","angle","tickFormatter","stroke"];function dj(t){"@babel/helpers - typeof";return dj=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},dj(t)}function k2(){return k2=Object.assign?Object.assign.bind():function(t){for(var e=1;e=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function kgt(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}function Tgt(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function one(t,e){for(var r=0;rune?c=i==="outer"?"start":"end":o<-une?c=i==="outer"?"end":"start":c="middle",c}},{key:"renderAxisLine",value:function(){var n=this.props,i=n.cx,o=n.cy,c=n.radius,a=n.axisLine,m=n.axisLineType,g=Pv(Pv({},Ks(this.props,!1)),{},{fill:"none"},Ks(a,!1));if(m==="circle")return Ve.createElement(bW,Vv({className:"recharts-polar-angle-axis-line"},g,{cx:i,cy:o,r:c}));var _=this.props.ticks,j=_.map(function(N){return Ga(i,o,c,N.coordinate)});return Ve.createElement(ngt,Vv({className:"recharts-polar-angle-axis-line"},g,{points:j}))}},{key:"renderTicks",value:function(){var n=this,i=this.props,o=i.ticks,c=i.tick,a=i.tickLine,m=i.tickFormatter,g=i.stroke,_=Ks(this.props,!1),j=Ks(c,!1),N=Pv(Pv({},_),{},{fill:"none"},Ks(a,!1)),C=o.map(function(P,A){var I=n.getTickLineCoord(P),O=n.getTickTextAnchor(P),R=Pv(Pv(Pv({textAnchor:O},_),{},{stroke:"none",fill:g},j),{},{index:A,payload:P,x:I.x2,y:I.y2});return Ve.createElement(Na,Vv({className:Ci("recharts-polar-angle-axis-tick",G_e(c)),key:"tick-".concat(P.coordinate)},G_(n.props,P,A)),a&&Ve.createElement("line",Vv({className:"recharts-polar-angle-axis-tick-line"},N,I)),c&&e.renderTickItem(c,R,m?m(P.value,A):P.value))});return Ve.createElement(Na,{className:"recharts-polar-angle-axis-ticks"},C)}},{key:"render",value:function(){var n=this.props,i=n.ticks,o=n.radius,c=n.axisLine;return o<=0||!i||!i.length?null:Ve.createElement(Na,{className:Ci("recharts-polar-angle-axis",this.props.className)},c&&this.renderAxisLine(),this.renderTicks())}}],[{key:"renderTickItem",value:function(n,i,o){var c;return Ve.isValidElement(n)?c=Ve.cloneElement(n,i):ti(n)?c=n(i):c=Ve.createElement(K_,Vv({},i,{className:"recharts-polar-angle-axis-tick-value"}),o),c}}])}(D.PureComponent);GL(KL,"displayName","PolarAngleAxis");GL(KL,"axisType","angleAxis");GL(KL,"defaultProps",{type:"category",angleAxisId:0,scale:"auto",cx:0,cy:0,orientation:"outer",axisLine:!0,tickLine:!0,tickSize:8,tick:!0,hide:!1,allowDuplicatedCategory:!0});var Vgt=pve,qgt=Vgt(Object.getPrototypeOf,Object),Hgt=qgt,Wgt=lg,Ggt=Hgt,Kgt=cg,Zgt="[object Object]",Ygt=Function.prototype,Xgt=Object.prototype,d0e=Ygt.toString,Qgt=Xgt.hasOwnProperty,Jgt=d0e.call(Object);function eyt(t){if(!Kgt(t)||Wgt(t)!=Zgt)return!1;var e=Ggt(t);if(e===null)return!0;var r=Qgt.call(e,"constructor")&&e.constructor;return typeof r=="function"&&r instanceof r&&d0e.call(r)==Jgt}var tyt=eyt;const ryt=sa(tyt);var nyt=lg,syt=cg,iyt="[object Boolean]";function ayt(t){return t===!0||t===!1||syt(t)&&nyt(t)==iyt}var oyt=ayt;const lyt=sa(oyt);function Kk(t){"@babel/helpers - typeof";return Kk=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Kk(t)}function xR(){return xR=Object.assign?Object.assign.bind():function(t){for(var e=1;et.length)&&(e=t.length);for(var r=0,n=new Array(e);r0,from:{upperWidth:0,lowerWidth:0,height:N,x:m,y:g},to:{upperWidth:_,lowerWidth:j,height:N,x:m,y:g},duration:A,animationEasing:P,isActive:O},function(z){var W=z.upperWidth,V=z.lowerWidth,K=z.height,Q=z.x,te=z.y;return Ve.createElement(Qm,{canBegin:c>0,from:"0px ".concat(c===-1?1:c,"px"),to:"".concat(c,"px 0px"),attributeName:"strokeDasharray",begin:I,duration:A,easing:P},Ve.createElement("path",xR({},Ks(r,!0),{className:R,d:pne(Q,te,W,V,K),ref:n})))}):Ve.createElement("g",null,Ve.createElement("path",xR({},Ks(r,!0),{className:R,d:pne(m,g,_,j,N)})))},vyt=["option","shapeType","propTransformer","activeClassName","isActive"];function Zk(t){"@babel/helpers - typeof";return Zk=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Zk(t)}function _yt(t,e){if(t==null)return{};var r=byt(t,e),n,i;if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);for(i=0;i=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function byt(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}function mne(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function vR(t){for(var e=1;e0?_d(z,"paddingAngle",0):0;if(V){var Q=uy(V.endAngle-V.startAngle,z.endAngle-z.startAngle),te=qa(qa({},z),{},{startAngle:R+K,endAngle:R+Q(A)+K});I.push(te),R=te.endAngle}else{var X=z.endAngle,ie=z.startAngle,he=uy(0,X-ie),xe=he(A),pe=qa(qa({},z),{},{startAngle:R+K,endAngle:R+xe+K});I.push(pe),R=pe.endAngle}}),Ve.createElement(Na,null,n.renderSectorsStatically(I))})}},{key:"attachKeyboardHandlers",value:function(n){var i=this;n.onkeydown=function(o){if(!o.altKey)switch(o.key){case"ArrowLeft":{var c=++i.state.sectorToFocus%i.sectorRefs.length;i.sectorRefs[c].focus(),i.setState({sectorToFocus:c});break}case"ArrowRight":{var a=--i.state.sectorToFocus<0?i.sectorRefs.length-1:i.state.sectorToFocus%i.sectorRefs.length;i.sectorRefs[a].focus(),i.setState({sectorToFocus:a});break}case"Escape":{i.sectorRefs[i.state.sectorToFocus].blur(),i.setState({sectorToFocus:0});break}}}}},{key:"renderSectors",value:function(){var n=this.props,i=n.sectors,o=n.isAnimationActive,c=this.state.prevSectors;return o&&i&&i.length&&(!c||!$L(c,i))?this.renderSectorsWithAnimation():this.renderSectorsStatically(i)}},{key:"componentDidMount",value:function(){this.pieRef&&this.attachKeyboardHandlers(this.pieRef)}},{key:"render",value:function(){var n=this,i=this.props,o=i.hide,c=i.sectors,a=i.className,m=i.label,g=i.cx,_=i.cy,j=i.innerRadius,N=i.outerRadius,C=i.isAnimationActive,P=this.state.isAnimationFinished;if(o||!c||!c.length||!hn(g)||!hn(_)||!hn(j)||!hn(N))return null;var A=Ci("recharts-pie",a);return Ve.createElement(Na,{tabIndex:this.props.rootTabIndex,className:A,ref:function(O){n.pieRef=O}},this.renderSectors(),m&&this.renderLabels(c),Vl.renderCallByParent(this.props,null,!1),(!C||P)&&ex.renderCallByParent(this.props,c,!1))}}],[{key:"getDerivedStateFromProps",value:function(n,i){return i.prevIsAnimationActive!==n.isAnimationActive?{prevIsAnimationActive:n.isAnimationActive,prevAnimationId:n.animationId,curSectors:n.sectors,prevSectors:[],isAnimationFinished:!0}:n.isAnimationActive&&n.animationId!==i.prevAnimationId?{prevAnimationId:n.animationId,curSectors:n.sectors,prevSectors:i.curSectors,isAnimationFinished:!0}:n.sectors!==i.curSectors?{curSectors:n.sectors,isAnimationFinished:!0}:null}},{key:"getTextAnchor",value:function(n,i){return n>i?"start":n=360?R:R-1)*m,W=I-R*C-z,V=i.reduce(function(te,X){var ie=Mc(X,O,0);return te+(hn(ie)?ie:0)},0),K;if(V>0){var Q;K=i.map(function(te,X){var ie=Mc(te,O,0),he=Mc(te,_,X),xe=(hn(ie)?ie:0)/V,pe;X?pe=Q.endAngle+nu(A)*m*(ie!==0?1:0):pe=c;var ve=pe+nu(A)*((ie!==0?C:0)+xe*W),ge=(pe+ve)/2,ke=(P.innerRadius+P.outerRadius)/2,Ce=[{name:he,value:ie,payload:te,dataKey:O,type:N}],Se=Ga(P.cx,P.cy,ke,ge);return Q=qa(qa(qa({percent:xe,cornerRadius:o,name:he,tooltipPayload:Ce,midAngle:ge,middleRadius:ke,tooltipPosition:Se},te),P),{},{value:Mc(te,O),startAngle:pe,endAngle:ve,payload:te,paddingAngle:nu(A)*m}),Q})}return qa(qa({},P),{},{sectors:K,data:i})});var Uyt=Math.ceil,Vyt=Math.max;function qyt(t,e,r,n){for(var i=-1,o=Vyt(Uyt((e-t)/(r||1)),0),c=Array(o);o--;)c[n?o:++i]=t,t+=r;return c}var Hyt=qyt,Wyt=Mve,vne=1/0,Gyt=17976931348623157e292;function Kyt(t){if(!t)return t===0?t:0;if(t=Wyt(t),t===vne||t===-vne){var e=t<0?-1:1;return e*Gyt}return t===t?t:0}var m0e=Kyt,Zyt=Hyt,Yyt=AL,bB=m0e;function Xyt(t){return function(e,r,n){return n&&typeof n!="number"&&Yyt(e,r,n)&&(r=n=void 0),e=bB(e),r===void 0?(r=e,e=0):r=bB(r),n=n===void 0?e0&&n.handleDrag(i.changedTouches[0])}),sd(n,"handleDragEnd",function(){n.setState({isTravellerMoving:!1,isSlideMoving:!1},function(){var i=n.props,o=i.endIndex,c=i.onDragEnd,a=i.startIndex;c==null||c({endIndex:o,startIndex:a})}),n.detachDragEndListener()}),sd(n,"handleLeaveWrapper",function(){(n.state.isTravellerMoving||n.state.isSlideMoving)&&(n.leaveTimer=window.setTimeout(n.handleDragEnd,n.props.leaveTimeOut))}),sd(n,"handleEnterSlideOrTraveller",function(){n.setState({isTextActive:!0})}),sd(n,"handleLeaveSlideOrTraveller",function(){n.setState({isTextActive:!1})}),sd(n,"handleSlideDragStart",function(i){var o=Sne(i)?i.changedTouches[0]:i;n.setState({isTravellerMoving:!1,isSlideMoving:!0,slideMoveStartX:o.pageX}),n.attachDragEndListener()}),n.travellerDragStartHandlers={startX:n.handleTravellerDragStart.bind(n,"startX"),endX:n.handleTravellerDragStart.bind(n,"endX")},n.state={},n}return dxt(e,t),oxt(e,[{key:"componentWillUnmount",value:function(){this.leaveTimer&&(clearTimeout(this.leaveTimer),this.leaveTimer=null),this.detachDragEndListener()}},{key:"getIndex",value:function(n){var i=n.startX,o=n.endX,c=this.state.scaleValues,a=this.props,m=a.gap,g=a.data,_=g.length-1,j=Math.min(i,o),N=Math.max(i,o),C=e.getIndexInRange(c,j),P=e.getIndexInRange(c,N);return{startIndex:C-C%m,endIndex:P===_?_:P-P%m}}},{key:"getTextOfTick",value:function(n){var i=this.props,o=i.data,c=i.tickFormatter,a=i.dataKey,m=Mc(o[n],a,n);return ti(c)?c(m,n):m}},{key:"attachDragEndListener",value:function(){window.addEventListener("mouseup",this.handleDragEnd,!0),window.addEventListener("touchend",this.handleDragEnd,!0),window.addEventListener("mousemove",this.handleDrag,!0)}},{key:"detachDragEndListener",value:function(){window.removeEventListener("mouseup",this.handleDragEnd,!0),window.removeEventListener("touchend",this.handleDragEnd,!0),window.removeEventListener("mousemove",this.handleDrag,!0)}},{key:"handleSlideDrag",value:function(n){var i=this.state,o=i.slideMoveStartX,c=i.startX,a=i.endX,m=this.props,g=m.x,_=m.width,j=m.travellerWidth,N=m.startIndex,C=m.endIndex,P=m.onChange,A=n.pageX-o;A>0?A=Math.min(A,g+_-j-a,g+_-j-c):A<0&&(A=Math.max(A,g-c,g-a));var I=this.getIndex({startX:c+A,endX:a+A});(I.startIndex!==N||I.endIndex!==C)&&P&&P(I),this.setState({startX:c+A,endX:a+A,slideMoveStartX:n.pageX})}},{key:"handleTravellerDragStart",value:function(n,i){var o=Sne(i)?i.changedTouches[0]:i;this.setState({isSlideMoving:!1,isTravellerMoving:!0,movingTravellerId:n,brushMoveStartX:o.pageX}),this.attachDragEndListener()}},{key:"handleTravellerMove",value:function(n){var i=this.state,o=i.brushMoveStartX,c=i.movingTravellerId,a=i.endX,m=i.startX,g=this.state[c],_=this.props,j=_.x,N=_.width,C=_.travellerWidth,P=_.onChange,A=_.gap,I=_.data,O={startX:this.state.startX,endX:this.state.endX},R=n.pageX-o;R>0?R=Math.min(R,j+N-C-g):R<0&&(R=Math.max(R,j-g)),O[c]=g+R;var z=this.getIndex(O),W=z.startIndex,V=z.endIndex,K=function(){var te=I.length-1;return c==="startX"&&(a>m?W%A===0:V%A===0)||am?V%A===0:W%A===0)||a>m&&V===te};this.setState(sd(sd({},c,g+R),"brushMoveStartX",n.pageX),function(){P&&K()&&P(z)})}},{key:"handleTravellerMoveKeyboard",value:function(n,i){var o=this,c=this.state,a=c.scaleValues,m=c.startX,g=c.endX,_=this.state[i],j=a.indexOf(_);if(j!==-1){var N=j+n;if(!(N===-1||N>=a.length)){var C=a[N];i==="startX"&&C>=g||i==="endX"&&C<=m||this.setState(sd({},i,C),function(){o.props.onChange(o.getIndex({startX:o.state.startX,endX:o.state.endX}))})}}}},{key:"renderBackground",value:function(){var n=this.props,i=n.x,o=n.y,c=n.width,a=n.height,m=n.fill,g=n.stroke;return Ve.createElement("rect",{stroke:g,fill:m,x:i,y:o,width:c,height:a})}},{key:"renderPanorama",value:function(){var n=this.props,i=n.x,o=n.y,c=n.width,a=n.height,m=n.data,g=n.children,_=n.padding,j=D.Children.only(g);return j?Ve.cloneElement(j,{x:i,y:o,width:c,height:a,margin:_,compact:!0,data:m}):null}},{key:"renderTravellerLayer",value:function(n,i){var o,c,a=this,m=this.props,g=m.y,_=m.travellerWidth,j=m.height,N=m.traveller,C=m.ariaLabel,P=m.data,A=m.startIndex,I=m.endIndex,O=Math.max(n,this.props.x),R=wB(wB({},Ks(this.props,!1)),{},{x:O,y:g,width:_,height:j}),z=C||"Min value: ".concat((o=P[A])===null||o===void 0?void 0:o.name,", Max value: ").concat((c=P[I])===null||c===void 0?void 0:c.name);return Ve.createElement(Na,{tabIndex:0,role:"slider","aria-label":z,"aria-valuenow":n,className:"recharts-brush-traveller",onMouseEnter:this.handleEnterSlideOrTraveller,onMouseLeave:this.handleLeaveSlideOrTraveller,onMouseDown:this.travellerDragStartHandlers[i],onTouchStart:this.travellerDragStartHandlers[i],onKeyDown:function(V){["ArrowLeft","ArrowRight"].includes(V.key)&&(V.preventDefault(),V.stopPropagation(),a.handleTravellerMoveKeyboard(V.key==="ArrowRight"?1:-1,i))},onFocus:function(){a.setState({isTravellerFocused:!0})},onBlur:function(){a.setState({isTravellerFocused:!1})},style:{cursor:"col-resize"}},e.renderTraveller(N,R))}},{key:"renderSlide",value:function(n,i){var o=this.props,c=o.y,a=o.height,m=o.stroke,g=o.travellerWidth,_=Math.min(n,i)+g,j=Math.max(Math.abs(i-n)-g,0);return Ve.createElement("rect",{className:"recharts-brush-slide",onMouseEnter:this.handleEnterSlideOrTraveller,onMouseLeave:this.handleLeaveSlideOrTraveller,onMouseDown:this.handleSlideDragStart,onTouchStart:this.handleSlideDragStart,style:{cursor:"move"},stroke:"none",fill:m,fillOpacity:.2,x:_,y:c,width:j,height:a})}},{key:"renderText",value:function(){var n=this.props,i=n.startIndex,o=n.endIndex,c=n.y,a=n.height,m=n.travellerWidth,g=n.stroke,_=this.state,j=_.startX,N=_.endX,C=5,P={pointerEvents:"none",fill:g};return Ve.createElement(Na,{className:"recharts-brush-texts"},Ve.createElement(K_,wR({textAnchor:"end",verticalAnchor:"middle",x:Math.min(j,N)-C,y:c+a/2},P),this.getTextOfTick(i)),Ve.createElement(K_,wR({textAnchor:"start",verticalAnchor:"middle",x:Math.max(j,N)+m+C,y:c+a/2},P),this.getTextOfTick(o)))}},{key:"render",value:function(){var n=this.props,i=n.data,o=n.className,c=n.children,a=n.x,m=n.y,g=n.width,_=n.height,j=n.alwaysShowText,N=this.state,C=N.startX,P=N.endX,A=N.isTextActive,I=N.isSlideMoving,O=N.isTravellerMoving,R=N.isTravellerFocused;if(!i||!i.length||!hn(a)||!hn(m)||!hn(g)||!hn(_)||g<=0||_<=0)return null;var z=Ci("recharts-brush",o),W=Ve.Children.count(c)===1,V=ixt("userSelect","none");return Ve.createElement(Na,{className:z,onMouseLeave:this.handleLeaveWrapper,onTouchMove:this.handleTouchMove,style:V},this.renderBackground(),W&&this.renderPanorama(),this.renderSlide(C,P),this.renderTravellerLayer(C,"startX"),this.renderTravellerLayer(P,"endX"),(A||I||O||R||j)&&this.renderText())}}],[{key:"renderDefaultTraveller",value:function(n){var i=n.x,o=n.y,c=n.width,a=n.height,m=n.stroke,g=Math.floor(o+a/2)-1;return Ve.createElement(Ve.Fragment,null,Ve.createElement("rect",{x:i,y:o,width:c,height:a,fill:m,stroke:"none"}),Ve.createElement("line",{x1:i+1,y1:g,x2:i+c-1,y2:g,fill:"none",stroke:"#fff"}),Ve.createElement("line",{x1:i+1,y1:g+2,x2:i+c-1,y2:g+2,fill:"none",stroke:"#fff"}))}},{key:"renderTraveller",value:function(n,i){var o;return Ve.isValidElement(n)?o=Ve.cloneElement(n,i):ti(n)?o=n(i):o=e.renderDefaultTraveller(i),o}},{key:"getDerivedStateFromProps",value:function(n,i){var o=n.data,c=n.width,a=n.x,m=n.travellerWidth,g=n.updateId,_=n.startIndex,j=n.endIndex;if(o!==i.prevData||g!==i.prevUpdateId)return wB({prevData:o,prevTravellerWidth:m,prevUpdateId:g,prevX:a,prevWidth:c},o&&o.length?fxt({data:o,width:c,x:a,travellerWidth:m,startIndex:_,endIndex:j}):{scale:null,scaleValues:null});if(i.scale&&(c!==i.prevWidth||a!==i.prevX||m!==i.prevTravellerWidth)){i.scale.range([a,a+c-m]);var N=i.scale.domain().map(function(C){return i.scale(C)});return{prevData:o,prevTravellerWidth:m,prevUpdateId:g,prevX:a,prevWidth:c,startX:i.scale(n.startIndex),endX:i.scale(n.endIndex),scaleValues:N}}return null}},{key:"getIndexInRange",value:function(n,i){for(var o=n.length,c=0,a=o-1;a-c>1;){var m=Math.floor((c+a)/2);n[m]>i?a=m:c=m}return i>=n[a]?a:c}}])}(D.PureComponent);sd(mj,"displayName","Brush");sd(mj,"defaultProps",{height:40,travellerWidth:5,gap:1,fill:"#fff",stroke:"#666",padding:{top:1,right:1,bottom:1,left:1},leaveTimeOut:1e3,alwaysShowText:!1});var pxt=WH;function mxt(t,e){var r;return pxt(t,function(n,i,o){return r=e(n,i,o),!r}),!!r}var gxt=mxt,yxt=ave,xxt=Lp,vxt=gxt,_xt=Wu,bxt=AL;function wxt(t,e,r){var n=_xt(t)?yxt:vxt;return r&&bxt(t,e,r)&&(e=void 0),n(t,xxt(e))}var jxt=wxt;const Sxt=sa(jxt);var vp=function(e,r){var n=e.alwaysShow,i=e.ifOverflow;return n&&(i="extendDomain"),i===r},Nne=Tve;function Nxt(t,e,r){e=="__proto__"&&Nne?Nne(t,e,{configurable:!0,enumerable:!0,value:r,writable:!0}):t[e]=r}var Cxt=Nxt,kxt=Cxt,Txt=Cve,Ext=Lp;function Axt(t,e){var r={};return e=Ext(e),Txt(t,function(n,i,o){kxt(r,i,e(n,i,o))}),r}var Pxt=Axt;const Ixt=sa(Pxt);function Mxt(t,e){for(var r=-1,n=t==null?0:t.length;++r=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function Yxt(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}function Xxt(t,e){var r=t.x,n=t.y,i=Zxt(t,Hxt),o="".concat(r),c=parseInt(o,10),a="".concat(n),m=parseInt(a,10),g="".concat(e.height||i.height),_=parseInt(g,10),j="".concat(e.width||i.width),N=parseInt(j,10);return PC(PC(PC(PC(PC({},e),i),c?{x:c}:{}),m?{y:m}:{}),{},{height:_,width:N,name:e.name,radius:e.radius})}function kne(t){return Ve.createElement(h0e,CV({shapeType:"rectangle",propTransformer:Xxt,activeClassName:"recharts-active-bar"},t))}var Qxt=function(e){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;return function(n,i){if(typeof e=="number")return e;var o=hn(n)||wXe(n);return o?e(n,i):(o||Y_(),r)}},Jxt=["value","background"],_0e;function gj(t){"@babel/helpers - typeof";return gj=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},gj(t)}function evt(t,e){if(t==null)return{};var r=tvt(t,e),n,i;if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);for(i=0;i=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function tvt(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}function SR(){return SR=Object.assign?Object.assign.bind():function(t){for(var e=1;e0&&Math.abs(ge)0&&Math.abs(ve)0&&(pe=Math.min((pt||0)-(ve[nt-1]||0),pe))}),Number.isFinite(pe)){var ge=pe/xe,ke=A.layout==="vertical"?n.height:n.width;if(A.padding==="gap"&&(Q=ge*ke/2),A.padding==="no-gap"){var Ce=su(e.barCategoryGap,ge*ke),Se=ge*ke/2;Q=Se-Ce-(Se-Ce)/ke*Ce}}}i==="xAxis"?te=[n.left+(z.left||0)+(Q||0),n.left+n.width-(z.right||0)-(Q||0)]:i==="yAxis"?te=m==="horizontal"?[n.top+n.height-(z.bottom||0),n.top+(z.top||0)]:[n.top+(z.top||0)+(Q||0),n.top+n.height-(z.bottom||0)-(Q||0)]:te=A.range,V&&(te=[te[1],te[0]]);var je=B_e(A,o,N),et=je.scale,bt=je.realScaleType;et.domain(O).range(te),$_e(et);var _e=U_e(et,cf(cf({},A),{},{realScaleType:bt}));i==="xAxis"?(he=I==="top"&&!W||I==="bottom"&&W,X=n.left,ie=j[K]-he*A.height):i==="yAxis"&&(he=I==="left"&&!W||I==="right"&&W,X=j[K]-he*A.width,ie=n.top);var Ye=cf(cf(cf({},A),_e),{},{realScaleType:bt,x:X,y:ie,scale:et,width:i==="xAxis"?n.width:A.width,height:i==="yAxis"?n.height:A.height});return Ye.bandSize=cR(Ye,_e),!A.hide&&i==="xAxis"?j[K]+=(he?-1:1)*Ye.height:A.hide||(j[K]+=(he?-1:1)*Ye.width),cf(cf({},C),{},XL({},P,Ye))},{})},S0e=function(e,r){var n=e.x,i=e.y,o=r.x,c=r.y;return{x:Math.min(n,o),y:Math.min(i,c),width:Math.abs(o-n),height:Math.abs(c-i)}},fvt=function(e){var r=e.x1,n=e.y1,i=e.x2,o=e.y2;return S0e({x:r,y:n},{x:i,y:o})},N0e=function(){function t(e){cvt(this,t),this.scale=e}return uvt(t,[{key:"domain",get:function(){return this.scale.domain}},{key:"range",get:function(){return this.scale.range}},{key:"rangeMin",get:function(){return this.range()[0]}},{key:"rangeMax",get:function(){return this.range()[1]}},{key:"bandwidth",get:function(){return this.scale.bandwidth}},{key:"apply",value:function(r){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=n.bandAware,o=n.position;if(r!==void 0){if(o)switch(o){case"start":return this.scale(r);case"middle":{var c=this.bandwidth?this.bandwidth()/2:0;return this.scale(r)+c}case"end":{var a=this.bandwidth?this.bandwidth():0;return this.scale(r)+a}default:return this.scale(r)}if(i){var m=this.bandwidth?this.bandwidth()/2:0;return this.scale(r)+m}return this.scale(r)}}},{key:"isInRange",value:function(r){var n=this.range(),i=n[0],o=n[n.length-1];return i<=o?r>=i&&r<=o:r>=o&&r<=i}}],[{key:"create",value:function(r){return new t(r)}}])}();XL(N0e,"EPS",1e-4);var wW=function(e){var r=Object.keys(e).reduce(function(n,i){return cf(cf({},n),{},XL({},i,N0e.create(e[i])))},{});return cf(cf({},r),{},{apply:function(i){var o=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},c=o.bandAware,a=o.position;return Ixt(i,function(m,g){return r[g].apply(m,{bandAware:c,position:a})})},isInRange:function(i){return v0e(i,function(o,c){return r[c].isInRange(o)})}})};function pvt(t){return(t%180+180)%180}var mvt=function(e){var r=e.width,n=e.height,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,o=pvt(i),c=o*Math.PI/180,a=Math.atan(n/r),m=c>a&&c-1?i[o?e[c]:c]:void 0}}var _vt=vvt,bvt=m0e;function wvt(t){var e=bvt(t),r=e%1;return e===e?r?e-r:e:0}var jvt=wvt,Svt=_ve,Nvt=Lp,Cvt=jvt,kvt=Math.max;function Tvt(t,e,r){var n=t==null?0:t.length;if(!n)return-1;var i=r==null?0:Cvt(r);return i<0&&(i=kvt(n+i,0)),Svt(t,Nvt(e),i)}var Evt=Tvt,Avt=_vt,Pvt=Evt,Ivt=Avt(Pvt),Mvt=Ivt;const Ovt=sa(Mvt);var Rvt=TYe(function(t){return{x:t.left,y:t.top,width:t.width,height:t.height}},function(t){return["l",t.left,"t",t.top,"w",t.width,"h",t.height].join("")}),jW=D.createContext(void 0),SW=D.createContext(void 0),C0e=D.createContext(void 0),k0e=D.createContext({}),T0e=D.createContext(void 0),E0e=D.createContext(0),A0e=D.createContext(0),Ine=function(e){var r=e.state,n=r.xAxisMap,i=r.yAxisMap,o=r.offset,c=e.clipPathId,a=e.children,m=e.width,g=e.height,_=Rvt(o);return Ve.createElement(jW.Provider,{value:n},Ve.createElement(SW.Provider,{value:i},Ve.createElement(k0e.Provider,{value:o},Ve.createElement(C0e.Provider,{value:_},Ve.createElement(T0e.Provider,{value:c},Ve.createElement(E0e.Provider,{value:g},Ve.createElement(A0e.Provider,{value:m},a)))))))},Dvt=function(){return D.useContext(T0e)},P0e=function(e){var r=D.useContext(jW);r==null&&Y_();var n=r[e];return n==null&&Y_(),n},Lvt=function(){var e=D.useContext(jW);return yy(e)},Fvt=function(){var e=D.useContext(SW),r=Ovt(e,function(n){return v0e(n.domain,Number.isFinite)});return r||yy(e)},I0e=function(e){var r=D.useContext(SW);r==null&&Y_();var n=r[e];return n==null&&Y_(),n},zvt=function(){var e=D.useContext(C0e);return e},Bvt=function(){return D.useContext(k0e)},NW=function(){return D.useContext(A0e)},CW=function(){return D.useContext(E0e)};function yj(t){"@babel/helpers - typeof";return yj=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},yj(t)}function $vt(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function Uvt(t,e){for(var r=0;rt.length)&&(e=t.length);for(var r=0,n=new Array(e);rt*i)return!1;var o=r();return t*(e-t*o/2-n)>=0&&t*(e+t*o/2-i)<=0}function j_t(t,e){return z0e(t,e+1)}function S_t(t,e,r,n,i){for(var o=(n||[]).slice(),c=e.start,a=e.end,m=0,g=1,_=c,j=function(){var P=n==null?void 0:n[m];if(P===void 0)return{v:z0e(n,g)};var A=m,I,O=function(){return I===void 0&&(I=r(P,A)),I},R=P.coordinate,z=m===0||ER(t,R,O,_,a);z||(m=0,_=c,g+=1),z&&(_=R+t*(O()/2+i),m+=g)},N;g<=o.length;)if(N=j(),N)return N.v;return[]}function eT(t){"@babel/helpers - typeof";return eT=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},eT(t)}function Bne(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function Ac(t){for(var e=1;e0?C.coordinate-I*t:C.coordinate})}else o[N]=C=Ac(Ac({},C),{},{tickCoord:C.coordinate});var O=ER(t,C.tickCoord,A,a,m);O&&(m=C.tickCoord-t*(A()/2+i),o[N]=Ac(Ac({},C),{},{isShow:!0}))},_=c-1;_>=0;_--)g(_);return o}function E_t(t,e,r,n,i,o){var c=(n||[]).slice(),a=c.length,m=e.start,g=e.end;if(o){var _=n[a-1],j=r(_,a-1),N=t*(_.coordinate+t*j/2-g);c[a-1]=_=Ac(Ac({},_),{},{tickCoord:N>0?_.coordinate-N*t:_.coordinate});var C=ER(t,_.tickCoord,function(){return j},m,g);C&&(g=_.tickCoord-t*(j/2+i),c[a-1]=Ac(Ac({},_),{},{isShow:!0}))}for(var P=o?a-1:a,A=function(R){var z=c[R],W,V=function(){return W===void 0&&(W=r(z,R)),W};if(R===0){var K=t*(z.coordinate-t*V()/2-m);c[R]=z=Ac(Ac({},z),{},{tickCoord:K<0?z.coordinate-K*t:z.coordinate})}else c[R]=z=Ac(Ac({},z),{},{tickCoord:z.coordinate});var Q=ER(t,z.tickCoord,V,m,g);Q&&(m=z.tickCoord+t*(V()/2+i),c[R]=Ac(Ac({},z),{},{isShow:!0}))},I=0;I=2?nu(i[1].coordinate-i[0].coordinate):1,O=w_t(o,I,C);return m==="equidistantPreserveStart"?S_t(I,O,A,i,c):(m==="preserveStart"||m==="preserveStartEnd"?N=E_t(I,O,A,i,c,m==="preserveStartEnd"):N=T_t(I,O,A,i,c),N.filter(function(R){return R.isShow}))}var A_t=["viewBox"],P_t=["viewBox"],I_t=["ticks"];function _j(t){"@babel/helpers - typeof";return _j=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_j(t)}function qw(){return qw=Object.assign?Object.assign.bind():function(t){for(var e=1;e=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function M_t(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}function O_t(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function Une(t,e){for(var r=0;r0?m(this.props):m(C)),c<=0||a<=0||!P||!P.length?null:Ve.createElement(Na,{className:Ci("recharts-cartesian-axis",g),ref:function(I){n.layerReference=I}},o&&this.renderAxisLine(),this.renderTicks(P,this.state.fontSize,this.state.letterSpacing),Vl.renderCallByParent(this.props))}}],[{key:"renderTickItem",value:function(n,i,o){var c,a=Ci(i.className,"recharts-cartesian-axis-tick-value");return Ve.isValidElement(n)?c=Ve.cloneElement(n,_l(_l({},i),{},{className:a})):ti(n)?c=n(_l(_l({},i),{},{className:a})):c=Ve.createElement(K_,qw({},i,{className:"recharts-cartesian-axis-tick-value"}),o),c}}])}(D.Component);AW(aS,"displayName","CartesianAxis");AW(aS,"defaultProps",{x:0,y:0,width:0,height:0,viewBox:{x:0,y:0,width:0,height:0},orientation:"bottom",ticks:[],stroke:"#666",tickLine:!0,axisLine:!0,tick:!0,mirror:!1,minTickGap:5,tickSize:6,tickMargin:2,interval:"preserveEnd"});var $_t=["x1","y1","x2","y2","key"],U_t=["offset"];function X_(t){"@babel/helpers - typeof";return X_=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},X_(t)}function Vne(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function Ic(t){for(var e=1;e=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function W_t(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}var G_t=function(e){var r=e.fill;if(!r||r==="none")return null;var n=e.fillOpacity,i=e.x,o=e.y,c=e.width,a=e.height,m=e.ry;return Ve.createElement("rect",{x:i,y:o,ry:m,width:c,height:a,stroke:"none",fill:r,fillOpacity:n,className:"recharts-cartesian-grid-bg"})};function U0e(t,e){var r;if(Ve.isValidElement(t))r=Ve.cloneElement(t,e);else if(ti(t))r=t(e);else{var n=e.x1,i=e.y1,o=e.x2,c=e.y2,a=e.key,m=qne(e,$_t),g=Ks(m,!1);g.offset;var _=qne(g,U_t);r=Ve.createElement("line",n_({},_,{x1:n,y1:i,x2:o,y2:c,fill:"none",key:a}))}return r}function K_t(t){var e=t.x,r=t.width,n=t.horizontal,i=n===void 0?!0:n,o=t.horizontalPoints;if(!i||!o||!o.length)return null;var c=o.map(function(a,m){var g=Ic(Ic({},t),{},{x1:e,y1:a,x2:e+r,y2:a,key:"line-".concat(m),index:m});return U0e(i,g)});return Ve.createElement("g",{className:"recharts-cartesian-grid-horizontal"},c)}function Z_t(t){var e=t.y,r=t.height,n=t.vertical,i=n===void 0?!0:n,o=t.verticalPoints;if(!i||!o||!o.length)return null;var c=o.map(function(a,m){var g=Ic(Ic({},t),{},{x1:a,y1:e,x2:a,y2:e+r,key:"line-".concat(m),index:m});return U0e(i,g)});return Ve.createElement("g",{className:"recharts-cartesian-grid-vertical"},c)}function Y_t(t){var e=t.horizontalFill,r=t.fillOpacity,n=t.x,i=t.y,o=t.width,c=t.height,a=t.horizontalPoints,m=t.horizontal,g=m===void 0?!0:m;if(!g||!e||!e.length)return null;var _=a.map(function(N){return Math.round(N+i-i)}).sort(function(N,C){return N-C});i!==_[0]&&_.unshift(0);var j=_.map(function(N,C){var P=!_[C+1],A=P?i+c-N:_[C+1]-N;if(A<=0)return null;var I=C%e.length;return Ve.createElement("rect",{key:"react-".concat(C),y:N,x:n,height:A,width:o,stroke:"none",fill:e[I],fillOpacity:r,className:"recharts-cartesian-grid-bg"})});return Ve.createElement("g",{className:"recharts-cartesian-gridstripes-horizontal"},j)}function X_t(t){var e=t.vertical,r=e===void 0?!0:e,n=t.verticalFill,i=t.fillOpacity,o=t.x,c=t.y,a=t.width,m=t.height,g=t.verticalPoints;if(!r||!n||!n.length)return null;var _=g.map(function(N){return Math.round(N+o-o)}).sort(function(N,C){return N-C});o!==_[0]&&_.unshift(0);var j=_.map(function(N,C){var P=!_[C+1],A=P?o+a-N:_[C+1]-N;if(A<=0)return null;var I=C%n.length;return Ve.createElement("rect",{key:"react-".concat(C),x:N,y:c,width:A,height:m,stroke:"none",fill:n[I],fillOpacity:i,className:"recharts-cartesian-grid-bg"})});return Ve.createElement("g",{className:"recharts-cartesian-gridstripes-vertical"},j)}var Q_t=function(e,r){var n=e.xAxis,i=e.width,o=e.height,c=e.offset;return z_e(EW(Ic(Ic(Ic({},aS.defaultProps),n),{},{ticks:Mm(n,!0),viewBox:{x:0,y:0,width:i,height:o}})),c.left,c.left+c.width,r)},J_t=function(e,r){var n=e.yAxis,i=e.width,o=e.height,c=e.offset;return z_e(EW(Ic(Ic(Ic({},aS.defaultProps),n),{},{ticks:Mm(n,!0),viewBox:{x:0,y:0,width:i,height:o}})),c.top,c.top+c.height,r)},xw={horizontal:!0,vertical:!0,stroke:"#ccc",fill:"none",verticalFill:[],horizontalFill:[]};function V0e(t){var e,r,n,i,o,c,a=NW(),m=CW(),g=Bvt(),_=Ic(Ic({},t),{},{stroke:(e=t.stroke)!==null&&e!==void 0?e:xw.stroke,fill:(r=t.fill)!==null&&r!==void 0?r:xw.fill,horizontal:(n=t.horizontal)!==null&&n!==void 0?n:xw.horizontal,horizontalFill:(i=t.horizontalFill)!==null&&i!==void 0?i:xw.horizontalFill,vertical:(o=t.vertical)!==null&&o!==void 0?o:xw.vertical,verticalFill:(c=t.verticalFill)!==null&&c!==void 0?c:xw.verticalFill,x:hn(t.x)?t.x:g.left,y:hn(t.y)?t.y:g.top,width:hn(t.width)?t.width:g.width,height:hn(t.height)?t.height:g.height}),j=_.x,N=_.y,C=_.width,P=_.height,A=_.syncWithTicks,I=_.horizontalValues,O=_.verticalValues,R=Lvt(),z=Fvt();if(!hn(C)||C<=0||!hn(P)||P<=0||!hn(j)||j!==+j||!hn(N)||N!==+N)return null;var W=_.verticalCoordinatesGenerator||Q_t,V=_.horizontalCoordinatesGenerator||J_t,K=_.horizontalPoints,Q=_.verticalPoints;if((!K||!K.length)&&ti(V)){var te=I&&I.length,X=V({yAxis:z?Ic(Ic({},z),{},{ticks:te?I:z.ticks}):void 0,width:a,height:m,offset:g},te?!0:A);wf(Array.isArray(X),"horizontalCoordinatesGenerator should return Array but instead it returned [".concat(X_(X),"]")),Array.isArray(X)&&(K=X)}if((!Q||!Q.length)&&ti(W)){var ie=O&&O.length,he=W({xAxis:R?Ic(Ic({},R),{},{ticks:ie?O:R.ticks}):void 0,width:a,height:m,offset:g},ie?!0:A);wf(Array.isArray(he),"verticalCoordinatesGenerator should return Array but instead it returned [".concat(X_(he),"]")),Array.isArray(he)&&(Q=he)}return Ve.createElement("g",{className:"recharts-cartesian-grid"},Ve.createElement(G_t,{fill:_.fill,fillOpacity:_.fillOpacity,x:_.x,y:_.y,width:_.width,height:_.height,ry:_.ry}),Ve.createElement(K_t,n_({},_,{offset:g,horizontalPoints:K,xAxis:R,yAxis:z})),Ve.createElement(Z_t,n_({},_,{offset:g,verticalPoints:Q,xAxis:R,yAxis:z})),Ve.createElement(Y_t,n_({},_,{horizontalPoints:K})),Ve.createElement(X_t,n_({},_,{verticalPoints:Q})))}V0e.displayName="CartesianGrid";function bj(t){"@babel/helpers - typeof";return bj=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},bj(t)}function e0t(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function t0t(t,e){for(var r=0;rt.length)&&(e=t.length);for(var r=0,n=new Array(e);r=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function $0t(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}function U0t(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function V0t(t,e){for(var r=0;rt.length)&&(e=t.length);for(var r=0,n=new Array(e);r0?c:e&&e.length&&hn(i)&&hn(o)?e.slice(i,o+1):[]};function nbe(t){return t==="number"?[0,"auto"]:void 0}var VV=function(e,r,n,i){var o=e.graphicalItems,c=e.tooltipAxis,a=s4(r,e);return n<0||!o||!o.length||n>=a.length?null:o.reduce(function(m,g){var _,j=(_=g.props.data)!==null&&_!==void 0?_:r;j&&e.dataStartIndex+e.dataEndIndex!==0&&e.dataEndIndex-e.dataStartIndex>=n&&(j=j.slice(e.dataStartIndex,e.dataEndIndex+1));var N;if(c.dataKey&&!c.allowDuplicatedCategory){var C=j===void 0?a:j;N=gU(C,c.dataKey,i)}else N=j&&j[n]||a[n];return N?[].concat(Sj(m),[q_e(g,N)]):m},[])},Yne=function(e,r,n,i){var o=i||{x:e.chartX,y:e.chartY},c=tbt(o,n),a=e.orderedTooltipTicks,m=e.tooltipAxis,g=e.tooltipTicks,_=Dht(c,a,g,m);if(_>=0&&g){var j=g[_]&&g[_].value,N=VV(e,r,_,j),C=rbt(n,a,_,o);return{activeTooltipIndex:_,activeLabel:j,activePayload:N,activeCoordinate:C}}return null},nbt=function(e,r){var n=r.axes,i=r.graphicalItems,o=r.axisType,c=r.axisIdKey,a=r.stackGroups,m=r.dataStartIndex,g=r.dataEndIndex,_=e.layout,j=e.children,N=e.stackOffset,C=F_e(_,o);return n.reduce(function(P,A){var I,O=A.type.defaultProps!==void 0?Rr(Rr({},A.type.defaultProps),A.props):A.props,R=O.type,z=O.dataKey,W=O.allowDataOverflow,V=O.allowDuplicatedCategory,K=O.scale,Q=O.ticks,te=O.includeHidden,X=O[c];if(P[X])return P;var ie=s4(e.data,{graphicalItems:i.filter(function(_e){var Ye,pt=c in _e.props?_e.props[c]:(Ye=_e.type.defaultProps)===null||Ye===void 0?void 0:Ye[c];return pt===X}),dataStartIndex:m,dataEndIndex:g}),he=ie.length,xe,pe,ve;E0t(O.domain,W,R)&&(xe=sV(O.domain,null,W),C&&(R==="number"||K!=="auto")&&(ve=S2(ie,z,"category")));var ge=nbe(R);if(!xe||xe.length===0){var ke,Ce=(ke=O.domain)!==null&&ke!==void 0?ke:ge;if(z){if(xe=S2(ie,z,R),R==="category"&&C){var Se=SXe(xe);V&&Se?(pe=xe,xe=bR(0,he)):V||(xe=bre(Ce,xe,A).reduce(function(_e,Ye){return _e.indexOf(Ye)>=0?_e:[].concat(Sj(_e),[Ye])},[]))}else if(R==="category")V?xe=xe.filter(function(_e){return _e!==""&&!$i(_e)}):xe=bre(Ce,xe,A).reduce(function(_e,Ye){return _e.indexOf(Ye)>=0||Ye===""||$i(Ye)?_e:[].concat(Sj(_e),[Ye])},[]);else if(R==="number"){var je=$ht(ie,i.filter(function(_e){var Ye,pt,nt=c in _e.props?_e.props[c]:(Ye=_e.type.defaultProps)===null||Ye===void 0?void 0:Ye[c],Qt="hide"in _e.props?_e.props.hide:(pt=_e.type.defaultProps)===null||pt===void 0?void 0:pt.hide;return nt===X&&(te||!Qt)}),z,o,_);je&&(xe=je)}C&&(R==="number"||K!=="auto")&&(ve=S2(ie,z,"category"))}else C?xe=bR(0,he):a&&a[X]&&a[X].hasStack&&R==="number"?xe=N==="expand"?[0,1]:V_e(a[X].stackGroups,m,g):xe=L_e(ie,i.filter(function(_e){var Ye=c in _e.props?_e.props[c]:_e.type.defaultProps[c],pt="hide"in _e.props?_e.props.hide:_e.type.defaultProps.hide;return Ye===X&&(te||!pt)}),R,_,!0);if(R==="number")xe=BV(j,xe,X,o,Q),Ce&&(xe=sV(Ce,xe,W));else if(R==="category"&&Ce){var et=Ce,bt=xe.every(function(_e){return et.indexOf(_e)>=0});bt&&(xe=et)}}return Rr(Rr({},P),{},zs({},X,Rr(Rr({},O),{},{axisType:o,domain:xe,categoricalDomain:ve,duplicateDomain:pe,originalDomain:(I=O.domain)!==null&&I!==void 0?I:ge,isCategorical:C,layout:_})))},{})},sbt=function(e,r){var n=r.graphicalItems,i=r.Axis,o=r.axisType,c=r.axisIdKey,a=r.stackGroups,m=r.dataStartIndex,g=r.dataEndIndex,_=e.layout,j=e.children,N=s4(e.data,{graphicalItems:n,dataStartIndex:m,dataEndIndex:g}),C=N.length,P=F_e(_,o),A=-1;return n.reduce(function(I,O){var R=O.type.defaultProps!==void 0?Rr(Rr({},O.type.defaultProps),O.props):O.props,z=R[c],W=nbe("number");if(!I[z]){A++;var V;return P?V=bR(0,C):a&&a[z]&&a[z].hasStack?(V=V_e(a[z].stackGroups,m,g),V=BV(j,V,z,o)):(V=sV(W,L_e(N,n.filter(function(K){var Q,te,X=c in K.props?K.props[c]:(Q=K.type.defaultProps)===null||Q===void 0?void 0:Q[c],ie="hide"in K.props?K.props.hide:(te=K.type.defaultProps)===null||te===void 0?void 0:te.hide;return X===z&&!ie}),"number",_),i.defaultProps.allowDataOverflow),V=BV(j,V,z,o)),Rr(Rr({},I),{},zs({},z,Rr(Rr({axisType:o},i.defaultProps),{},{hide:!0,orientation:_d(J0t,"".concat(o,".").concat(A%2),null),domain:V,originalDomain:W,isCategorical:P,layout:_})))}return I},{})},ibt=function(e,r){var n=r.axisType,i=n===void 0?"xAxis":n,o=r.AxisComp,c=r.graphicalItems,a=r.stackGroups,m=r.dataStartIndex,g=r.dataEndIndex,_=e.children,j="".concat(i,"Id"),N=dh(_,o),C={};return N&&N.length?C=nbt(e,{axes:N,graphicalItems:c,axisType:i,axisIdKey:j,stackGroups:a,dataStartIndex:m,dataEndIndex:g}):c&&c.length&&(C=sbt(e,{Axis:o,graphicalItems:c,axisType:i,axisIdKey:j,stackGroups:a,dataStartIndex:m,dataEndIndex:g})),C},abt=function(e){var r=yy(e),n=Mm(r,!1,!0);return{tooltipTicks:n,orderedTooltipTicks:GH(n,function(i){return i.coordinate}),tooltipAxis:r,tooltipAxisBandSize:cR(r,n)}},Xne=function(e){var r=e.children,n=e.defaultShowTooltip,i=od(r,mj),o=0,c=0;return e.data&&e.data.length!==0&&(c=e.data.length-1),i&&i.props&&(i.props.startIndex>=0&&(o=i.props.startIndex),i.props.endIndex>=0&&(c=i.props.endIndex)),{chartX:0,chartY:0,dataStartIndex:o,dataEndIndex:c,activeTooltipIndex:-1,isTooltipActive:!!n}},obt=function(e){return!e||!e.length?!1:e.some(function(r){var n=Lm(r&&r.type);return n&&n.indexOf("Bar")>=0})},Qne=function(e){return e==="horizontal"?{numericAxisName:"yAxis",cateAxisName:"xAxis"}:e==="vertical"?{numericAxisName:"xAxis",cateAxisName:"yAxis"}:e==="centric"?{numericAxisName:"radiusAxis",cateAxisName:"angleAxis"}:{numericAxisName:"angleAxis",cateAxisName:"radiusAxis"}},lbt=function(e,r){var n=e.props,i=e.graphicalItems,o=e.xAxisMap,c=o===void 0?{}:o,a=e.yAxisMap,m=a===void 0?{}:a,g=n.width,_=n.height,j=n.children,N=n.margin||{},C=od(j,mj),P=od(j,u1),A=Object.keys(m).reduce(function(V,K){var Q=m[K],te=Q.orientation;return!Q.mirror&&!Q.hide?Rr(Rr({},V),{},zs({},te,V[te]+Q.width)):V},{left:N.left||0,right:N.right||0}),I=Object.keys(c).reduce(function(V,K){var Q=c[K],te=Q.orientation;return!Q.mirror&&!Q.hide?Rr(Rr({},V),{},zs({},te,_d(V,"".concat(te))+Q.height)):V},{top:N.top||0,bottom:N.bottom||0}),O=Rr(Rr({},I),A),R=O.bottom;C&&(O.bottom+=C.props.height||mj.defaultProps.height),P&&r&&(O=zht(O,i,n,r));var z=g-O.left-O.right,W=_-O.top-O.bottom;return Rr(Rr({brushBottom:R},O),{},{width:Math.max(z,0),height:Math.max(W,0)})},cbt=function(e,r){if(r==="xAxis")return e[r].width;if(r==="yAxis")return e[r].height},sbe=function(e){var r=e.chartName,n=e.GraphicalChild,i=e.defaultTooltipEventType,o=i===void 0?"axis":i,c=e.validateTooltipEventTypes,a=c===void 0?["axis"]:c,m=e.axisComponents,g=e.legendContent,_=e.formatAxisMap,j=e.defaultProps,N=function(O,R){var z=R.graphicalItems,W=R.stackGroups,V=R.offset,K=R.updateId,Q=R.dataStartIndex,te=R.dataEndIndex,X=O.barSize,ie=O.layout,he=O.barGap,xe=O.barCategoryGap,pe=O.maxBarSize,ve=Qne(ie),ge=ve.numericAxisName,ke=ve.cateAxisName,Ce=obt(z),Se=[];return z.forEach(function(je,et){var bt=s4(O.data,{graphicalItems:[je],dataStartIndex:Q,dataEndIndex:te}),_e=je.type.defaultProps!==void 0?Rr(Rr({},je.type.defaultProps),je.props):je.props,Ye=_e.dataKey,pt=_e.maxBarSize,nt=_e["".concat(ge,"Id")],Qt=_e["".concat(ke,"Id")],gt={},Me=m.reduce(function(We,_t){var Gt=R["".concat(_t.axisType,"Map")],rr=_e["".concat(_t.axisType,"Id")];Gt&&Gt[rr]||_t.axisType==="zAxis"||Y_();var pr=Gt[rr];return Rr(Rr({},We),{},zs(zs({},_t.axisType,pr),"".concat(_t.axisType,"Ticks"),Mm(pr)))},gt),Oe=Me[ke],Ie=Me["".concat(ke,"Ticks")],Be=W&&W[nt]&&W[nt].hasStack&&Yht(je,W[nt].stackGroups),Pe=Lm(je.type).indexOf("Bar")>=0,ut=cR(Oe,Ie),jt=[],$t=Ce&&Lht({barSize:X,stackGroups:W,totalSize:cbt(Me,ke)});if(Pe){var Ht,Lt,Kt=$i(pt)?pe:pt,Ar=(Ht=(Lt=cR(Oe,Ie,!0))!==null&&Lt!==void 0?Lt:Kt)!==null&&Ht!==void 0?Ht:0;jt=Fht({barGap:he,barCategoryGap:xe,bandSize:Ar!==ut?Ar:ut,sizeList:$t[Qt],maxBarSize:Kt}),Ar!==ut&&(jt=jt.map(function(We){return Rr(Rr({},We),{},{position:Rr(Rr({},We.position),{},{offset:We.position.offset-Ar/2})})}))}var rt=je&&je.type&&je.type.getComposedData;rt&&Se.push({props:Rr(Rr({},rt(Rr(Rr({},Me),{},{displayedData:bt,props:O,dataKey:Ye,item:je,bandSize:ut,barPosition:jt,offset:V,stackedData:Be,layout:ie,dataStartIndex:Q,dataEndIndex:te}))),{},zs(zs(zs({key:je.key||"item-".concat(et)},ge,Me[ge]),ke,Me[ke]),"animationId",K)),childIndex:DXe(je,O.children),item:je})}),Se},C=function(O,R){var z=O.props,W=O.dataStartIndex,V=O.dataEndIndex,K=O.updateId;if(!mee({props:z}))return null;var Q=z.children,te=z.layout,X=z.stackOffset,ie=z.data,he=z.reverseStackOrder,xe=Qne(te),pe=xe.numericAxisName,ve=xe.cateAxisName,ge=dh(Q,n),ke=Kht(ie,ge,"".concat(pe,"Id"),"".concat(ve,"Id"),X,he),Ce=m.reduce(function(_e,Ye){var pt="".concat(Ye.axisType,"Map");return Rr(Rr({},_e),{},zs({},pt,ibt(z,Rr(Rr({},Ye),{},{graphicalItems:ge,stackGroups:Ye.axisType===pe&&ke,dataStartIndex:W,dataEndIndex:V}))))},{}),Se=lbt(Rr(Rr({},Ce),{},{props:z,graphicalItems:ge}),R==null?void 0:R.legendBBox);Object.keys(Ce).forEach(function(_e){Ce[_e]=_(z,Ce[_e],Se,_e.replace("Map",""),r)});var je=Ce["".concat(ve,"Map")],et=abt(je),bt=N(z,Rr(Rr({},Ce),{},{dataStartIndex:W,dataEndIndex:V,updateId:K,graphicalItems:ge,stackGroups:ke,offset:Se}));return Rr(Rr({formattedGraphicalItems:bt,graphicalItems:ge,offset:Se,stackGroups:ke},et),Ce)},P=function(I){function O(R){var z,W,V;return U0t(this,O),V=H0t(this,O,[R]),zs(V,"eventEmitterSymbol",Symbol("rechartsEventEmitter")),zs(V,"accessibilityManager",new T0t),zs(V,"handleLegendBBoxUpdate",function(K){if(K){var Q=V.state,te=Q.dataStartIndex,X=Q.dataEndIndex,ie=Q.updateId;V.setState(Rr({legendBBox:K},C({props:V.props,dataStartIndex:te,dataEndIndex:X,updateId:ie},Rr(Rr({},V.state),{},{legendBBox:K}))))}}),zs(V,"handleReceiveSyncEvent",function(K,Q,te){if(V.props.syncId===K){if(te===V.eventEmitterSymbol&&typeof V.props.syncMethod!="function")return;V.applySyncEvent(Q)}}),zs(V,"handleBrushChange",function(K){var Q=K.startIndex,te=K.endIndex;if(Q!==V.state.dataStartIndex||te!==V.state.dataEndIndex){var X=V.state.updateId;V.setState(function(){return Rr({dataStartIndex:Q,dataEndIndex:te},C({props:V.props,dataStartIndex:Q,dataEndIndex:te,updateId:X},V.state))}),V.triggerSyncEvent({dataStartIndex:Q,dataEndIndex:te})}}),zs(V,"handleMouseEnter",function(K){var Q=V.getMouseInfo(K);if(Q){var te=Rr(Rr({},Q),{},{isTooltipActive:!0});V.setState(te),V.triggerSyncEvent(te);var X=V.props.onMouseEnter;ti(X)&&X(te,K)}}),zs(V,"triggeredAfterMouseMove",function(K){var Q=V.getMouseInfo(K),te=Q?Rr(Rr({},Q),{},{isTooltipActive:!0}):{isTooltipActive:!1};V.setState(te),V.triggerSyncEvent(te);var X=V.props.onMouseMove;ti(X)&&X(te,K)}),zs(V,"handleItemMouseEnter",function(K){V.setState(function(){return{isTooltipActive:!0,activeItem:K,activePayload:K.tooltipPayload,activeCoordinate:K.tooltipPosition||{x:K.cx,y:K.cy}}})}),zs(V,"handleItemMouseLeave",function(){V.setState(function(){return{isTooltipActive:!1}})}),zs(V,"handleMouseMove",function(K){K.persist(),V.throttleTriggeredAfterMouseMove(K)}),zs(V,"handleMouseLeave",function(K){V.throttleTriggeredAfterMouseMove.cancel();var Q={isTooltipActive:!1};V.setState(Q),V.triggerSyncEvent(Q);var te=V.props.onMouseLeave;ti(te)&&te(Q,K)}),zs(V,"handleOuterEvent",function(K){var Q=RXe(K),te=_d(V.props,"".concat(Q));if(Q&&ti(te)){var X,ie;/.*touch.*/i.test(Q)?ie=V.getMouseInfo(K.changedTouches[0]):ie=V.getMouseInfo(K),te((X=ie)!==null&&X!==void 0?X:{},K)}}),zs(V,"handleClick",function(K){var Q=V.getMouseInfo(K);if(Q){var te=Rr(Rr({},Q),{},{isTooltipActive:!0});V.setState(te),V.triggerSyncEvent(te);var X=V.props.onClick;ti(X)&&X(te,K)}}),zs(V,"handleMouseDown",function(K){var Q=V.props.onMouseDown;if(ti(Q)){var te=V.getMouseInfo(K);Q(te,K)}}),zs(V,"handleMouseUp",function(K){var Q=V.props.onMouseUp;if(ti(Q)){var te=V.getMouseInfo(K);Q(te,K)}}),zs(V,"handleTouchMove",function(K){K.changedTouches!=null&&K.changedTouches.length>0&&V.throttleTriggeredAfterMouseMove(K.changedTouches[0])}),zs(V,"handleTouchStart",function(K){K.changedTouches!=null&&K.changedTouches.length>0&&V.handleMouseDown(K.changedTouches[0])}),zs(V,"handleTouchEnd",function(K){K.changedTouches!=null&&K.changedTouches.length>0&&V.handleMouseUp(K.changedTouches[0])}),zs(V,"handleDoubleClick",function(K){var Q=V.props.onDoubleClick;if(ti(Q)){var te=V.getMouseInfo(K);Q(te,K)}}),zs(V,"handleContextMenu",function(K){var Q=V.props.onContextMenu;if(ti(Q)){var te=V.getMouseInfo(K);Q(te,K)}}),zs(V,"triggerSyncEvent",function(K){V.props.syncId!==void 0&&SB.emit(NB,V.props.syncId,K,V.eventEmitterSymbol)}),zs(V,"applySyncEvent",function(K){var Q=V.props,te=Q.layout,X=Q.syncMethod,ie=V.state.updateId,he=K.dataStartIndex,xe=K.dataEndIndex;if(K.dataStartIndex!==void 0||K.dataEndIndex!==void 0)V.setState(Rr({dataStartIndex:he,dataEndIndex:xe},C({props:V.props,dataStartIndex:he,dataEndIndex:xe,updateId:ie},V.state)));else if(K.activeTooltipIndex!==void 0){var pe=K.chartX,ve=K.chartY,ge=K.activeTooltipIndex,ke=V.state,Ce=ke.offset,Se=ke.tooltipTicks;if(!Ce)return;if(typeof X=="function")ge=X(Se,K);else if(X==="value"){ge=-1;for(var je=0;je=0){var Be,Pe;if(pe.dataKey&&!pe.allowDuplicatedCategory){var ut=typeof pe.dataKey=="function"?Ie:"payload.".concat(pe.dataKey.toString());Be=gU(je,ut,ge),Pe=et&&bt&&gU(bt,ut,ge)}else Be=je==null?void 0:je[ve],Pe=et&&bt&&bt[ve];if(Qt||nt){var jt=K.props.activeIndex!==void 0?K.props.activeIndex:ve;return[D.cloneElement(K,Rr(Rr(Rr({},X.props),Me),{},{activeIndex:jt})),null,null]}if(!$i(Be))return[Oe].concat(Sj(V.renderActivePoints({item:X,activePoint:Be,basePoint:Pe,childIndex:ve,isRange:et})))}else{var $t,Ht=($t=V.getItemByXY(V.state.activeCoordinate))!==null&&$t!==void 0?$t:{graphicalItem:Oe},Lt=Ht.graphicalItem,Kt=Lt.item,Ar=Kt===void 0?K:Kt,rt=Lt.childIndex,We=Rr(Rr(Rr({},X.props),Me),{},{activeIndex:rt});return[D.cloneElement(Ar,We),null,null]}return et?[Oe,null,null]:[Oe,null]}),zs(V,"renderCustomized",function(K,Q,te){return D.cloneElement(K,Rr(Rr({key:"recharts-customized-".concat(te)},V.props),V.state))}),zs(V,"renderMap",{CartesianGrid:{handler:oI,once:!0},ReferenceArea:{handler:V.renderReferenceElement},ReferenceLine:{handler:oI},ReferenceDot:{handler:V.renderReferenceElement},XAxis:{handler:oI},YAxis:{handler:oI},Brush:{handler:V.renderBrush,once:!0},Bar:{handler:V.renderGraphicChild},Line:{handler:V.renderGraphicChild},Area:{handler:V.renderGraphicChild},Radar:{handler:V.renderGraphicChild},RadialBar:{handler:V.renderGraphicChild},Scatter:{handler:V.renderGraphicChild},Pie:{handler:V.renderGraphicChild},Funnel:{handler:V.renderGraphicChild},Tooltip:{handler:V.renderCursor,once:!0},PolarGrid:{handler:V.renderPolarGrid,once:!0},PolarAngleAxis:{handler:V.renderPolarAxis},PolarRadiusAxis:{handler:V.renderPolarAxis},Customized:{handler:V.renderCustomized}}),V.clipPathId="".concat((z=R.id)!==null&&z!==void 0?z:HT("recharts"),"-clip"),V.throttleTriggeredAfterMouseMove=Ove(V.triggeredAfterMouseMove,(W=R.throttleDelay)!==null&&W!==void 0?W:1e3/60),V.state={},V}return K0t(O,I),q0t(O,[{key:"componentDidMount",value:function(){var z,W;this.addListener(),this.accessibilityManager.setDetails({container:this.container,offset:{left:(z=this.props.margin.left)!==null&&z!==void 0?z:0,top:(W=this.props.margin.top)!==null&&W!==void 0?W:0},coordinateList:this.state.tooltipTicks,mouseHandlerCallback:this.triggeredAfterMouseMove,layout:this.props.layout}),this.displayDefaultTooltip()}},{key:"displayDefaultTooltip",value:function(){var z=this.props,W=z.children,V=z.data,K=z.height,Q=z.layout,te=od(W,lf);if(te){var X=te.props.defaultIndex;if(!(typeof X!="number"||X<0||X>this.state.tooltipTicks.length-1)){var ie=this.state.tooltipTicks[X]&&this.state.tooltipTicks[X].value,he=VV(this.state,V,X,ie),xe=this.state.tooltipTicks[X].coordinate,pe=(this.state.offset.top+K)/2,ve=Q==="horizontal",ge=ve?{x:xe,y:pe}:{y:xe,x:pe},ke=this.state.formattedGraphicalItems.find(function(Se){var je=Se.item;return je.type.name==="Scatter"});ke&&(ge=Rr(Rr({},ge),ke.props.points[X].tooltipPosition),he=ke.props.points[X].tooltipPayload);var Ce={activeTooltipIndex:X,isTooltipActive:!0,activeLabel:ie,activePayload:he,activeCoordinate:ge};this.setState(Ce),this.renderCursor(te),this.accessibilityManager.setIndex(X)}}}},{key:"getSnapshotBeforeUpdate",value:function(z,W){if(!this.props.accessibilityLayer)return null;if(this.state.tooltipTicks!==W.tooltipTicks&&this.accessibilityManager.setDetails({coordinateList:this.state.tooltipTicks}),this.props.layout!==z.layout&&this.accessibilityManager.setDetails({layout:this.props.layout}),this.props.margin!==z.margin){var V,K;this.accessibilityManager.setDetails({offset:{left:(V=this.props.margin.left)!==null&&V!==void 0?V:0,top:(K=this.props.margin.top)!==null&&K!==void 0?K:0}})}return null}},{key:"componentDidUpdate",value:function(z){xU([od(z.children,lf)],[od(this.props.children,lf)])||this.displayDefaultTooltip()}},{key:"componentWillUnmount",value:function(){this.removeListener(),this.throttleTriggeredAfterMouseMove.cancel()}},{key:"getTooltipEventType",value:function(){var z=od(this.props.children,lf);if(z&&typeof z.props.shared=="boolean"){var W=z.props.shared?"axis":"item";return a.indexOf(W)>=0?W:o}return o}},{key:"getMouseInfo",value:function(z){if(!this.container)return null;var W=this.container,V=W.getBoundingClientRect(),K=ult(V),Q={chartX:Math.round(z.pageX-K.left),chartY:Math.round(z.pageY-K.top)},te=V.width/W.offsetWidth||1,X=this.inRange(Q.chartX,Q.chartY,te);if(!X)return null;var ie=this.state,he=ie.xAxisMap,xe=ie.yAxisMap,pe=this.getTooltipEventType(),ve=Yne(this.state,this.props.data,this.props.layout,X);if(pe!=="axis"&&he&&xe){var ge=yy(he).scale,ke=yy(xe).scale,Ce=ge&&ge.invert?ge.invert(Q.chartX):null,Se=ke&&ke.invert?ke.invert(Q.chartY):null;return Rr(Rr({},Q),{},{xValue:Ce,yValue:Se},ve)}return ve?Rr(Rr({},Q),ve):null}},{key:"inRange",value:function(z,W){var V=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,K=this.props.layout,Q=z/V,te=W/V;if(K==="horizontal"||K==="vertical"){var X=this.state.offset,ie=Q>=X.left&&Q<=X.left+X.width&&te>=X.top&&te<=X.top+X.height;return ie?{x:Q,y:te}:null}var he=this.state,xe=he.angleAxisMap,pe=he.radiusAxisMap;if(xe&&pe){var ve=yy(xe);return Sre({x:Q,y:te},ve)}return null}},{key:"parseEventsOfWrapper",value:function(){var z=this.props.children,W=this.getTooltipEventType(),V=od(z,lf),K={};V&&W==="axis"&&(V.props.trigger==="click"?K={onClick:this.handleClick}:K={onMouseEnter:this.handleMouseEnter,onDoubleClick:this.handleDoubleClick,onMouseMove:this.handleMouseMove,onMouseLeave:this.handleMouseLeave,onTouchMove:this.handleTouchMove,onTouchStart:this.handleTouchStart,onTouchEnd:this.handleTouchEnd,onContextMenu:this.handleContextMenu});var Q=DO(this.props,this.handleOuterEvent);return Rr(Rr({},Q),K)}},{key:"addListener",value:function(){SB.on(NB,this.handleReceiveSyncEvent)}},{key:"removeListener",value:function(){SB.removeListener(NB,this.handleReceiveSyncEvent)}},{key:"filterFormatItem",value:function(z,W,V){for(var K=this.state.formattedGraphicalItems,Q=0,te=K.length;Q");return t}const obe=D.forwardRef(({id:t,className:e,children:r,config:n,...i},o)=>{const c=D.useId(),a=`chart-${t||c.replace(/:/g,"")}`;return s.jsx(ibe.Provider,{value:{config:n},children:s.jsxs("div",{"data-chart":a,ref:o,className:ar("flex aspect-video justify-center text-xs [&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-none [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-sector]:outline-none [&_.recharts-surface]:outline-none",e),...i,children:[s.jsx(fbt,{id:a,config:n}),s.jsx($U,{children:r})]})})});obe.displayName="Chart";const fbt=({id:t,config:e})=>{const r=Object.entries(e).filter(([n,i])=>i.theme||i.color);return r.length?s.jsx("style",{dangerouslySetInnerHTML:{__html:Object.entries(hbt).map(([n,i])=>` ${i} [data-chart=${t}] { ${r.map(([o,c])=>{var m;const a=((m=c.theme)==null?void 0:m[n])||c.color;return a?` --color-${o}: ${a};`:null}).join(` `)} } `).join(` `)}}):null},lbe=D.forwardRef(({active:t,payload:e,className:r,indicator:n="dot",hideLabel:i=!1,hideIndicator:o=!1,label:c,labelFormatter:a,labelClassName:m,formatter:g,color:_,nameKey:j,labelKey:N},C)=>{const{config:P}=abe(),A=D.useMemo(()=>{var V;if(i||!(e!=null&&e.length))return null;const[O]=e,R=`${N||O.dataKey||O.name||"value"}`,z=qV(P,O,R),W=!N&&typeof c=="string"?((V=P[c])==null?void 0:V.label)||c:z==null?void 0:z.label;return a?s.jsx("div",{className:ar("font-medium",m),children:a(W,e)}):W?s.jsx("div",{className:ar("font-medium",m),children:W}):null},[c,a,e,i,m,P,N]);if(!t||!(e!=null&&e.length))return null;const I=e.length===1&&n!=="dot";return s.jsxs("div",{ref:C,className:ar("grid min-w-[8rem] items-start gap-1.5 rounded-lg border border-border/50 bg-background px-2.5 py-1.5 text-xs shadow-xl",r),children:[I?null:A,s.jsx("div",{className:"grid gap-1.5",children:e.map((O,R)=>{const z=`${j||O.name||O.dataKey||"value"}`,W=qV(P,O,z),V=_||O.payload.fill||O.color;return s.jsx("div",{className:ar("flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground",n==="dot"&&"items-center"),children:g&&(O==null?void 0:O.value)!==void 0&&O.name?g(O.value,O.name,O,R,O.payload):s.jsxs(s.Fragment,{children:[W!=null&&W.icon?s.jsx(W.icon,{}):!o&&s.jsx("div",{className:ar("shrink-0 rounded-[2px] border-[--color-border] bg-[--color-bg]",{"h-2.5 w-2.5":n==="dot","w-1":n==="line","w-0 border-[1.5px] border-dashed bg-transparent":n==="dashed","my-0.5":I&&n==="dashed"}),style:{"--color-bg":V,"--color-border":V}}),s.jsxs("div",{className:ar("flex flex-1 justify-between leading-none",I?"items-end":"items-center"),children:[s.jsxs("div",{className:"grid gap-1.5",children:[I?A:null,s.jsx("span",{className:"text-muted-foreground",children:(W==null?void 0:W.label)||O.name})]}),O.value&&s.jsx("span",{className:"font-mono font-medium tabular-nums text-foreground",children:O.value.toLocaleString()})]})]})},O.dataKey)})})]})});lbe.displayName="ChartTooltip";const pbt=D.forwardRef(({className:t,hideIcon:e=!1,payload:r,verticalAlign:n="bottom",nameKey:i},o)=>{const{config:c}=abe();return r!=null&&r.length?s.jsx("div",{ref:o,className:ar("flex items-center justify-center gap-4",n==="top"?"pb-3":"pt-3",t),children:r.map(a=>{const m=`${i||a.dataKey||"value"}`,g=qV(c,a,m);return s.jsxs("div",{className:ar("flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground"),children:[g!=null&&g.icon&&!e?s.jsx(g.icon,{}):s.jsx("div",{className:"h-2 w-2 shrink-0 rounded-[2px]",style:{backgroundColor:a.color}}),g==null?void 0:g.label]},a.value)})}):null});pbt.displayName="ChartLegend";function qV(t,e,r){if(typeof e!="object"||e===null)return;const n="payload"in e&&typeof e.payload=="object"&&e.payload!==null?e.payload:void 0;let i=r;return r in e&&typeof e[r]=="string"?i=e[r]:n&&r in n&&typeof n[r]=="string"&&(i=n[r]),i in t?t[i]:t[r]}const lI=["hsl(var(--primary))","hsl(var(--secondary))","hsl(210, 70%, 50%)","hsl(170, 60%, 45%)","hsl(280, 60%, 55%)","hsl(30, 70%, 50%)","hsl(340, 65%, 55%)","hsl(200, 65%, 50%)"];function cbe({stats:t,year:e}){const r=t.transactionsByMonth.some(i=>i.count>0),n=t.leadSourceBreakdown.length>0;return!r&&!n?s.jsx(at,{children:s.jsx(ct,{className:"py-12 text-center text-muted-foreground",children:"Add transactions to see your performance charts"})}):s.jsxs("div",{className:"grid gap-6",children:[r&&s.jsxs(at,{className:"overflow-hidden",children:[s.jsx(xr,{children:s.jsx(wr,{className:"text-base",children:"Transactions by Month"})}),s.jsx(ct,{className:"overflow-hidden",children:s.jsx(obe,{config:{count:{label:"Transactions",color:"hsl(var(--primary))"}},className:"h-[250px]",children:s.jsx($U,{width:"100%",height:"100%",children:s.jsxs(ubt,{data:t.transactionsByMonth,margin:{top:5,right:10,left:0,bottom:5},children:[s.jsx(V0e,{strokeDasharray:"3 3",className:"stroke-muted"}),s.jsx(r4,{dataKey:"month",tick:{fontSize:11},className:"fill-muted-foreground",interval:0}),s.jsx(n4,{allowDecimals:!1,tick:{fontSize:12},className:"fill-muted-foreground",width:30}),s.jsx(lf,{content:s.jsx(lbe,{})}),s.jsx(f0,{dataKey:"count",fill:"hsl(var(--primary))",radius:[4,4,0,0],name:"Transactions"})]})})})})]}),n&&s.jsxs(at,{children:[s.jsx(xr,{children:s.jsx(wr,{className:"text-base",children:"Lead Sources"})}),s.jsxs(ct,{children:[s.jsx("div",{className:"h-[250px]",children:s.jsx($U,{width:"100%",height:"100%",children:s.jsxs(dbt,{children:[s.jsx(dg,{data:t.leadSourceBreakdown,dataKey:"count",nameKey:"name",cx:"50%",cy:"50%",outerRadius:80,label:({name:i,percent:o})=>o>.05?`${i} (${(o*100).toFixed(0)}%)`:"",labelLine:!1,children:t.leadSourceBreakdown.map((i,o)=>s.jsx(PL,{fill:lI[o%lI.length]},`cell-${o}`))}),s.jsx(lf,{formatter:(i,o)=>[`${i} deals`,o]})]})})}),s.jsx("div",{className:"flex flex-wrap gap-2 mt-2 justify-center",children:t.leadSourceBreakdown.slice(0,6).map((i,o)=>s.jsxs("div",{className:"flex items-center gap-1 text-xs",children:[s.jsx("div",{className:"w-3 h-3 rounded-sm",style:{backgroundColor:lI[o%lI.length]}}),s.jsx("span",{className:"text-muted-foreground",children:i.name})]},i.name))})]})]})]})}const mbt=Ej("relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground",{variants:{variant:{default:"bg-background text-foreground",destructive:"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive"}},defaultVariants:{variant:"default"}}),ube=D.forwardRef(({className:t,variant:e,...r},n)=>s.jsx("div",{ref:n,role:"alert",className:ar(mbt({variant:e}),t),...r}));ube.displayName="Alert";const gbt=D.forwardRef(({className:t,...e},r)=>s.jsx("h5",{ref:r,className:ar("mb-1 font-medium leading-none tracking-tight",t),...e}));gbt.displayName="AlertTitle";const dbe=D.forwardRef(({className:t,...e},r)=>s.jsx("div",{ref:r,className:ar("text-sm [&_p]:leading-relaxed",t),...e}));dbe.displayName="AlertDescription";const ybt=["property_address","city","state","zip","transaction_type","close_date","sale_price","commission_amount","lead_source","client_type","is_win","notes"];function xbt({open:t,onOpenChange:e}){const[r,n]=D.useState([]),[i,o]=D.useState(!1),[c,a]=D.useState(0),{data:m}=kq(),{data:g}=sg(),_=Eq(),j=()=>{const O=ybt.join(","),R=["123 Main St","Dallas","TX","75001","buyer","2024-06-15","450000","13500","Referral","Past Client","yes","Great transaction!"].join(","),z=`${O} ${R}`,W=new Blob([z],{type:"text/csv"}),V=URL.createObjectURL(W),K=document.createElement("a");K.href=V,K.download="transaction-import-template.csv",K.click(),URL.revokeObjectURL(V)},N=O=>{const R=O.split(` `).filter(W=>W.trim());if(R.length<2)return[];const z=R[0].split(",").map(W=>W.trim().toLowerCase().replace(/['"]/g,""));return R.slice(1).map((W,V)=>{var ge,ke,Ce,Se;const K=[];let Q="",te=!1;for(const je of W)je==='"'?te=!te:je===","&&!te?(K.push(Q.trim()),Q=""):Q+=je;K.push(Q.trim());const X=je=>{var bt;const et=z.indexOf(je);return et>=0?(bt=K[et])==null?void 0:bt.replace(/^["']|["']$/g,"").trim():""},ie=(ge=X("transaction_type"))==null?void 0:ge.toLowerCase(),he=(ke=X("sale_price"))==null?void 0:ke.replace(/[$,]/g,""),xe=(Ce=X("commission_amount"))==null?void 0:Ce.replace(/[$,]/g,""),pe=(Se=X("is_win"))==null?void 0:Se.toLowerCase();let ve;return X("property_address")?["buyer","seller"].includes(ie)?X("close_date")?(!he||isNaN(Number(he)))&&(ve="Invalid sale price"):ve="Missing close date":ve='Transaction type must be "buyer" or "seller"':ve="Missing property address",{property_address:X("property_address"),city:X("city"),state:X("state"),zip:X("zip"),transaction_type:ie==="seller"?"seller":"buyer",close_date:X("close_date"),sale_price:Number(he)||0,commission_amount:xe?Number(xe):null,lead_source_name:X("lead_source"),client_type_name:X("client_type"),is_win:["yes","true","1"].includes(pe),notes:X("notes"),error:ve}})},C=O=>{var W;const R=(W=O.target.files)==null?void 0:W[0];if(!R)return;const z=new FileReader;z.onload=V=>{var te;const K=(te=V.target)==null?void 0:te.result,Q=N(K);n(Q)},z.readAsText(R)},P=async()=>{const O=r.filter(W=>!W.error);if(O.length===0){Dt.error("No valid transactions to import");return}o(!0),a(0);let R=0,z=0;for(let W=0;Wte.name.toLowerCase()===V.lead_source_name.toLowerCase()),Q=g==null?void 0:g.find(te=>te.name.toLowerCase()===V.client_type_name.toLowerCase());await _.mutateAsync({property_address:V.property_address,city:V.city||null,state:V.state||null,zip:V.zip||null,transaction_type:V.transaction_type,close_date:V.close_date,sale_price:V.sale_price,commission_amount:V.commission_amount,lead_source_id:(K==null?void 0:K.id)||null,client_type_id:(Q==null?void 0:Q.id)||null,contact_id:null,notes:V.notes||null,is_win:V.is_win}),R++}catch(K){z++,console.error("Failed to import transaction:",K)}a(Math.round((W+1)/O.length*100))}o(!1),R>0&&Dt.success(`Imported ${R} transaction${R>1?"s":""}`),z>0&&Dt.error(`Failed to import ${z} transaction${z>1?"s":""}`),n([]),e(!1)},A=r.filter(O=>!O.error).length,I=r.filter(O=>O.error).length;return s.jsx(mn,{open:t,onOpenChange:e,children:s.jsxs(pn,{className:"max-w-2xl max-h-[90vh]",children:[s.jsxs(xn,{children:[s.jsx(gn,{children:"Import Transactions"}),s.jsx(fi,{children:"Upload a CSV file with your past transactions"})]}),s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"flex items-center justify-between p-3 border rounded-lg bg-muted/50",children:[s.jsxs("div",{children:[s.jsx("p",{className:"font-medium",children:"Download Template"}),s.jsx("p",{className:"text-sm text-muted-foreground",children:"Get a CSV template with the correct format"})]}),s.jsxs(de,{variant:"outline",onClick:j,children:[s.jsx(Pp,{className:"h-4 w-4 mr-2"}),"Template"]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{htmlFor:"csv-file",children:"Upload CSV File"}),s.jsx(Et,{id:"csv-file",type:"file",accept:".csv",onChange:C})]}),r.length>0&&s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs(ir,{variant:"outline",children:[r.length," rows found"]}),A>0&&s.jsxs(ir,{className:"bg-green-500 text-white",children:[s.jsx(ru,{className:"h-3 w-3 mr-1"}),A," valid"]}),I>0&&s.jsxs(ir,{variant:"destructive",children:[s.jsx(sx,{className:"h-3 w-3 mr-1"}),I," errors"]})]}),s.jsx(qu,{className:"h-[200px] border rounded-lg",children:s.jsxs("div",{className:"p-2 space-y-2",children:[r.slice(0,10).map((O,R)=>s.jsxs("div",{className:`p-2 rounded text-sm ${O.error?"bg-destructive/10":"bg-muted/50"}`,children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"font-medium",children:O.property_address||"(no address)"}),s.jsx(ir,{variant:O.transaction_type==="buyer"?"default":"secondary",children:O.transaction_type})]}),s.jsxs("div",{className:"text-muted-foreground",children:[O.close_date," • $",O.sale_price.toLocaleString()]}),O.error&&s.jsx(ube,{variant:"destructive",className:"mt-1 py-1",children:s.jsx(dbe,{className:"text-xs",children:O.error})})]},R)),r.length>10&&s.jsxs("p",{className:"text-center text-sm text-muted-foreground",children:["...and ",r.length-10," more"]})]})}),i&&s.jsxs("div",{className:"space-y-2",children:[s.jsx("div",{className:"w-full bg-muted rounded-full h-2",children:s.jsx("div",{className:"bg-primary h-2 rounded-full transition-all",style:{width:`${c}%`}})}),s.jsxs("p",{className:"text-sm text-center text-muted-foreground",children:["Importing... ",c,"%"]})]})]}),s.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[s.jsx(de,{variant:"outline",onClick:()=>e(!1),children:"Cancel"}),s.jsxs(de,{onClick:P,disabled:A===0||i,children:[s.jsx(Vu,{className:"h-4 w-4 mr-2"}),"Import ",A," Transaction",A!==1?"s":""]})]})]})]})})}const vbt=wD({transactions_goal:l2().min(0).optional(),volume_goal:l2().min(0).optional(),gci_goal:l2().min(0).optional()});function _bt({open:t,onOpenChange:e,year:r,existingGoals:n}){const i=VBe(),{data:o}=BD(),c=(o==null?void 0:o.show_commission)??!0,a=eq({resolver:tq(vbt),defaultValues:{transactions_goal:void 0,volume_goal:void 0,gci_goal:void 0}});D.useEffect(()=>{n?a.reset({transactions_goal:n.transactions_goal??void 0,volume_goal:n.volume_goal?Number(n.volume_goal):void 0,gci_goal:n.gci_goal?Number(n.gci_goal):void 0}):a.reset({transactions_goal:void 0,volume_goal:void 0,gci_goal:void 0})},[n,a,t]);const m=async g=>{await i.mutateAsync({year:r,transactions_goal:g.transactions_goal??null,volume_goal:g.volume_goal??null,gci_goal:c?g.gci_goal??null:null}),e(!1)};return s.jsx(mn,{open:t,onOpenChange:e,children:s.jsxs(pn,{className:"max-w-md",children:[s.jsxs(xn,{children:[s.jsxs(gn,{children:[r," Goals"]}),s.jsx(fi,{children:"Set your annual targets to track your progress throughout the year."})]}),s.jsx(rq,{...a,children:s.jsxs("form",{onSubmit:a.handleSubmit(m),className:"space-y-4",children:[s.jsx(Sl,{control:a.control,name:"transactions_goal",render:({field:g})=>s.jsxs(cl,{children:[s.jsx(ul,{children:"Transactions Goal"}),s.jsx(dl,{children:s.jsx(Et,{type:"number",placeholder:"e.g., 24",...g,value:g.value??"",onChange:_=>g.onChange(_.target.value?Number(_.target.value):void 0)})}),s.jsx(PI,{children:"Total number of deals you want to close"}),s.jsx(gf,{})]})}),s.jsx(Sl,{control:a.control,name:"volume_goal",render:({field:g})=>s.jsxs(cl,{children:[s.jsx(ul,{children:"Volume Goal ($)"}),s.jsx(dl,{children:s.jsx(Et,{type:"number",placeholder:"e.g., 5000000",...g,value:g.value??"",onChange:_=>g.onChange(_.target.value?Number(_.target.value):void 0)})}),s.jsx(PI,{children:"Total sales volume you want to achieve"}),s.jsx(gf,{})]})}),c&&s.jsx(Sl,{control:a.control,name:"gci_goal",render:({field:g})=>s.jsxs(cl,{children:[s.jsx(ul,{children:"GCI Goal ($)"}),s.jsx(dl,{children:s.jsx(Et,{type:"number",placeholder:"e.g., 150000",...g,value:g.value??"",onChange:_=>g.onChange(_.target.value?Number(_.target.value):void 0)})}),s.jsx(PI,{children:"Gross commission income target"}),s.jsx(gf,{})]})}),s.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[s.jsx(de,{type:"button",variant:"outline",onClick:()=>e(!1),children:"Cancel"}),s.jsx(de,{type:"submit",disabled:i.isPending,children:"Save Goals"})]})]})})]})})}const hbe=new Date().getFullYear(),bbt=Array.from({length:10},(t,e)=>hbe-e);function wbt(){var V;const[t,e]=D.useState(hbe),[r,n]=D.useState(!1),[i,o]=D.useState(!1),[c,a]=D.useState(!1),[m,g]=D.useState(!1),{data:_,isLoading:j}=Tq(t),{yearStats:N,lifetimeStats:C,showCommission:P}=_pe(t),{data:A,isLoading:I}=vpe(t),{data:O}=BD(),R=qBe(),z=()=>{if(!_||_.length===0)return;const K=["Property Address","City","State","Zip","Transaction Type","Close Date","Sale Price",...P?["Commission"]:[],"Lead Source","Client Type","Contact Name","Is Win","Notes"],Q=_.map(xe=>{var pe,ve;return[xe.property_address,xe.city||"",xe.state||"",xe.zip||"",xe.transaction_type,xe.close_date,xe.sale_price,...P?[xe.commission_amount||""]:[],((pe=xe.lead_source)==null?void 0:pe.name)||"",((ve=xe.client_type)==null?void 0:ve.name)||"",xe.contact?`${xe.contact.first_name} ${xe.contact.last_name||""}`.trim():"",xe.is_win?"Yes":"No",xe.notes||""]}),te=[K,...Q].map(xe=>xe.map(pe=>`"${String(pe).replace(/"/g,'""')}"`).join(",")).join(` `),X=new Blob([te],{type:"text/csv"}),ie=URL.createObjectURL(X),he=document.createElement("a");he.href=ie,he.download=`transactions-${t}.csv`,he.click(),URL.revokeObjectURL(ie)},W=!_||_.length===0;return s.jsxs(Jr,{title:"Scorecard",children:[s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("h1",{className:"text-2xl font-bold",children:"Scorecard"}),s.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-amber-500 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),s.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[s.jsxs("div",{children:[s.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Business Scorecard"}),s.jsx("p",{className:"text-muted-foreground",children:"Track your transactions, goals, and performance"})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs(Kn,{value:String(t),onValueChange:K=>e(Number(K)),children:[s.jsx(qn,{className:"w-[120px]",children:s.jsx(Zn,{})}),s.jsx(Hn,{children:bbt.map(K=>s.jsx(_r,{value:String(K),children:K},K))})]}),s.jsx(de,{variant:"outline",size:"icon",onClick:()=>g(!m),children:s.jsx(eg,{className:"h-4 w-4"})})]})]}),m&&s.jsxs(at,{children:[s.jsx(xr,{className:"pb-3",children:s.jsx(wr,{className:"text-lg",children:"Settings"})}),s.jsx(ct,{children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"space-y-0.5",children:[s.jsx(mt,{children:"Show Commission"}),s.jsx("p",{className:"text-sm text-muted-foreground",children:"Display commission fields and include in stats"})]}),s.jsx(ri,{checked:(O==null?void 0:O.show_commission)??!0,onCheckedChange:K=>R.mutate({show_commission:K})})]})})]}),W&&!j?s.jsx(at,{className:"py-12",children:s.jsxs(ct,{className:"text-center space-y-4",children:[s.jsx("div",{className:"w-16 h-16 mx-auto rounded-full bg-primary/10 flex items-center justify-center",children:s.jsx(_p,{className:"h-8 w-8 text-primary"})}),s.jsxs("div",{children:[s.jsx("h3",{className:"text-lg font-semibold",children:"Start Tracking Your Success"}),s.jsx("p",{className:"text-muted-foreground max-w-md mx-auto mt-1",children:"Add your past transactions to see your performance metrics, track your goals, and celebrate your wins."})]}),s.jsxs("div",{className:"flex flex-wrap justify-center gap-2 pt-2",children:[s.jsxs(de,{onClick:()=>n(!0),children:[s.jsx(Qn,{className:"h-4 w-4 mr-2"}),"Add Your First Transaction"]}),s.jsxs(de,{variant:"outline",onClick:()=>o(!0),children:[s.jsx(Vu,{className:"h-4 w-4 mr-2"}),"Import CSV"]})]})]})}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsxs(de,{onClick:()=>n(!0),children:[s.jsx(Qn,{className:"h-4 w-4 mr-2"}),"Add Transaction"]}),s.jsxs(de,{variant:"outline",onClick:()=>a(!0),children:[s.jsx(rD,{className:"h-4 w-4 mr-2"}),"Set Goals"]}),s.jsxs(de,{variant:"outline",onClick:()=>o(!0),children:[s.jsx(Vu,{className:"h-4 w-4 mr-2"}),"Import"]}),s.jsxs(de,{variant:"outline",onClick:z,disabled:W,children:[s.jsx(Pp,{className:"h-4 w-4 mr-2"}),"Export"]})]}),s.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4",children:[s.jsx(at,{children:s.jsxs(ct,{className:"pt-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[s.jsx(ou,{className:"h-4 w-4"}),s.jsx("span",{className:"text-xs font-medium",children:"Transactions"})]}),s.jsx("p",{className:"text-2xl font-bold",children:N.totalTransactions}),s.jsxs("p",{className:"text-xs text-muted-foreground",children:[C.totalTransactions," lifetime"]})]})}),s.jsx(at,{children:s.jsxs(ct,{className:"pt-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[s.jsx(_i,{className:"h-4 w-4"}),s.jsx("span",{className:"text-xs font-medium",children:"Buyer/Seller"})]}),s.jsxs("p",{className:"text-2xl font-bold",children:[N.buyerCount,"/",N.sellerCount]}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"B/S split"})]})}),s.jsx(at,{children:s.jsxs(ct,{className:"pt-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[s.jsx(M1,{className:"h-4 w-4"}),s.jsx("span",{className:"text-xs font-medium",children:"Volume"})]}),s.jsx("p",{className:"text-2xl font-bold",children:fc(N.totalVolume,!0)}),s.jsxs("p",{className:"text-xs text-muted-foreground",children:[fc(C.totalVolume,!0)," lifetime"]})]})}),s.jsx(at,{children:s.jsxs(ct,{className:"pt-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[s.jsx(r0,{className:"h-4 w-4"}),s.jsx("span",{className:"text-xs font-medium",children:"Avg Price"})]}),s.jsx("p",{className:"text-2xl font-bold",children:fc(N.averagePrice,!0)})]})}),s.jsx(at,{children:s.jsxs(ct,{className:"pt-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[s.jsx(Jw,{className:"h-4 w-4"}),s.jsx("span",{className:"text-xs font-medium",children:"Top Source"})]}),s.jsx("p",{className:"text-lg font-bold truncate",children:((V=N.topLeadSource)==null?void 0:V.name)||"-"}),N.topLeadSource&&s.jsxs("p",{className:"text-xs text-muted-foreground",children:[N.topLeadSource.count," deals"]})]})}),P&&s.jsx(at,{children:s.jsxs(ct,{className:"pt-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[s.jsx(M1,{className:"h-4 w-4"}),s.jsx("span",{className:"text-xs font-medium",children:"Commission"})]}),s.jsx("p",{className:"text-2xl font-bold",children:fc(N.totalCommission,!0)}),s.jsxs("p",{className:"text-xs text-muted-foreground",children:[fc(C.totalCommission,!0)," lifetime"]})]})})]}),A&&s.jsx(vxe,{goals:A,stats:N,year:t,showCommission:P}),s.jsxs(go,{defaultValue:"transactions",className:"space-y-4",children:[s.jsxs(ao,{children:[s.jsx(Bn,{value:"transactions",children:"Transactions"}),s.jsx(Bn,{value:"charts",children:"Charts"})]}),s.jsx(xs,{value:"transactions",children:s.jsx(xxe,{transactions:_||[],showCommission:P,isLoading:j})}),s.jsx(xs,{value:"charts",children:s.jsx(cbe,{stats:N,year:t})})]})]})]}),s.jsx(Hye,{open:r,onOpenChange:n}),s.jsx(xbt,{open:i,onOpenChange:o}),s.jsx(_bt,{open:c,onOpenChange:a,year:t,existingGoals:A})]})}const jbt={active:"bg-emerald-500",coming_soon:"bg-sky-500",price_improvement:"bg-orange-500",under_contract:"bg-purple-500",sold:"bg-gray-500"},Sbt={active:"Active",coming_soon:"Coming Soon",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},Nbt={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"};function kB({listing:t,onClick:e,onEdit:r,showActions:n}){var j,N;const{data:i}=gpe(t.id),o=mpe(),c=ype(),a=C=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(C),m=((j=t.photos)==null?void 0:j.find(C=>C.is_primary))||((N=t.photos)==null?void 0:N[0]),g=async C=>{C.stopPropagation();try{const P=await o.mutateAsync(t.id);Dt.success(P.saved?"Listing saved!":"Listing removed from saved")}catch{Dt.error("Failed to save listing")}},_=async C=>{C.stopPropagation();try{await navigator.clipboard.writeText(window.location.origin+`/innercircle/listings/${t.id}`),await c.mutateAsync({listingId:t.id,shareType:"copy_link"}),Dt.success("Link copied to clipboard!")}catch{Dt.error("Failed to copy link")}};return s.jsxs(at,{className:"overflow-hidden hover:shadow-lg transition-shadow cursor-pointer group",onClick:e,children:[s.jsxs("div",{className:"relative aspect-[4/3] bg-muted",children:[m?s.jsx("img",{src:m.photo_url,alt:t.property_address||t.city,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):s.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:s.jsx(gM,{className:"h-12 w-12"})}),s.jsx(ir,{className:`absolute top-2 left-2 ${jbt[t.status]} text-white border-0`,children:Sbt[t.status]}),t.is_featured&&s.jsx("div",{className:"absolute top-2 right-2 p-1.5 bg-amber-500 rounded-full",children:s.jsx(mh,{className:"h-4 w-4 text-white fill-white"})}),s.jsxs("div",{className:"absolute bottom-2 right-2 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[s.jsx(de,{size:"icon",variant:"secondary",className:"h-8 w-8",onClick:g,children:s.jsx(bp,{className:`h-4 w-4 ${i?"fill-pink-500 text-pink-500":""}`})}),s.jsx(de,{size:"icon",variant:"secondary",className:"h-8 w-8",onClick:_,children:s.jsx(ph,{className:"h-4 w-4"})})]})]}),s.jsxs(ct,{className:"p-4 space-y-3",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("p",{className:"text-xl font-bold text-primary",children:a(t.price)}),t.open_to_referrals&&s.jsxs(ir,{variant:"outline",className:"text-xs",children:[s.jsx(_i,{className:"h-3 w-3 mr-1"}),"Referrals"]})]}),s.jsxs("div",{children:[t.property_address&&s.jsx("p",{className:"font-medium truncate",children:t.property_address}),s.jsxs("p",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[s.jsx(wp,{className:"h-3 w-3"}),t.city,", ",t.state,t.neighborhood&&` • ${t.neighborhood}`]})]}),s.jsxs("div",{className:"flex items-center gap-4 text-sm text-muted-foreground",children:[t.bedrooms&&s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(ioe,{className:"h-4 w-4"}),t.bedrooms," bd"]}),t.bathrooms&&s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(soe,{className:"h-4 w-4"}),t.bathrooms," ba"]}),t.square_footage&&s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(gM,{className:"h-4 w-4"}),t.square_footage.toLocaleString()," sqft"]})]}),s.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[s.jsx(ir,{variant:"secondary",className:"text-xs",children:Nbt[t.property_type]}),t.agent&&s.jsx("p",{className:"text-xs text-muted-foreground truncate max-w-[120px]",children:t.agent.name})]}),s.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground",children:[s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(Rc,{className:"h-3 w-3"}),t.view_count]}),s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(ph,{className:"h-3 w-3"}),t.share_count]}),s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(bp,{className:"h-3 w-3"}),t.save_count]})]}),n&&r&&s.jsxs(de,{variant:"outline",size:"sm",className:"w-full",onClick:C=>{C.stopPropagation(),r()},children:[s.jsx(P_,{className:"h-4 w-4 mr-2"}),"Edit Listing"]})]})]})}const Cbt=[{value:"active",label:"Active"},{value:"coming_soon",label:"Coming Soon"},{value:"price_improvement",label:"Price Improvement"},{value:"under_contract",label:"Under Contract"},{value:"sold",label:"Sold"}],kbt=[{value:"single_family",label:"Single Family"},{value:"condo",label:"Condo"},{value:"townhouse",label:"Townhouse"},{value:"land",label:"Land"},{value:"multi_family",label:"Multi-Family"},{value:"luxury",label:"Luxury"},{value:"commercial",label:"Commercial"},{value:"other",label:"Other"}];function Tbt({filters:t,onFiltersChange:e,onClose:r}){const n=()=>{e({sortBy:"newest"})};return s.jsxs(at,{children:[s.jsxs(xr,{className:"flex flex-row items-center justify-between pb-3",children:[s.jsx(wr,{className:"text-lg",children:"Filters"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(de,{variant:"ghost",size:"sm",onClick:n,children:"Clear All"}),s.jsx(de,{variant:"ghost",size:"icon",onClick:r,children:s.jsx(Ni,{className:"h-4 w-4"})})]})]}),s.jsxs(ct,{children:[s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Status"}),s.jsxs(Kn,{value:t.status||"all",onValueChange:i=>e({...t,status:i==="all"?void 0:i}),children:[s.jsx(qn,{children:s.jsx(Zn,{placeholder:"All statuses"})}),s.jsxs(Hn,{children:[s.jsx(_r,{value:"all",children:"All Statuses"}),Cbt.map(i=>s.jsx(_r,{value:i.value,children:i.label},i.value))]})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Property Type"}),s.jsxs(Kn,{value:t.propertyType||"all",onValueChange:i=>e({...t,propertyType:i==="all"?void 0:i}),children:[s.jsx(qn,{children:s.jsx(Zn,{placeholder:"All types"})}),s.jsxs(Hn,{children:[s.jsx(_r,{value:"all",children:"All Types"}),kbt.map(i=>s.jsx(_r,{value:i.value,children:i.label},i.value))]})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Min Price"}),s.jsx(Et,{type:"number",placeholder:"No minimum",value:t.minPrice||"",onChange:i=>e({...t,minPrice:i.target.value?Number(i.target.value):void 0})})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Max Price"}),s.jsx(Et,{type:"number",placeholder:"No maximum",value:t.maxPrice||"",onChange:i=>e({...t,maxPrice:i.target.value?Number(i.target.value):void 0})})]})]}),s.jsxs("div",{className:"flex items-center justify-between mt-4 pt-4 border-t",children:[s.jsxs("div",{children:[s.jsx(mt,{children:"Open to Referrals Only"}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Show only listings accepting buyer referrals"})]}),s.jsx(ri,{checked:t.openToReferrals||!1,onCheckedChange:i=>e({...t,openToReferrals:i||void 0})})]})]})]})}function Ebt({leaderboard:t}){const e=n=>{switch(n){case 0:return s.jsx(RF,{className:"h-5 w-5 text-amber-500"});case 1:return s.jsx(KZ,{className:"h-5 w-5 text-gray-400"});case 2:return s.jsx(Jw,{className:"h-5 w-5 text-amber-700"});default:return s.jsx("span",{className:"text-sm font-medium text-muted-foreground w-5 text-center",children:n+1})}},r=(n,i)=>!n||n.length===0?s.jsx("div",{className:"py-8 text-center text-muted-foreground",children:"No data yet. Start sharing to climb the leaderboard!"}):s.jsx("div",{className:"space-y-2",children:n.map((o,c)=>s.jsxs("div",{className:`flex items-center gap-4 p-3 rounded-lg ${c===0?"bg-gradient-to-r from-amber-500/10 to-amber-500/5 border border-amber-500/20":"bg-muted/50"}`,children:[s.jsx("div",{className:"flex items-center justify-center w-8",children:e(c)}),s.jsx("div",{className:"flex-1 min-w-0",children:s.jsx("p",{className:"font-medium truncate",children:o.name})}),s.jsxs(ir,{variant:c===0?"default":"secondary",children:[o.count," ",i]})]},o.agentId))});return s.jsxs("div",{className:"space-y-6",children:[s.jsxs(at,{children:[s.jsx(xr,{children:s.jsxs(wr,{className:"flex items-center gap-2",children:[s.jsx(RF,{className:"h-5 w-5 text-amber-500"}),"Community Badges"]})}),s.jsx(ct,{children:s.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[s.jsxs("div",{className:"text-center p-4 rounded-lg bg-gradient-to-br from-emerald-500/10 to-emerald-500/5 border border-emerald-500/20",children:[s.jsx("div",{className:"w-12 h-12 mx-auto mb-2 rounded-full bg-emerald-500/20 flex items-center justify-center",children:s.jsx(ph,{className:"h-6 w-6 text-emerald-500"})}),s.jsx("p",{className:"font-medium text-sm",children:"Listing Amplifier"}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Share 10+ listings"})]}),s.jsxs("div",{className:"text-center p-4 rounded-lg bg-gradient-to-br from-sky-500/10 to-sky-500/5 border border-sky-500/20",children:[s.jsx("div",{className:"w-12 h-12 mx-auto mb-2 rounded-full bg-sky-500/20 flex items-center justify-center",children:s.jsx(ou,{className:"h-6 w-6 text-sky-500"})}),s.jsx("p",{className:"font-medium text-sm",children:"Top Contributor"}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Add 5+ listings"})]}),s.jsxs("div",{className:"text-center p-4 rounded-lg bg-gradient-to-br from-purple-500/10 to-purple-500/5 border border-purple-500/20",children:[s.jsx("div",{className:"w-12 h-12 mx-auto mb-2 rounded-full bg-purple-500/20 flex items-center justify-center",children:s.jsx(KZ,{className:"h-6 w-6 text-purple-500"})}),s.jsx("p",{className:"font-medium text-sm",children:"Referral Connector"}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Send 3+ referrals"})]}),s.jsxs("div",{className:"text-center p-4 rounded-lg bg-gradient-to-br from-amber-500/10 to-amber-500/5 border border-amber-500/20",children:[s.jsx("div",{className:"w-12 h-12 mx-auto mb-2 rounded-full bg-amber-500/20 flex items-center justify-center",children:s.jsx(RF,{className:"h-6 w-6 text-amber-500"})}),s.jsx("p",{className:"font-medium text-sm",children:"Community MVP"}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Top performer"})]})]})})]}),s.jsxs(at,{children:[s.jsx(xr,{children:s.jsx(wr,{children:"Community Leaderboard"})}),s.jsx(ct,{children:s.jsxs(go,{defaultValue:"sharers",children:[s.jsxs(ao,{className:"w-full",children:[s.jsxs(Bn,{value:"sharers",className:"flex-1",children:[s.jsx(ph,{className:"h-4 w-4 mr-2"}),"Top Sharers"]}),s.jsxs(Bn,{value:"listers",className:"flex-1",children:[s.jsx(ou,{className:"h-4 w-4 mr-2"}),"Top Contributors"]})]}),s.jsx(xs,{value:"sharers",className:"mt-4",children:r(t==null?void 0:t.topSharers,"shares")}),s.jsx(xs,{value:"listers",className:"mt-4",children:r(t==null?void 0:t.topListers,"listings")})]})})]})]})}function Abt(){var W,V,K,Q,te,X,ie,he;const t=Bs(),{data:e,isLoading:r}=hpe(),[n,i]=D.useState("feed"),[o,c]=D.useState(!1),[a,m]=D.useState(""),[g,_]=D.useState({sortBy:"newest"}),{data:j,isLoading:N}=fpe({...g,city:a||g.city}),{data:C,isLoading:P}=EBe(),{data:A,isLoading:I}=jBe(),{data:O,isLoading:R}=IBe(),{data:z}=OBe();return r?s.jsx(Jr,{title:"Listing Exchange",description:"Community-powered listing collaboration",children:s.jsx("div",{className:"flex items-center justify-center py-12",children:s.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full"})})}):e?s.jsx(Jr,{title:"Listing Exchange",description:"Community-powered listing collaboration",children:s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("h1",{className:"text-2xl font-bold",children:"Listing Exchange"}),s.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-amber-500 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),s.jsxs(de,{onClick:()=>t("/innercircle/listings/new"),children:[s.jsx(Qn,{className:"h-4 w-4 mr-2"}),"Add Listing"]})]}),s.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[s.jsx(at,{children:s.jsxs(ct,{className:"p-4 flex items-center gap-3",children:[s.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:s.jsx(ou,{className:"h-5 w-5 text-primary"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-2xl font-bold",children:(j==null?void 0:j.length)||0}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Active Listings"})]})]})}),s.jsx(at,{children:s.jsxs(ct,{className:"p-4 flex items-center gap-3",children:[s.jsx("div",{className:"p-2 bg-pink-500/10 rounded-lg",children:s.jsx(bp,{className:"h-5 w-5 text-pink-500"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-2xl font-bold",children:(C==null?void 0:C.length)||0}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Saved"})]})]})}),s.jsx(at,{children:s.jsxs(ct,{className:"p-4 flex items-center gap-3",children:[s.jsx("div",{className:"p-2 bg-emerald-500/10 rounded-lg",children:s.jsx(qZ,{className:"h-5 w-5 text-emerald-500"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-2xl font-bold",children:(A==null?void 0:A.length)||0}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"My Listings"})]})]})}),s.jsx(at,{children:s.jsxs(ct,{className:"p-4 flex items-center gap-3",children:[s.jsx("div",{className:"p-2 bg-sky-500/10 rounded-lg",children:s.jsx(_i,{className:"h-5 w-5 text-sky-500"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-2xl font-bold",children:(((W=O==null?void 0:O.sent)==null?void 0:W.length)||0)+(((V=O==null?void 0:O.received)==null?void 0:V.length)||0)}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Referrals"})]})]})})]}),s.jsxs(go,{value:n,onValueChange:i,children:[s.jsxs(ao,{className:"w-full justify-start overflow-x-auto",children:[s.jsx(Bn,{value:"feed",children:"Community Feed"}),s.jsx(Bn,{value:"my-listings",children:"My Listings"}),s.jsx(Bn,{value:"saved",children:"Saved"}),s.jsx(Bn,{value:"referrals",children:"Referrals"}),s.jsx(Bn,{value:"leaderboard",children:"Leaderboard"})]}),s.jsxs(xs,{value:"feed",className:"space-y-4",children:[s.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[s.jsxs("div",{className:"relative flex-1",children:[s.jsx(ba,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),s.jsx(Et,{placeholder:"Search by city or neighborhood...",value:a,onChange:xe=>m(xe.target.value),className:"pl-9"})]}),s.jsxs(Kn,{value:g.sortBy,onValueChange:xe=>_({...g,sortBy:xe}),children:[s.jsx(qn,{className:"w-[180px]",children:s.jsx(Zn,{placeholder:"Sort by"})}),s.jsxs(Hn,{children:[s.jsx(_r,{value:"newest",children:"Newest First"}),s.jsx(_r,{value:"updated",children:"Recently Updated"}),s.jsx(_r,{value:"price_asc",children:"Price: Low to High"}),s.jsx(_r,{value:"price_desc",children:"Price: High to Low"})]})]}),s.jsxs(de,{variant:"outline",onClick:()=>c(!o),children:[s.jsx(k2e,{className:"h-4 w-4 mr-2"}),"Filters"]})]}),o&&s.jsx(Tbt,{filters:g,onFiltersChange:_,onClose:()=>c(!1)}),N?s.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(6)].map((xe,pe)=>s.jsxs(at,{children:[s.jsx(Dn,{className:"h-48 w-full"}),s.jsxs(ct,{className:"p-4 space-y-2",children:[s.jsx(Dn,{className:"h-5 w-3/4"}),s.jsx(Dn,{className:"h-4 w-1/2"}),s.jsx(Dn,{className:"h-4 w-1/4"})]})]},pe))}):(j==null?void 0:j.length)===0?s.jsx(at,{children:s.jsxs(ct,{className:"py-12 text-center",children:[s.jsx(ou,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),s.jsx("h3",{className:"text-lg font-medium mb-2",children:"No listings found"}),s.jsx("p",{className:"text-muted-foreground mb-4",children:"Be the first to share a listing with the community!"}),s.jsxs(de,{onClick:()=>t("/innercircle/listings/new"),children:[s.jsx(Qn,{className:"h-4 w-4 mr-2"}),"Add Listing"]})]})}):s.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:j==null?void 0:j.map(xe=>s.jsx(kB,{listing:xe,onClick:()=>t(`/innercircle/listings/${xe.id}`)},xe.id))})]}),s.jsx(xs,{value:"my-listings",className:"space-y-4",children:I?s.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((xe,pe)=>s.jsxs(at,{children:[s.jsx(Dn,{className:"h-48 w-full"}),s.jsxs(ct,{className:"p-4 space-y-2",children:[s.jsx(Dn,{className:"h-5 w-3/4"}),s.jsx(Dn,{className:"h-4 w-1/2"})]})]},pe))}):(A==null?void 0:A.length)===0?s.jsx(at,{children:s.jsxs(ct,{className:"py-12 text-center",children:[s.jsx(qZ,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),s.jsx("h3",{className:"text-lg font-medium mb-2",children:"No listings yet"}),s.jsx("p",{className:"text-muted-foreground mb-4",children:"Share your listings with the LevelUp community!"}),s.jsxs(de,{onClick:()=>t("/innercircle/listings/new"),children:[s.jsx(Qn,{className:"h-4 w-4 mr-2"}),"Add Your First Listing"]})]})}):s.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:A==null?void 0:A.map(xe=>s.jsx(kB,{listing:xe,showActions:!0,onClick:()=>t(`/innercircle/listings/${xe.id}`),onEdit:()=>t(`/innercircle/listings/${xe.id}/edit`)},xe.id))})}),s.jsx(xs,{value:"saved",className:"space-y-4",children:P?s.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((xe,pe)=>s.jsxs(at,{children:[s.jsx(Dn,{className:"h-48 w-full"}),s.jsxs(ct,{className:"p-4 space-y-2",children:[s.jsx(Dn,{className:"h-5 w-3/4"}),s.jsx(Dn,{className:"h-4 w-1/2"})]})]},pe))}):(C==null?void 0:C.length)===0?s.jsx(at,{children:s.jsxs(ct,{className:"py-12 text-center",children:[s.jsx(bp,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),s.jsx("h3",{className:"text-lg font-medium mb-2",children:"No saved listings"}),s.jsx("p",{className:"text-muted-foreground",children:"Save listings to quickly access them later"})]})}):s.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:C==null?void 0:C.map(xe=>s.jsx(kB,{listing:xe.listing,onClick:()=>t(`/innercircle/listings/${xe.listing.id}`)},xe.id))})}),s.jsx(xs,{value:"referrals",className:"space-y-6",children:s.jsxs("div",{className:"grid md:grid-cols-2 gap-6",children:[s.jsxs("div",{children:[s.jsxs("h3",{className:"font-semibold mb-3 flex items-center gap-2",children:[s.jsx(ph,{className:"h-4 w-4"}),"Referrals Sent (",((K=O==null?void 0:O.sent)==null?void 0:K.length)||0,")"]}),((Q=O==null?void 0:O.sent)==null?void 0:Q.length)===0?s.jsx(at,{children:s.jsx(ct,{className:"py-8 text-center text-muted-foreground",children:"No referrals sent yet"})}):s.jsx("div",{className:"space-y-3",children:(te=O==null?void 0:O.sent)==null?void 0:te.map(xe=>{var pe,ve;return s.jsx(at,{children:s.jsx(ct,{className:"p-4",children:s.jsxs("div",{className:"flex justify-between items-start mb-2",children:[s.jsxs("div",{children:[s.jsx("p",{className:"font-medium",children:xe.buyer_name}),s.jsx("p",{className:"text-sm text-muted-foreground",children:((pe=xe.listing)==null?void 0:pe.property_address)||((ve=xe.listing)==null?void 0:ve.city)})]}),s.jsx(ir,{variant:xe.status==="closed"?"default":"secondary",children:xe.status.replace("_"," ")})]})})},xe.id)})})]}),s.jsxs("div",{children:[s.jsxs("h3",{className:"font-semibold mb-3 flex items-center gap-2",children:[s.jsx(_i,{className:"h-4 w-4"}),"Referrals Received (",((X=O==null?void 0:O.received)==null?void 0:X.length)||0,")"]}),((ie=O==null?void 0:O.received)==null?void 0:ie.length)===0?s.jsx(at,{children:s.jsx(ct,{className:"py-8 text-center text-muted-foreground",children:"No referrals received yet"})}):s.jsx("div",{className:"space-y-3",children:(he=O==null?void 0:O.received)==null?void 0:he.map(xe=>{var pe;return s.jsx(at,{children:s.jsxs(ct,{className:"p-4",children:[s.jsxs("div",{className:"flex justify-between items-start mb-2",children:[s.jsxs("div",{children:[s.jsx("p",{className:"font-medium",children:xe.buyer_name}),s.jsxs("p",{className:"text-sm text-muted-foreground",children:["From: ",(pe=xe.sender)==null?void 0:pe.name]})]}),s.jsx(ir,{variant:xe.status==="closed"?"default":"secondary",children:xe.status.replace("_"," ")})]}),s.jsx(de,{size:"sm",variant:"outline",className:"w-full mt-2",onClick:()=>t(`/innercircle/listings/${xe.listing_id}`),children:"View Listing"})]})},xe.id)})})]})]})}),s.jsx(xs,{value:"leaderboard",children:s.jsx(Ebt,{leaderboard:z})})]})]})}):s.jsx(Jr,{title:"Listing Exchange",description:"Community-powered listing collaboration",children:s.jsx(at,{children:s.jsxs(ct,{className:"py-12 text-center",children:[s.jsx(ou,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),s.jsx("h2",{className:"text-xl font-semibold mb-2",children:"Coming Soon"}),s.jsx("p",{className:"text-muted-foreground",children:"Listing Exchange is currently in development. Check back soon!"})]})})})}const Pbt={active:"bg-emerald-500",coming_soon:"bg-sky-500",price_improvement:"bg-orange-500",under_contract:"bg-purple-500",sold:"bg-gray-500"},Ibt={active:"Active",coming_soon:"Coming Soon",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},Jne={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"};function Mbt(){var he,xe,pe,ve,ge,ke,Ce,Se,je;const{listingId:t}=mu(),e=Bs(),{user:r}=rn(),{data:n,isLoading:i}=ppe(t||""),{data:o}=gpe(t||""),{data:c}=PBe(t||""),a=mpe(),m=ABe(),g=ype(),_=CBe(),j=MBe(),[N,C]=D.useState(!1),[P,A]=D.useState(!1),[I,O]=D.useState(null),[R,z]=D.useState({buyerName:"",buyerType:"",notes:""}),W=(r==null?void 0:r.id)===(n==null?void 0:n.agent_id),V=et=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(et),K=async et=>{const bt=window.location.href,_e=`Check out this listing: ${(n==null?void 0:n.property_address)||(n==null?void 0:n.city)}`;try{switch(await g.mutateAsync({listingId:n.id,shareType:et}),et){case"facebook":window.open(`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(bt)}`,"_blank");break;case"copy":await navigator.clipboard.writeText(bt),Dt.success("Link copied to clipboard!");break;case"text":window.open(`sms:?body=${encodeURIComponent(`${_e} ${bt}`)}`);break;case"email":window.open(`mailto:?subject=${encodeURIComponent(_e)}&body=${encodeURIComponent(`Check out this listing: ${bt}`)}`);break}}catch{Dt.error("Failed to share")}},Q=async()=>{try{await _.mutateAsync(n.id),Dt.success("Listing deleted"),e("/innercircle/listings")}catch{Dt.error("Failed to delete listing")}},te=async()=>{if(!R.buyerName.trim()){Dt.error("Please enter buyer name");return}try{await j.mutateAsync({listingId:n.id,listingAgentId:n.agent_id,buyerName:R.buyerName,buyerType:R.buyerType||void 0,notes:R.notes||void 0}),Dt.success("Referral sent successfully!"),A(!1),z({buyerName:"",buyerType:"",notes:""})}catch{Dt.error("Failed to send referral")}},X=et=>{var gt,Me;const bt=(n==null?void 0:n.property_address)||`${n==null?void 0:n.city}, ${n==null?void 0:n.state}`,_e=V((n==null?void 0:n.price)||0),Ye=n!=null&&n.bedrooms?`${n.bedrooms}BD`:"",pt=n!=null&&n.bathrooms?`${n.bathrooms}BA`:"",nt=n!=null&&n.square_footage?`${n.square_footage.toLocaleString()}SF`:"",Qt=[Ye,pt,nt].filter(Boolean).join(" | ");switch(et){case"just_listed":return`🏡 JUST LISTED! ${bt} ${_e} ${Qt} ${(n==null?void 0:n.description)||"Schedule your showing today!"} #JustListed #RealEstate #HomeForSale #${(gt=n==null?void 0:n.city)==null?void 0:gt.replace(/\s/g,"")}`;case"price_improvement":return`📣 PRICE IMPROVEMENT! ${bt} Now ${_e}! ${Qt} Don't miss this opportunity! #PriceReduced #RealEstate #HomeForSale`;case"teaser":return`Looking for a ${Jne[(n==null?void 0:n.property_type)||"single_family"].toLowerCase()} in ${n==null?void 0:n.city}? 👀 I've got just the one for you! ${Qt} DM me for details! 📩 #ComingSoon #RealEstate #${(Me=n==null?void 0:n.city)==null?void 0:Me.replace(/\s/g,"")}`;default:return""}};if(i)return s.jsx(Jr,{title:"Listing",description:"",children:s.jsxs("div",{className:"space-y-6",children:[s.jsx(Dn,{className:"h-10 w-32"}),s.jsx(Dn,{className:"h-[400px] w-full"}),s.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[s.jsx(Dn,{className:"h-48"}),s.jsx(Dn,{className:"h-48"}),s.jsx(Dn,{className:"h-48"})]})]})});if(!n)return s.jsx(Jr,{title:"Listing Not Found",description:"",children:s.jsx(at,{children:s.jsxs(ct,{className:"py-12 text-center",children:[s.jsx("p",{className:"text-muted-foreground mb-4",children:"This listing could not be found."}),s.jsx(de,{onClick:()=>e("/innercircle/listings"),children:"Back to Listings"})]})})});const ie=((he=n.photos)==null?void 0:he.find(et=>et.is_primary))||((xe=n.photos)==null?void 0:xe[0]);return s.jsxs(Jr,{title:"",description:"",children:[s.jsxs("div",{className:"space-y-6",children:[s.jsxs(de,{variant:"ghost",onClick:()=>e("/innercircle/listings"),children:[s.jsx(Ka,{className:"h-4 w-4 mr-2"}),"Back to Listings"]}),s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[s.jsx("div",{className:"md:col-span-2",children:s.jsx("div",{className:"aspect-[16/10] rounded-lg overflow-hidden bg-muted cursor-pointer",onClick:()=>ie&&O(ie.photo_url),children:ie?s.jsx("img",{src:ie.photo_url,alt:"Primary",className:"w-full h-full object-cover"}):s.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:"No photos"})})}),s.jsx("div",{className:"grid grid-cols-2 gap-2",children:(pe=n.photos)==null?void 0:pe.slice(1,5).map((et,bt)=>s.jsx("div",{className:"aspect-square rounded-lg overflow-hidden bg-muted cursor-pointer",onClick:()=>O(et.photo_url),children:s.jsx("img",{src:et.photo_url,alt:`Photo ${bt+2}`,className:"w-full h-full object-cover"})},et.id))})]}),s.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[s.jsxs("div",{className:"md:col-span-2 space-y-6",children:[s.jsx(at,{children:s.jsxs(ct,{className:"p-6",children:[s.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4 mb-6",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[s.jsx(ir,{className:`${Pbt[n.status]} text-white border-0`,children:Ibt[n.status]}),n.is_featured&&s.jsxs(ir,{variant:"outline",className:"border-amber-500 text-amber-500",children:[s.jsx(mh,{className:"h-3 w-3 mr-1 fill-amber-500"}),"Featured"]}),n.open_to_referrals&&s.jsxs(ir,{variant:"outline",children:[s.jsx(_i,{className:"h-3 w-3 mr-1"}),"Open to Referrals"]})]}),s.jsx("h1",{className:"text-3xl font-bold text-primary mb-2",children:V(n.price)}),n.property_address&&s.jsx("p",{className:"text-xl font-medium",children:n.property_address}),s.jsxs("p",{className:"text-muted-foreground flex items-center gap-1",children:[s.jsx(wp,{className:"h-4 w-4"}),n.city,", ",n.state,n.neighborhood&&` • ${n.neighborhood}`]})]}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(de,{variant:"outline",size:"icon",onClick:()=>a.mutate(n.id),children:s.jsx(bp,{className:`h-4 w-4 ${o?"fill-pink-500 text-pink-500":""}`})}),s.jsx(de,{variant:"outline",size:"icon",onClick:()=>m.mutate(n.id),children:c?s.jsx(H6,{className:"h-4 w-4"}):s.jsx(QR,{className:"h-4 w-4"})}),s.jsxs(rg,{children:[s.jsx(ng,{asChild:!0,children:s.jsxs(de,{variant:"outline",children:[s.jsx(ph,{className:"h-4 w-4 mr-2"}),"Share"]})}),s.jsxs(Op,{children:[s.jsxs(Ro,{onClick:()=>K("copy"),children:[s.jsx(ix,{className:"h-4 w-4 mr-2"}),"Copy Link"]}),s.jsxs(Ro,{onClick:()=>K("facebook"),children:[s.jsx(C2e,{className:"h-4 w-4 mr-2"}),"Facebook"]}),s.jsxs(Ro,{onClick:()=>K("text"),children:[s.jsx(Tf,{className:"h-4 w-4 mr-2"}),"Text"]}),s.jsxs(Ro,{onClick:()=>K("email"),children:[s.jsx(Fo,{className:"h-4 w-4 mr-2"}),"Email"]})]})]}),W&&s.jsxs(s.Fragment,{children:[s.jsxs(de,{variant:"outline",onClick:()=>e(`/innercircle/listings/${n.id}/edit`),children:[s.jsx(P_,{className:"h-4 w-4 mr-2"}),"Edit"]}),s.jsx(de,{variant:"destructive",size:"icon",onClick:()=>C(!0),children:s.jsx(oi,{className:"h-4 w-4"})})]})]})]}),s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-4 py-4 border-y",children:[n.bedrooms&&s.jsxs("div",{className:"text-center",children:[s.jsx(ioe,{className:"h-5 w-5 mx-auto mb-1 text-muted-foreground"}),s.jsx("p",{className:"font-semibold",children:n.bedrooms}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Beds"})]}),n.bathrooms&&s.jsxs("div",{className:"text-center",children:[s.jsx(soe,{className:"h-5 w-5 mx-auto mb-1 text-muted-foreground"}),s.jsx("p",{className:"font-semibold",children:n.bathrooms}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Baths"})]}),n.square_footage&&s.jsxs("div",{className:"text-center",children:[s.jsx(gM,{className:"h-5 w-5 mx-auto mb-1 text-muted-foreground"}),s.jsx("p",{className:"font-semibold",children:n.square_footage.toLocaleString()}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Sq Ft"})]}),n.year_built&&s.jsxs("div",{className:"text-center",children:[s.jsx(ko,{className:"h-5 w-5 mx-auto mb-1 text-muted-foreground"}),s.jsx("p",{className:"font-semibold",children:n.year_built}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Built"})]})]}),s.jsxs("div",{className:"pt-4 space-y-4",children:[s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsxs(ir,{variant:"secondary",children:[s.jsx(yc,{className:"h-3 w-3 mr-1"}),Jne[n.property_type]]}),n.lot_size&&s.jsxs(ir,{variant:"secondary",children:["Lot: ",n.lot_size]}),n.has_hoa&&s.jsx(ir,{variant:"secondary",children:"HOA"})]}),n.description&&s.jsxs("div",{children:[s.jsx("h3",{className:"font-medium mb-2",children:"Description"}),s.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:n.description})]}),n.agent_notes&&n.agent_notes_public&&s.jsxs("div",{children:[s.jsx("h3",{className:"font-medium mb-2",children:"Agent Notes"}),s.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:n.agent_notes})]}),n.mls_link&&s.jsx(de,{variant:"outline",asChild:!0,children:s.jsxs("a",{href:n.mls_link,target:"_blank",rel:"noopener noreferrer",children:[s.jsx(oa,{className:"h-4 w-4 mr-2"}),"View on MLS"]})})]}),s.jsxs("div",{className:"flex items-center gap-4 pt-4 mt-4 border-t text-sm text-muted-foreground",children:[s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(Rc,{className:"h-4 w-4"}),n.view_count," views"]}),s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(ph,{className:"h-4 w-4"}),n.share_count," shares"]}),s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(bp,{className:"h-4 w-4"}),n.save_count," saves"]})]})]})}),n.allow_sharing&&s.jsxs(at,{children:[s.jsx(xr,{children:s.jsx(wr,{className:"text-lg",children:"Share Content"})}),s.jsx(ct,{className:"space-y-4",children:["just_listed","price_improvement","teaser"].map(et=>s.jsxs("div",{className:"p-3 bg-muted rounded-lg",children:[s.jsxs("div",{className:"flex justify-between items-start mb-2",children:[s.jsxs("p",{className:"font-medium text-sm capitalize",children:[et.replace("_"," ")," Caption"]}),s.jsx(de,{size:"sm",variant:"ghost",onClick:()=>{navigator.clipboard.writeText(X(et)),Dt.success("Caption copied!")},children:s.jsx(ix,{className:"h-3 w-3"})})]}),s.jsx("p",{className:"text-xs text-muted-foreground whitespace-pre-wrap",children:X(et)})]},et))})]})]}),s.jsxs("div",{className:"space-y-6",children:[s.jsxs(at,{children:[s.jsx(xr,{children:s.jsx(wr,{className:"text-lg",children:"Listing Agent"})}),s.jsxs(ct,{children:[s.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[s.jsx("div",{className:"w-12 h-12 rounded-full bg-primary/10 flex items-center justify-center",children:s.jsx("span",{className:"text-lg font-semibold text-primary",children:((ge=(ve=n.agent)==null?void 0:ve.name)==null?void 0:ge.charAt(0))||"?"})}),s.jsxs("div",{children:[s.jsx("p",{className:"font-medium",children:((ke=n.agent)==null?void 0:ke.name)||"Unknown"}),((Se=(Ce=n.agent)==null?void 0:Ce.brokerage)==null?void 0:Se.name)&&s.jsx("p",{className:"text-sm text-muted-foreground",children:n.agent.brokerage.name})]})]}),!W&&s.jsx("div",{className:"space-y-2",children:((je=n.agent)==null?void 0:je.email)&&s.jsx(de,{variant:"outline",className:"w-full",asChild:!0,children:s.jsxs("a",{href:`mailto:${n.agent.email}`,children:[s.jsx(Fo,{className:"h-4 w-4 mr-2"}),"Email Agent"]})})})]})]}),!W&&n.open_to_referrals&&s.jsxs(at,{children:[s.jsx(xr,{children:s.jsxs(wr,{className:"text-lg flex items-center gap-2",children:[s.jsx(_i,{className:"h-5 w-5"}),"Send a Buyer"]})}),s.jsxs(ct,{children:[s.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Have a buyer interested in this property? Send a referral to the listing agent."}),s.jsx(de,{className:"w-full",onClick:()=>A(!0),children:"Send Referral"})]})]})]})]})]}),s.jsx(mn,{open:!!I,onOpenChange:()=>O(null),children:s.jsx(pn,{className:"max-w-4xl",children:s.jsx("img",{src:I||"",alt:"Full size",className:"w-full h-auto"})})}),s.jsx(mn,{open:N,onOpenChange:C,children:s.jsxs(pn,{children:[s.jsxs(xn,{children:[s.jsx(gn,{children:"Delete Listing"}),s.jsx(fi,{children:"Are you sure you want to delete this listing? This action cannot be undone."})]}),s.jsxs(zi,{children:[s.jsx(de,{variant:"outline",onClick:()=>C(!1),children:"Cancel"}),s.jsx(de,{variant:"destructive",onClick:Q,disabled:_.isPending,children:_.isPending?"Deleting...":"Delete"})]})]})}),s.jsx(mn,{open:P,onOpenChange:A,children:s.jsxs(pn,{children:[s.jsxs(xn,{children:[s.jsx(gn,{children:"Send Buyer Referral"}),s.jsx(fi,{children:"Submit buyer information to the listing agent"})]}),s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Buyer Name *"}),s.jsx(Et,{value:R.buyerName,onChange:et=>z({...R,buyerName:et.target.value}),placeholder:"Enter buyer's name"})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Buyer Type"}),s.jsxs(Kn,{value:R.buyerType,onValueChange:et=>z({...R,buyerType:et}),children:[s.jsx(qn,{children:s.jsx(Zn,{placeholder:"Select type"})}),s.jsxs(Hn,{children:[s.jsx(_r,{value:"first_time",children:"First-Time Buyer"}),s.jsx(_r,{value:"investor",children:"Investor"}),s.jsx(_r,{value:"relocating",children:"Relocating"}),s.jsx(_r,{value:"upgrade",children:"Upgrading"}),s.jsx(_r,{value:"downsize",children:"Downsizing"})]})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Notes"}),s.jsx(mi,{value:R.notes,onChange:et=>z({...R,notes:et.target.value}),placeholder:"Any additional information..."})]})]}),s.jsxs(zi,{children:[s.jsx(de,{variant:"outline",onClick:()=>A(!1),children:"Cancel"}),s.jsx(de,{onClick:te,disabled:j.isPending,children:j.isPending?"Sending...":"Send Referral"})]})]})})]})}const Obt=[{value:"active",label:"Active"},{value:"coming_soon",label:"Coming Soon"},{value:"price_improvement",label:"Price Improvement"},{value:"under_contract",label:"Under Contract"},{value:"sold",label:"Sold"}],Rbt=[{value:"single_family",label:"Single Family"},{value:"condo",label:"Condo"},{value:"townhouse",label:"Townhouse"},{value:"land",label:"Land"},{value:"multi_family",label:"Multi-Family"},{value:"luxury",label:"Luxury"},{value:"commercial",label:"Commercial"},{value:"other",label:"Other"}];function ese(){var te;const{listingId:t}=mu(),e=Bs(),{user:r}=rn(),n=!!t&&t!=="new",{data:i,isLoading:o}=ppe(n?t:""),c=SBe(),a=NBe(),m=kBe(),g=TBe(),[_,j]=D.useState(!1),[N,C]=D.useState([]),[P,A]=D.useState([]),[I,O]=D.useState({property_address:"",city:"",state:"",neighborhood:"",price:"",property_type:"single_family",status:"active",bedrooms:"",bathrooms:"",square_footage:"",lot_size:"",year_built:"",has_hoa:!1,description:"",agent_notes:"",agent_notes_public:!1,mls_link:"",video_link:"",allow_sharing:!0,open_to_referrals:!0,open_to_social_promotion:!0,is_public:!0});D.useEffect(()=>{var X,ie,he,xe,pe;i&&n&&O({property_address:i.property_address||"",city:i.city||"",state:i.state||"",neighborhood:i.neighborhood||"",price:((X=i.price)==null?void 0:X.toString())||"",property_type:i.property_type,status:i.status,bedrooms:((ie=i.bedrooms)==null?void 0:ie.toString())||"",bathrooms:((he=i.bathrooms)==null?void 0:he.toString())||"",square_footage:((xe=i.square_footage)==null?void 0:xe.toString())||"",lot_size:i.lot_size||"",year_built:((pe=i.year_built)==null?void 0:pe.toString())||"",has_hoa:i.has_hoa,description:i.description||"",agent_notes:i.agent_notes||"",agent_notes_public:i.agent_notes_public,mls_link:i.mls_link||"",video_link:i.video_link||"",allow_sharing:i.allow_sharing,open_to_referrals:i.open_to_referrals,open_to_social_promotion:i.open_to_social_promotion,is_public:i.is_public})},[i,n]);const R=X=>{if(!X)return;const ie=Array.from(X);C(xe=>[...xe,...ie]);const he=ie.map(xe=>URL.createObjectURL(xe));A(xe=>[...xe,...he])},z=X=>{URL.revokeObjectURL(P[X]),C(ie=>ie.filter((he,xe)=>xe!==X)),A(ie=>ie.filter((he,xe)=>xe!==X))},W=async X=>{var ie;if(!(!X||!i)){j(!0);try{for(const he of Array.from(X)){const xe=he.name.split(".").pop(),pe=`${r==null?void 0:r.id}/${i.id}/${Date.now()}.${xe}`,{error:ve}=await ae.storage.from("listing-photos").upload(pe,he);if(ve)throw ve;const{data:{publicUrl:ge}}=ae.storage.from("listing-photos").getPublicUrl(pe);await m.mutateAsync({listingId:i.id,photoUrl:ge,isPrimary:!((ie=i.photos)!=null&&ie.length)})}Dt.success("Photos uploaded!")}catch(he){console.error("Upload error:",he),Dt.error("Failed to upload photos")}finally{j(!1)}}},V=async X=>{for(let ie=0;ie{if(i)try{await g.mutateAsync({photoId:X,listingId:i.id}),Dt.success("Photo removed")}catch{Dt.error("Failed to remove photo")}},Q=async X=>{if(X.preventDefault(),!I.city.trim()||!I.state.trim()||!I.price){Dt.error("Please fill in required fields (City, State, Price)");return}try{const ie={property_address:I.property_address||null,city:I.city,state:I.state,neighborhood:I.neighborhood||null,price:Number(I.price),property_type:I.property_type,status:I.status,bedrooms:I.bedrooms?Number(I.bedrooms):null,bathrooms:I.bathrooms?Number(I.bathrooms):null,square_footage:I.square_footage?Number(I.square_footage):null,lot_size:I.lot_size||null,year_built:I.year_built?Number(I.year_built):null,has_hoa:I.has_hoa,description:I.description||null,agent_notes:I.agent_notes||null,agent_notes_public:I.agent_notes_public,mls_link:I.mls_link||null,video_link:I.video_link||null,allow_sharing:I.allow_sharing,open_to_referrals:I.open_to_referrals,open_to_social_promotion:I.open_to_social_promotion,is_public:I.is_public};if(n)await a.mutateAsync({id:t,...ie}),Dt.success("Listing updated!"),e(`/innercircle/listings/${t}`);else{j(!0);const he=await c.mutateAsync(ie);if(N.length>0)try{await V(he.id),P.forEach(xe=>URL.revokeObjectURL(xe)),C([]),A([])}catch(xe){console.error("Photo upload error:",xe),Dt.error("Listing created but some photos failed to upload")}j(!1),Dt.success("Listing created!"),e(`/innercircle/listings/${he.id}`)}}catch(ie){console.error("Save error:",ie),Dt.error("Failed to save listing"),j(!1)}};return n&&o?s.jsx(Jr,{title:"Loading...",description:"",children:s.jsxs("div",{className:"space-y-6",children:[s.jsx(Dn,{className:"h-10 w-32"}),s.jsx(Dn,{className:"h-[600px] w-full"})]})}):s.jsx(Jr,{title:n?"Edit Listing":"Add Listing",description:"",children:s.jsxs("form",{onSubmit:Q,className:"space-y-6",children:[s.jsxs(de,{type:"button",variant:"ghost",onClick:()=>e("/innercircle/listings"),children:[s.jsx(Ka,{className:"h-4 w-4 mr-2"}),"Back to Listings"]}),s.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[s.jsxs("div",{className:"md:col-span-2 space-y-6",children:[s.jsxs(at,{children:[s.jsx(xr,{children:s.jsx(wr,{children:"Property Details"})}),s.jsx(ct,{className:"space-y-4",children:s.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[s.jsxs("div",{className:"sm:col-span-2 space-y-2",children:[s.jsx(mt,{children:"Property Address"}),s.jsx(Et,{value:I.property_address,onChange:X=>O({...I,property_address:X.target.value}),placeholder:"123 Main St"})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"City *"}),s.jsx(Et,{value:I.city,onChange:X=>O({...I,city:X.target.value}),placeholder:"City",required:!0})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"State *"}),s.jsx(Et,{value:I.state,onChange:X=>O({...I,state:X.target.value}),placeholder:"State",required:!0})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Neighborhood"}),s.jsx(Et,{value:I.neighborhood,onChange:X=>O({...I,neighborhood:X.target.value}),placeholder:"Neighborhood"})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Price *"}),s.jsx(Et,{type:"number",value:I.price,onChange:X=>O({...I,price:X.target.value}),placeholder:"500000",required:!0})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Property Type"}),s.jsxs(Kn,{value:I.property_type,onValueChange:X=>O({...I,property_type:X}),children:[s.jsx(qn,{children:s.jsx(Zn,{})}),s.jsx(Hn,{children:Rbt.map(X=>s.jsx(_r,{value:X.value,children:X.label},X.value))})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Status"}),s.jsxs(Kn,{value:I.status,onValueChange:X=>O({...I,status:X}),children:[s.jsx(qn,{children:s.jsx(Zn,{})}),s.jsx(Hn,{children:Obt.map(X=>s.jsx(_r,{value:X.value,children:X.label},X.value))})]})]})]})})]}),s.jsxs(at,{children:[s.jsx(xr,{children:s.jsx(wr,{children:"Property Specs (Optional)"})}),s.jsx(ct,{children:s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Bedrooms"}),s.jsx(Et,{type:"number",value:I.bedrooms,onChange:X=>O({...I,bedrooms:X.target.value}),placeholder:"3"})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Bathrooms"}),s.jsx(Et,{type:"number",step:"0.5",value:I.bathrooms,onChange:X=>O({...I,bathrooms:X.target.value}),placeholder:"2"})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Sq Ft"}),s.jsx(Et,{type:"number",value:I.square_footage,onChange:X=>O({...I,square_footage:X.target.value}),placeholder:"2000"})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Lot Size"}),s.jsx(Et,{value:I.lot_size,onChange:X=>O({...I,lot_size:X.target.value}),placeholder:"0.25 acres"})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Year Built"}),s.jsx(Et,{type:"number",value:I.year_built,onChange:X=>O({...I,year_built:X.target.value}),placeholder:"2005"})]}),s.jsxs("div",{className:"flex items-center gap-2 pt-6",children:[s.jsx(ri,{checked:I.has_hoa,onCheckedChange:X=>O({...I,has_hoa:X})}),s.jsx(mt,{children:"Has HOA"})]})]})})]}),s.jsxs(at,{children:[s.jsx(xr,{children:s.jsx(wr,{children:"Description & Links"})}),s.jsxs(ct,{className:"space-y-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Description"}),s.jsx(mi,{value:I.description,onChange:X=>O({...I,description:X.target.value}),placeholder:"Tell the story of this property...",rows:4})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Agent Notes"}),s.jsx(mi,{value:I.agent_notes,onChange:X=>O({...I,agent_notes:X.target.value}),placeholder:"Notes for other agents...",rows:2}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(ri,{checked:I.agent_notes_public,onCheckedChange:X=>O({...I,agent_notes_public:X})}),s.jsx(mt,{className:"text-sm text-muted-foreground",children:"Make notes visible to other agents"})]})]}),s.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"MLS Link"}),s.jsx(Et,{value:I.mls_link,onChange:X=>O({...I,mls_link:X.target.value}),placeholder:"https://..."})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Video Link"}),s.jsx(Et,{value:I.video_link,onChange:X=>O({...I,video_link:X.target.value}),placeholder:"YouTube or Vimeo URL"})]})]})]})]}),s.jsxs(at,{children:[s.jsx(xr,{children:s.jsx(wr,{children:"Photos"})}),s.jsxs(ct,{children:[s.jsxs("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-4",children:[n&&((te=i==null?void 0:i.photos)==null?void 0:te.map(X=>s.jsxs("div",{className:"relative aspect-square rounded-lg overflow-hidden bg-muted",children:[s.jsx("img",{src:X.photo_url,alt:"",className:"w-full h-full object-cover"}),s.jsx("button",{type:"button",onClick:()=>K(X.id),className:"absolute top-1 right-1 p-1 bg-destructive text-destructive-foreground rounded-full hover:bg-destructive/90",children:s.jsx(Ni,{className:"h-3 w-3"})}),X.is_primary&&s.jsx("span",{className:"absolute bottom-1 left-1 text-[10px] bg-primary text-primary-foreground px-1.5 py-0.5 rounded",children:"Primary"})]},X.id))),!n&&P.map((X,ie)=>s.jsxs("div",{className:"relative aspect-square rounded-lg overflow-hidden bg-muted",children:[s.jsx("img",{src:X,alt:"",className:"w-full h-full object-cover"}),s.jsx("button",{type:"button",onClick:()=>z(ie),className:"absolute top-1 right-1 p-1 bg-destructive text-destructive-foreground rounded-full hover:bg-destructive/90",children:s.jsx(Ni,{className:"h-3 w-3"})}),ie===0&&s.jsx("span",{className:"absolute bottom-1 left-1 text-[10px] bg-primary text-primary-foreground px-1.5 py-0.5 rounded",children:"Primary"})]},ie)),s.jsxs("label",{className:"aspect-square rounded-lg border-2 border-dashed border-muted-foreground/25 hover:border-muted-foreground/50 cursor-pointer flex flex-col items-center justify-center gap-2 text-muted-foreground",children:[_?s.jsx(Ps,{className:"h-8 w-8 animate-spin"}):s.jsxs(s.Fragment,{children:[s.jsx(Vu,{className:"h-8 w-8"}),s.jsx("span",{className:"text-xs",children:"Upload"})]}),s.jsx("input",{type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:X=>n?W(X.target.files):R(X.target.files),disabled:_})]})]}),!n&&N.length>0&&s.jsxs("p",{className:"text-sm text-muted-foreground mt-4",children:[N.length," photo",N.length!==1?"s":""," will be uploaded when you save."]})]})]})]}),s.jsxs("div",{className:"space-y-6",children:[s.jsxs(at,{children:[s.jsx(xr,{children:s.jsx(wr,{children:"Sharing & Collaboration"})}),s.jsxs(ct,{className:"space-y-4",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx(mt,{children:"Allow Sharing"}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Other agents can share this listing"})]}),s.jsx(ri,{checked:I.allow_sharing,onCheckedChange:X=>O({...I,allow_sharing:X})})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx(mt,{children:"Open to Referrals"}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Accept buyer referrals"})]}),s.jsx(ri,{checked:I.open_to_referrals,onCheckedChange:X=>O({...I,open_to_referrals:X})})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx(mt,{children:"Social Promotion"}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Can be promoted on social media"})]}),s.jsx(ri,{checked:I.open_to_social_promotion,onCheckedChange:X=>O({...I,open_to_social_promotion:X})})]}),s.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[s.jsxs("div",{children:[s.jsx(mt,{children:"Public Listing"}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"Visible to all LevelUp agents"})]}),s.jsx(ri,{checked:I.is_public,onCheckedChange:X=>O({...I,is_public:X})})]})]})]}),s.jsx(de,{type:"submit",className:"w-full",size:"lg",disabled:c.isPending||a.isPending,children:c.isPending||a.isPending?s.jsxs(s.Fragment,{children:[s.jsx(Ps,{className:"h-4 w-4 mr-2 animate-spin"}),"Saving..."]}):n?"Update Listing":"Create Listing"})]})]})]})})}function Dbt({maxDurationSeconds:t=30,onRecordingComplete:e,onError:r,onRecordingStateChange:n,className:i,teleprompterContent:o}){const c=D.useRef(null),a=D.useRef(null),m=D.useRef(null),g=D.useRef([]),_=D.useRef(null),j=D.useRef(null),N=D.useRef(null),C=D.useRef(null),P=jH(),[A,I]=D.useState(!0),[O,R]=D.useState(!0),[z,W]=D.useState(null),[V,K]=D.useState(!1),[Q,te]=D.useState(!1),[X,ie]=D.useState(null),[he,xe]=D.useState(null),[pe,ve]=D.useState(0),[ge,ke]=D.useState("user"),[Ce,Se]=D.useState(0),[je,et]=D.useState(!1),[bt,_e]=D.useState(!0),[Ye,pt]=D.useState(null),[nt,Qt]=D.useState(!1),gt=D.useCallback(We=>{I(We)},[]),Me=D.useRef(A),Oe=D.useCallback(async()=>{var _t;R(!0),pt(null);const We=P&&A;console.log("[VideoRecorder] initCamera start",{isMobile:P,usePortraitMode:A,shouldBePortrait:We,facingMode:ge});try{if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)throw new Error("Camera not available in this browser or context. Try opening in a new tab.");m.current&&(console.log("[VideoRecorder] stopping existing stream"),m.current.getTracks().forEach(Hr=>Hr.stop()));const Gt=P&&We?{facingMode:{ideal:ge},width:{ideal:720},height:{ideal:1280}}:{facingMode:{ideal:ge},width:{ideal:1280},height:{ideal:720}};console.log("[VideoRecorder] requesting getUserMedia",Gt);const rr=await navigator.mediaDevices.getUserMedia({video:Gt,audio:{echoCancellation:!0,noiseSuppression:!0}});if(console.log("[VideoRecorder] getUserMedia success"),rr.getVideoTracks().length===0)throw new Error("Camera stream started but no video track was provided.");m.current=rr,W(!0);const kr=rr.getVideoTracks()[0].getSettings();if(console.log("[VideoRecorder] Camera initialized with dimensions:",kr.width,"x",kr.height),c.current){const Hr=c.current;Hr.srcObject=rr,Hr.muted=!0,Hr.playsInline=!0,Hr.autoplay=!0,Hr.setAttribute("muted",""),Hr.setAttribute("playsinline",""),Hr.setAttribute("autoplay","");try{(_t=Hr.load)==null||_t.call(Hr)}catch(Os){console.warn("[VideoRecorder] videoEl.load failed",Os)}const Fn=async()=>{try{return await Hr.play(),console.log("[VideoRecorder] preview play ok"),Qt(!1),setTimeout(()=>{console.debug("[VideoRecorder] preview metrics",{readyState:Hr.readyState,videoWidth:Hr.videoWidth,videoHeight:Hr.videoHeight})},300),!0}catch(Os){return console.warn("[VideoRecorder] preview play blocked",Os),Qt(!0),!1}};await new Promise(Os=>{let ia=!1;const pa=()=>{ia||(ia=!0,Os())},zo=()=>{Fn().finally(pa)};Hr.onloadedmetadata=zo,Hr.onloadeddata=zo,setTimeout(pa,1500)})}try{j.current=new AudioContext;const Hr=j.current.createMediaStreamSource(rr);N.current=j.current.createAnalyser(),N.current.fftSize=256,Hr.connect(N.current);const Fn=()=>{if(N.current){const Os=new Uint8Array(N.current.frequencyBinCount);N.current.getByteFrequencyData(Os);const ia=Os.reduce((pa,zo)=>pa+zo)/Os.length;Se(Math.min(100,ia/128*100))}C.current=requestAnimationFrame(Fn)};Fn()}catch(Hr){console.warn("Audio context not available:",Hr)}}catch(Gt){console.error("Camera initialization error:",Gt),W(!1);let rr="Failed to access camera or microphone.";Gt.name==="NotAllowedError"?rr="Camera permission denied. Please allow camera access in your browser settings.":Gt.name==="NotFoundError"?rr="No camera found. Please connect a camera and try again.":Gt.name==="NotReadableError"?rr="Camera is in use by another application. Please close other apps using the camera.":Gt.message&&(rr=Gt.message),pt(rr),r==null||r(rr)}finally{R(!1)}},[ge,r,P,A]);D.useEffect(()=>{Me.current!==A&&z&&!V&&!he&&(Me.current=A,Oe())},[A,z,V,he,Oe]),D.useEffect(()=>(Oe(),()=>{m.current&&m.current.getTracks().forEach(We=>We.stop()),_.current&&clearInterval(_.current),C.current&&cancelAnimationFrame(C.current),j.current&&j.current.close(),he&&URL.revokeObjectURL(he)}),[Oe,he]),D.useEffect(()=>{if(O||z!==!0||he)return;const We=m.current,_t=c.current;!We||!_t||(_t.srcObject!==We&&(_t.srcObject=We,_t.muted=!0,_t.playsInline=!0,_t.autoplay=!0,_t.setAttribute("muted",""),_t.setAttribute("playsinline",""),_t.setAttribute("autoplay","")),_t.play().then(()=>Qt(!1)).catch(Gt=>{Qt(!0),console.warn("Live preview play blocked on mount:",Gt)}))},[z,O,he]),D.useEffect(()=>{n==null||n(V)},[V,n]);const Ie=D.useCallback(async()=>{if(he)return;const We=c.current;if(We)try{await We.play(),Qt(!1)}catch(_t){Qt(!0),console.warn("Live preview still blocked (needs user gesture):",_t)}},[he]),Be=D.useCallback(()=>{a.current&&a.current.state!=="inactive"&&a.current.stop(),_.current&&(clearInterval(_.current),_.current=null),K(!1),te(!1)},[]),Pe=D.useCallback(()=>{if(!m.current)return;Ie(),g.current=[],ve(0);const _t=["video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm"].find(rr=>MediaRecorder.isTypeSupported(rr)),Gt=new MediaRecorder(m.current,_t?{mimeType:_t,videoBitsPerSecond:25e5}:{videoBitsPerSecond:25e5});Gt.ondataavailable=rr=>{rr.data.size>0&&g.current.push(rr.data)},Gt.onstop=()=>{var Hr;const rr=Gt.mimeType||_t||((Hr=g.current[0])==null?void 0:Hr.type)||"video/webm",pr=new Blob(g.current,{type:rr});ie(pr);const kr=URL.createObjectURL(pr);xe(kr)},a.current=Gt,Gt.start(100),K(!0),_.current=setInterval(()=>{ve(rr=>rr>=t-1?(Be(),t):rr+1)},1e3)},[Ie,t,Be]),ut=D.useCallback(()=>{a.current&&a.current.state==="recording"&&(a.current.pause(),te(!0),_.current&&clearInterval(_.current))},[]),jt=D.useCallback(()=>{a.current&&a.current.state==="paused"&&(a.current.resume(),te(!1),_.current=setInterval(()=>{ve(We=>We>=t-1?(Be(),t):We+1)},1e3))},[t,Be]),$t=D.useCallback(()=>{he&&URL.revokeObjectURL(he),ie(null),xe(null),ve(0),et(!1),_e(!0),c.current&&m.current&&(c.current.srcObject=m.current,c.current.muted=!0,Ie())},[Ie,he]),Ht=D.useCallback(()=>{ke(We=>We==="user"?"environment":"user")},[]),Lt=D.useCallback(()=>{X&&e(X,pe)},[X,pe,e]),Kt=D.useCallback(()=>{c.current&&he&&(je?c.current.pause():(_e(!1),c.current.muted=!1,c.current.play()),et(!je))},[he,je]);D.useEffect(()=>{if(!he)return;const We=c.current;if(!We)return;_e(!1),We.pause(),We.removeAttribute("src"),We.srcObject=null,We.load(),We.src=he,We.currentTime=0,We.playsInline=!0,We.muted=!1,We.onended=()=>et(!1);const _t=()=>{const Gt=We.error,rr=Gt?`Recorded video failed to play (code ${Gt.code}). Likely unsupported format/codec in this browser.`:"Recorded video failed to play.";console.warn("[VideoRecorder] recorded playback error",Gt),r==null||r(rr)};return We.addEventListener("error",_t),We.load(),()=>{We.removeEventListener("error",_t)}},[r,he]);const Ar=We=>{const _t=Math.floor(We/60),Gt=We%60;return`${_t}:${Gt.toString().padStart(2,"0")}`},rt=P&&A?"aspect-[9/16]":"aspect-video";return O?s.jsx("div",{className:ar("flex items-center justify-center bg-black rounded-lg",rt,i),children:s.jsxs("div",{className:"text-center text-white",children:[s.jsx(Ps,{className:"h-12 w-12 animate-spin mx-auto mb-4"}),s.jsx("p",{children:"Initializing camera..."})]})}):z===!1?s.jsx("div",{className:ar("flex items-center justify-center bg-black rounded-lg",rt,i),children:s.jsxs("div",{className:"text-center text-white p-8 max-w-md",children:[s.jsx(sx,{className:"h-12 w-12 mx-auto mb-4 text-destructive"}),s.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Camera Access Required"}),s.jsx("p",{className:"text-gray-400 mb-4 text-sm",children:Ye||"Please allow camera and microphone access to record videos."}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs(de,{onClick:()=>Oe(),variant:"secondary",className:"w-full",children:[s.jsx(R1,{className:"h-4 w-4 mr-2"}),"Try Again"]}),s.jsx("p",{className:"text-xs text-gray-500 mt-3",children:"💡 Tip: If you're viewing this in an embedded preview, try opening the app in a new browser tab for full camera access."})]})]})}):s.jsxs("div",{className:ar("flex flex-col gap-2",i),children:[P&&!V&&!he&&s.jsxs("div",{className:"flex items-center justify-center gap-3 py-2 bg-muted/50 rounded-lg",children:[s.jsx(voe,{className:ar("h-4 w-4",A?"text-muted-foreground":"text-primary")}),s.jsx(mt,{htmlFor:"orientation-toggle",className:"text-sm text-muted-foreground",children:"Landscape"}),s.jsx(ri,{id:"orientation-toggle",checked:A,onCheckedChange:gt}),s.jsx(mt,{htmlFor:"orientation-toggle",className:"text-sm text-muted-foreground",children:"Portrait"}),s.jsx(V2e,{className:ar("h-4 w-4",A?"text-primary":"text-muted-foreground")})]}),s.jsxs("div",{className:ar("relative bg-black rounded-lg overflow-hidden"),onPointerDown:()=>{Ie()},children:[s.jsx("video",{ref:c,src:he??void 0,className:ar("w-full bg-black",A&&!he?"object-contain":"object-cover",rt,ge==="user"&&!he&&"scale-x-[-1]"),playsInline:!0,controls:!!he,muted:he?bt:!0,autoPlay:!he},he??"live"),!he&&nt&&s.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/40",children:s.jsx(de,{type:"button",variant:"secondary",onClick:()=>void Ie(),className:"bg-white/20 hover:bg-white/30 text-white",children:"Tap to enable preview"})}),o&&!he&&s.jsx("div",{className:"absolute inset-0 pointer-events-none",children:o}),V&&s.jsxs("div",{className:"absolute top-4 left-4 flex items-center gap-2 bg-black/50 px-3 py-1.5 rounded-full",children:[s.jsx("div",{className:ar("w-3 h-3 rounded-full",Q?"bg-yellow-500":"bg-red-500 animate-pulse")}),s.jsxs("span",{className:"text-white text-sm font-medium",children:[Ar(pe)," / ",Ar(t)]})]}),V&&s.jsx("div",{className:"absolute top-0 left-0 right-0",children:s.jsx(vc,{value:pe/t*100,className:"h-1 rounded-none"})}),!he&&s.jsxs("div",{className:"absolute bottom-20 left-4 flex items-center gap-2 bg-black/50 px-3 py-1.5 rounded-full",children:[s.jsx(D2e,{className:"h-4 w-4 text-white"}),s.jsx("div",{className:"w-20 h-2 bg-white/20 rounded-full overflow-hidden",children:s.jsx("div",{className:"h-full bg-green-500 transition-all duration-75",style:{width:`${Ce}%`}})})]}),s.jsx("div",{className:"absolute bottom-4 left-0 right-0 flex justify-center gap-3 px-4",children:he?s.jsxs(s.Fragment,{children:[s.jsxs(de,{variant:"secondary",size:"lg",className:"bg-white/20 hover:bg-white/30 text-white",onClick:$t,children:[s.jsx(R1,{className:"h-5 w-5 mr-2"}),"Re-record"]}),s.jsx(de,{variant:"secondary",size:"icon",className:"h-12 w-12 rounded-full bg-white/20 hover:bg-white/30 text-white",onClick:Kt,children:je?s.jsx(k5,{className:"h-5 w-5"}):s.jsx(Sf,{className:"h-5 w-5"})}),s.jsxs(de,{size:"lg",className:"bg-green-500 hover:bg-green-600 text-white",onClick:Lt,children:[s.jsx(ru,{className:"h-5 w-5 mr-2"}),"Use This Video"]})]}):s.jsxs(s.Fragment,{children:[s.jsx(de,{variant:"secondary",size:"icon",className:"h-12 w-12 rounded-full bg-white/20 hover:bg-white/30 text-white",onClick:Ht,disabled:V,children:s.jsx(woe,{className:"h-5 w-5"})}),V?s.jsxs(s.Fragment,{children:[s.jsx(de,{size:"icon",className:"h-12 w-12 rounded-full bg-white/20 hover:bg-white/30 text-white",onClick:Q?jt:ut,children:Q?s.jsx(Sf,{className:"h-5 w-5"}):s.jsx(k5,{className:"h-5 w-5"})}),s.jsx(de,{size:"icon",className:"h-16 w-16 rounded-full bg-red-500 hover:bg-red-600 text-white",onClick:Be,children:s.jsx(gM,{className:"h-6 w-6 fill-current"})})]}):s.jsx(de,{size:"icon",className:"h-16 w-16 rounded-full bg-red-500 hover:bg-red-600 text-white",onClick:Pe,children:s.jsx(Ia,{className:"h-6 w-6"})}),s.jsx("div",{className:"h-12 w-12"})]})})]})]})}function Lbt({text:t,isVisible:e,onToggleVisibility:r,isRecording:n=!1,className:i}){const o=D.useRef(null),c=D.useRef(null),a=D.useRef(0),[m,g]=D.useState(!1),[_,j]=D.useState(30),[N,C]=D.useState(24),[P,A]=D.useState(1.6),[I,O]=D.useState(.85),[R,z]=D.useState("top"),[W,V]=D.useState(!1),K=D.useCallback(ie=>{if(!o.current)return;a.current===0&&(a.current=ie);const he=ie-a.current;a.current=ie;const xe=_*he/1e3;o.current.scrollTop+=xe;const{scrollTop:pe,scrollHeight:ve,clientHeight:ge}=o.current;if(pe+ge>=ve){g(!1);return}c.current=requestAnimationFrame(K)},[_]);D.useEffect(()=>(m?(a.current=0,c.current=requestAnimationFrame(K)):c.current&&cancelAnimationFrame(c.current),()=>{c.current&&cancelAnimationFrame(c.current)}),[m,K]),D.useEffect(()=>{n&&e&&!m?(o.current&&(o.current.scrollTop=0),g(!0)):!n&&m&&g(!1)},[n,e]);const Q=D.useCallback(()=>{o.current&&(o.current.scrollTop=0),g(!1)},[]),te=D.useCallback(()=>{g(ie=>!ie)},[]);if(!e)return s.jsx("div",{className:ar("absolute top-4 right-4 pointer-events-auto z-10",i),children:s.jsxs(de,{variant:"secondary",size:"sm",onClick:r,className:"bg-black/50 hover:bg-black/70 text-white border-0",children:[s.jsx(Rc,{className:"h-4 w-4 mr-2"}),"Show Script"]})});const X={top:"top-0 pt-16",center:"top-1/2 -translate-y-1/2",bottom:"bottom-0 pb-24"};return s.jsxs("div",{className:ar("absolute inset-0 pointer-events-none",i),children:[s.jsx("div",{className:ar("absolute left-0 right-0 max-h-[40%] overflow-hidden pointer-events-auto",X[R]),style:{opacity:I},children:s.jsxs("div",{ref:o,className:ar("mx-auto max-w-2xl px-6 overflow-y-auto scrollbar-hide h-full",W&&"scale-x-[-1]"),style:{maskImage:"linear-gradient(to bottom, transparent, black 10%, black 90%, transparent)",WebkitMaskImage:"linear-gradient(to bottom, transparent, black 10%, black 90%, transparent)"},children:[s.jsx("p",{className:"text-white text-center font-medium drop-shadow-lg",style:{fontSize:`${N}px`,lineHeight:P,textShadow:"0 2px 4px rgba(0,0,0,0.8)"},children:t}),s.jsx("div",{className:"h-32"})]})}),s.jsxs("div",{className:"absolute top-4 right-4 flex items-center gap-2 pointer-events-auto",children:[s.jsxs(HD,{children:[s.jsx(WD,{asChild:!0,children:s.jsx(de,{variant:"secondary",size:"icon",className:"h-9 w-9 bg-black/50 hover:bg-black/70 text-white border-0",children:s.jsx(eg,{className:"h-4 w-4"})})}),s.jsx(RT,{className:"w-72",side:"left",align:"start",children:s.jsxs("div",{className:"space-y-4",children:[s.jsx("h4",{className:"font-medium",children:"Teleprompter Settings"}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{className:"text-xs",children:"Scroll Speed"}),s.jsx(Zv,{value:[_],onValueChange:([ie])=>j(ie),min:10,max:100,step:5})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{className:"text-xs",children:"Font Size"}),s.jsx(Zv,{value:[N],onValueChange:([ie])=>C(ie),min:16,max:48,step:2})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{className:"text-xs",children:"Line Spacing"}),s.jsx(Zv,{value:[P*10],onValueChange:([ie])=>A(ie/10),min:12,max:24,step:1})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{className:"text-xs",children:"Opacity"}),s.jsx(Zv,{value:[I*100],onValueChange:([ie])=>O(ie/100),min:30,max:100,step:5})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{className:"text-xs",children:"Position"}),s.jsxs("div",{className:"flex gap-1",children:[s.jsx(de,{variant:R==="top"?"default":"outline",size:"sm",onClick:()=>z("top"),children:s.jsx(W6,{className:"h-4 w-4"})}),s.jsx(de,{variant:R==="center"?"default":"outline",size:"sm",onClick:()=>z("center"),children:s.jsx(xoe,{className:"h-4 w-4"})}),s.jsx(de,{variant:R==="bottom"?"default":"outline",size:"sm",onClick:()=>z("bottom"),children:s.jsx(pT,{className:"h-4 w-4"})})]})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx(mt,{className:"text-xs",children:"Mirror Mode"}),s.jsx(ri,{checked:W,onCheckedChange:V})]})]})})]}),s.jsx(de,{variant:"secondary",size:"icon",onClick:te,className:"h-9 w-9 bg-black/50 hover:bg-black/70 text-white border-0",children:m?s.jsx(k5,{className:"h-4 w-4"}):s.jsx(Sf,{className:"h-4 w-4"})}),s.jsx(de,{variant:"secondary",size:"icon",onClick:Q,className:"h-9 w-9 bg-black/50 hover:bg-black/70 text-white border-0",children:s.jsx(woe,{className:"h-4 w-4"})}),s.jsxs(de,{variant:"secondary",size:"sm",onClick:r,className:"bg-black/50 hover:bg-black/70 text-white border-0",children:[s.jsx(Z6,{className:"h-4 w-4 mr-2"}),"Hide"]})]})]})}function Fbt({onSelectScript:t,onCreateNew:e,selectedScriptId:r,className:n}){const{toast:i}=Ri(),[o,c]=D.useState(""),[a,m]=D.useState(null),[g,_]=D.useState("levelup"),{data:j,isLoading:N}=o7e(),{data:C,isLoading:P}=l7e(),{data:A,isLoading:I}=c7e(),O=u7e(),R=D.useMemo(()=>C?C.filter(Q=>{const te=!o||Q.title.toLowerCase().includes(o.toLowerCase())||Q.script_text.toLowerCase().includes(o.toLowerCase())||Q.tags.some(ie=>ie.toLowerCase().includes(o.toLowerCase())),X=!a||Q.category_id===a;return te&&X}):[],[C,o,a]),z=D.useMemo(()=>A?A.filter(Q=>!o||Q.title.toLowerCase().includes(o.toLowerCase())||Q.script_text.toLowerCase().includes(o.toLowerCase())):[],[A,o]),W=Q=>{t({title:Q.title,text:Q.script_text})},V=async Q=>{try{await O.mutateAsync(Q),i({title:"Script saved to My Scripts"})}catch{i({title:"Failed to save script",variant:"destructive"})}},K=N||P||I;return s.jsxs("div",{className:ar("flex flex-col h-full",n),children:[s.jsx("div",{className:"p-4 border-b",children:s.jsxs("div",{className:"relative",children:[s.jsx(ba,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),s.jsx(Et,{placeholder:"Search scripts...",value:o,onChange:Q=>c(Q.target.value),className:"pl-9"})]})}),s.jsxs(go,{value:g,onValueChange:Q=>_(Q),className:"flex-1 flex flex-col",children:[s.jsxs(ao,{className:"mx-4 mt-4 grid grid-cols-2",children:[s.jsxs(Bn,{value:"levelup",children:[s.jsx(Ii,{className:"h-4 w-4 mr-2"}),"LevelUp Scripts"]}),s.jsxs(Bn,{value:"my-scripts",children:[s.jsx(g_,{className:"h-4 w-4 mr-2"}),"My Scripts"]})]}),s.jsxs(xs,{value:"levelup",className:"flex-1 flex flex-col mt-0 p-4",children:[s.jsxs("div",{className:"flex flex-wrap gap-2 mb-4",children:[s.jsx(ir,{variant:a?"outline":"default",className:"cursor-pointer",onClick:()=>m(null),children:"All"}),j==null?void 0:j.map(Q=>s.jsx(ir,{variant:a===Q.id?"default":"outline",className:"cursor-pointer",onClick:()=>m(Q.id),children:Q.name},Q.id))]}),s.jsx(qu,{className:"flex-1",children:K?s.jsx("div",{className:"flex items-center justify-center py-8",children:s.jsx(Ps,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):R.length===0?s.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[s.jsx(Ii,{className:"h-12 w-12 mx-auto mb-2 opacity-50"}),s.jsx("p",{children:"No scripts found"})]}):s.jsx("div",{className:"space-y-2",children:R.map(Q=>s.jsxs(at,{className:ar("cursor-pointer hover:bg-accent/50 transition-colors",r===Q.id&&"ring-2 ring-primary"),onClick:()=>W(Q),children:[s.jsx(xr,{className:"p-3",children:s.jsxs("div",{className:"flex items-start justify-between",children:[s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx(wr,{className:"text-sm font-medium truncate",children:Q.title}),Q.category&&s.jsx(ir,{variant:"secondary",className:"mt-1 text-xs",children:Q.category.name})]}),s.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[s.jsx(de,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:te=>{te.stopPropagation(),V(Q)},children:s.jsx(g_,{className:"h-4 w-4"})}),s.jsx(wd,{className:"h-4 w-4 text-muted-foreground"})]})]})}),s.jsx(ct,{className:"p-3 pt-0",children:s.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",children:Q.script_text})})]},Q.id))})})]}),s.jsxs(xs,{value:"my-scripts",className:"flex-1 flex flex-col mt-0 p-4",children:[e&&s.jsxs(de,{variant:"outline",className:"mb-4",onClick:e,children:[s.jsx(Qn,{className:"h-4 w-4 mr-2"}),"Create New Script"]}),s.jsx(qu,{className:"flex-1",children:I?s.jsx("div",{className:"flex items-center justify-center py-8",children:s.jsx(Ps,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):z.length===0?s.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[s.jsx(g_,{className:"h-12 w-12 mx-auto mb-2 opacity-50"}),s.jsx("p",{children:"No saved scripts"}),s.jsx("p",{className:"text-sm mt-1",children:"Save LevelUp scripts or create your own"})]}):s.jsx("div",{className:"space-y-2",children:z.map(Q=>s.jsxs(at,{className:ar("cursor-pointer hover:bg-accent/50 transition-colors",r===Q.id&&"ring-2 ring-primary"),onClick:()=>W(Q),children:[s.jsx(xr,{className:"p-3",children:s.jsxs("div",{className:"flex items-start justify-between",children:[s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx(wr,{className:"text-sm font-medium truncate",children:Q.title}),s.jsx("div",{className:"flex items-center gap-2 mt-1",children:Q.is_custom?s.jsx(ir,{variant:"outline",className:"text-xs",children:"Custom"}):s.jsx(ir,{variant:"secondary",className:"text-xs",children:"Saved"})})]}),s.jsx(wd,{className:"h-4 w-4 text-muted-foreground ml-2"})]})}),s.jsx(ct,{className:"p-3 pt-0",children:s.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",children:Q.script_text})})]},Q.id))})})]})]})]})}function zbt(){const t=Bs(),[e]=n0(),{toast:r}=Ri(),n=e.get("contact_id"),i=e.get("task_id"),{canRecord:o,remainingMb:c,usagePercent:a,isNearLimit:m}=m7e(),{data:g}=ig(),_=f7e(),j=v7e(),[N,C]=D.useState("record"),[P,A]=D.useState(""),[I,O]=D.useState(!1),[R,z]=D.useState(!1),[W,V]=D.useState(!1),[K,Q]=D.useState(null),[te,X]=D.useState(0),[ie,he]=D.useState(0),[xe,pe]=D.useState(null),[ve,ge]=D.useState(null),[ke,Ce]=D.useState(n||""),[Se,je]=D.useState(""),[et,bt]=D.useState(""),[_e,Ye]=D.useState(null),[pt,nt]=D.useState(null),[Qt,gt]=D.useState(null),Me=D.useCallback(async($t,Ht)=>{Q($t),C("uploading");try{const{videoId:Lt,uploadUrl:Kt}=await g7e(Se||"Quick Video Touch");pe(Lt);const{apiKey:Ar}=await y7e(Lt),rt=new XMLHttpRequest;rt.upload.onprogress=_t=>{_t.lengthComputable&&X(_t.loaded/_t.total*100)},await new Promise((_t,Gt)=>{rt.onload=()=>{rt.status>=200&&rt.status<300?_t():Gt(new Error(`Upload failed: ${rt.status}`))},rt.onerror=()=>Gt(new Error("Upload failed")),rt.open("PUT",Kt),rt.setRequestHeader("AccessKey",Ar),rt.send($t)}),C("processing");let We=0;for(;We<4;){await new Promise(Gt=>setTimeout(Gt,2e3));const _t=await x7e(Lt);if(We=_t.status,he(_t.encodeProgress||0),We===4)ge({playbackUrl:_t.directPlayUrl,thumbnailUrl:_t.thumbnailUrl,previewUrl:_t.previewUrl||null,duration:_t.length||Ht,fileSizeMb:(_t.storageSize||$t.size)/(1024*1024)});else if(We===5||We===6)throw new Error("Video processing failed")}C("details")}catch(Lt){console.error("Upload error:",Lt),r({title:"Upload failed",description:"Please try recording again.",variant:"destructive"}),C("record")}},[Se,r]),Oe=async()=>{if(!(!xe||!ve))try{const $t=await _.mutateAsync({bunny_video_id:xe,contact_id:ke||null,playback_url:ve.playbackUrl,thumbnail_url:ve.thumbnailUrl,preview_url:ve.previewUrl,duration_seconds:ve.duration,file_size_mb:ve.fileSizeMb,title:Se||"Quick Video Touch",notes:et,task_id:i||null,status:"ready"});Ye($t.id),nt($t.share_token||null),ke&&await j.mutateAsync({contactId:ke,videoId:$t.id,notes:et}),r({title:"Video saved successfully!"}),C("share")}catch($t){console.error("Save video error:",$t),r({title:"Failed to save video",description:($t==null?void 0:$t.message)||"Please try again.",variant:"destructive"})}},Ie=($t,Ht)=>{navigator.clipboard.writeText(Ht),gt($t),setTimeout(()=>gt(null),2e3),r({title:"Copied to clipboard!"})},Be=()=>pt?`https://video.relevelup.com/${pt}`:(ve==null?void 0:ve.playbackUrl)||"",Pe=()=>{const $t=g==null?void 0:g.find(rt=>rt.id===ke),Ht=$t?`${$t.first_name}`:"",Lt=($t==null?void 0:$t.phone)||"",Kt=($t==null?void 0:$t.email)||"",Ar=Be();return{text:`Hey${Ht?` ${Ht}`:""}! I recorded a quick video for you: ${Ar}`,link:Ar,contactPhone:Lt,contactEmail:Kt}},ut=()=>{const{text:$t,contactPhone:Ht}=Pe(),Lt=Ht?`sms:${Ht}?body=${encodeURIComponent($t)}`:`sms:?body=${encodeURIComponent($t)}`;window.open(Lt,"_self")},jt=()=>{const{link:$t,contactEmail:Ht}=Pe(),Lt="Check out this video",Kt=`I recorded a quick video for you: ${$t}`,Ar=Ht?`mailto:${Ht}?subject=${encodeURIComponent(Lt)}&body=${encodeURIComponent(Kt)}`:`mailto:?subject=${encodeURIComponent(Lt)}&body=${encodeURIComponent(Kt)}`;window.open(Ar,"_self")};return o?s.jsx(Jr,{title:"Quick Video Touch",children:s.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-4",children:[s.jsx(de,{variant:"ghost",size:"icon",onClick:()=>t(-1),children:s.jsx(Ka,{className:"h-5 w-5"})}),s.jsxs("div",{children:[s.jsx("h1",{className:"text-2xl font-bold",children:"Quick Video Touch"}),s.jsx("p",{className:"text-muted-foreground",children:"Record a personal video message"})]})]}),m&&s.jsxs("div",{className:"text-right",children:[s.jsxs("p",{className:"text-sm text-warning",children:["Storage: ",a.toFixed(0),"% used"]}),s.jsxs("p",{className:"text-xs text-muted-foreground",children:[c.toFixed(0)," MB remaining"]})]})]}),N==="record"&&s.jsxs("div",{className:"grid gap-6 lg:grid-cols-3",children:[s.jsxs("div",{className:"lg:col-span-2",children:[s.jsx(Dbt,{maxDurationSeconds:30,onRecordingComplete:Me,onRecordingStateChange:V,className:"w-full",teleprompterContent:I&&P&&s.jsx(Lbt,{text:P,isVisible:I,onToggleVisibility:()=>O(!1),isRecording:W})}),!I&&P&&s.jsxs(de,{variant:"outline",className:"mt-4",onClick:()=>O(!0),children:[s.jsx(Ii,{className:"h-4 w-4 mr-2"}),"Show Teleprompter"]})]}),s.jsxs(at,{className:"lg:col-span-1",children:[s.jsx(xr,{className:"pb-2",children:s.jsx(wr,{className:"text-lg",children:"Teleprompter Script"})}),s.jsxs(ct,{className:"space-y-4",children:[s.jsx(mi,{placeholder:"Type or paste your script here...",value:P,onChange:$t=>A($t.target.value),rows:6}),s.jsxs(Uue,{open:R,onOpenChange:z,children:[s.jsx(Vue,{asChild:!0,children:s.jsxs(de,{variant:"outline",className:"w-full",children:[s.jsx(Ii,{className:"h-4 w-4 mr-2"}),"Browse Scripts"]})}),s.jsxs(O8,{side:"right",className:"w-[400px] sm:w-[540px] p-0",children:[s.jsx(Hue,{className:"p-4 border-b",children:s.jsx(Wue,{children:"Select a Script"})}),s.jsx(Fbt,{onSelectScript:$t=>{A($t.text),z(!1),O(!0)},className:"h-[calc(100vh-80px)]"})]})]}),P&&s.jsx(de,{className:"w-full",onClick:()=>O(!0),children:"Use Script"})]})]})]}),N==="uploading"&&s.jsx(at,{className:"max-w-md mx-auto",children:s.jsxs(ct,{className:"pt-6 text-center",children:[s.jsx(Vu,{className:"h-12 w-12 mx-auto mb-4 text-primary animate-pulse"}),s.jsx("h2",{className:"text-lg font-semibold mb-2",children:"Uploading Video..."}),s.jsx(vc,{value:te,className:"mb-2"}),s.jsxs("p",{className:"text-sm text-muted-foreground",children:[te.toFixed(0),"%"]})]})}),N==="processing"&&s.jsx(at,{className:"max-w-md mx-auto",children:s.jsxs(ct,{className:"pt-6 text-center",children:[s.jsx(Ps,{className:"h-12 w-12 mx-auto mb-4 text-primary animate-spin"}),s.jsx("h2",{className:"text-lg font-semibold mb-2",children:"Processing Video..."}),s.jsx(vc,{value:ie,className:"mb-2"}),s.jsxs("p",{className:"text-sm text-muted-foreground",children:[ie.toFixed(0),"%"]})]})}),N==="details"&&s.jsxs(at,{className:"max-w-lg mx-auto",children:[s.jsx(xr,{children:s.jsx(wr,{children:"Video Details"})}),s.jsxs(ct,{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsx(mt,{children:"Title"}),s.jsx(Et,{value:Se,onChange:$t=>je($t.target.value),placeholder:"Quick Video Touch"})]}),s.jsxs("div",{children:[s.jsx(mt,{children:"Attach to Contact"}),s.jsxs(Kn,{value:ke,onValueChange:Ce,children:[s.jsx(qn,{children:s.jsx(Zn,{placeholder:"Select a contact..."})}),s.jsx(Hn,{children:g==null?void 0:g.map($t=>s.jsx(_r,{value:$t.id,children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(bf,{className:"h-4 w-4"}),$t.first_name," ",$t.last_name]})},$t.id))})]})]}),s.jsxs("div",{children:[s.jsx(mt,{children:"Notes"}),s.jsx(mi,{value:et,onChange:$t=>bt($t.target.value),placeholder:"Add notes about this video...",rows:3})]}),s.jsxs(de,{className:"w-full",onClick:Oe,disabled:_.isPending,children:[_.isPending&&s.jsx(Ps,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Video"]})]})]}),N==="share"&&s.jsxs(at,{className:"max-w-lg mx-auto",children:[s.jsx(xr,{children:s.jsxs(wr,{className:"flex items-center gap-2",children:[s.jsx(ru,{className:"h-5 w-5 text-green-500"}),"Video Saved!"]})}),s.jsxs(ct,{className:"space-y-4",children:[s.jsx("p",{className:"text-muted-foreground",children:"Share your video with one click:"}),s.jsxs("div",{className:"grid gap-3",children:[s.jsxs(de,{variant:"outline",className:"justify-start",onClick:ut,children:[s.jsx(Tf,{className:"h-4 w-4 mr-2"}),"Text Contact Video"]}),s.jsxs(de,{variant:"outline",className:"justify-start",onClick:jt,children:[s.jsx(Fo,{className:"h-4 w-4 mr-2"}),"Email Contact Video"]}),s.jsxs(de,{variant:"outline",className:"justify-start",onClick:()=>Ie("link",Pe().link),children:[s.jsx(Go,{className:"h-4 w-4 mr-2"}),"Copy Video Link",Qt==="link"&&s.jsx(ru,{className:"h-4 w-4 ml-auto text-green-500"})]})]}),s.jsxs("div",{className:"flex gap-3 pt-4",children:[s.jsx(de,{variant:"outline",onClick:()=>t("/innercircle/video-library"),children:"View Library"}),s.jsx(de,{onClick:()=>{C("record"),Q(null),pe(null),ge(null)},children:"Record Another"})]})]})]})]})}):s.jsx(Jr,{title:"Quick Video Touch",children:s.jsxs("div",{className:"max-w-2xl mx-auto text-center py-12",children:[s.jsx(yT,{className:"h-16 w-16 text-destructive mx-auto mb-4"}),s.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Storage Limit Reached"}),s.jsx("p",{className:"text-muted-foreground mb-6",children:"You've reached your video storage limit. Delete videos from your library to record more."}),s.jsx(de,{onClick:()=>t("/innercircle/video-library"),children:"Open Video Library"})]})})}function Bbt(){const t=Bs(),{data:e,isLoading:r}=d7e(),{data:n}=Lye(),{data:i}=ig(),o=p7e(),[c,a]=D.useState(""),[m,g]=D.useState(null),[_,j]=D.useState(!1),[N,C]=D.useState(!1),P=pe=>{if(!pe)return"Unassigned";const ve=i==null?void 0:i.find(ge=>ge.id===pe);return ve?`${ve.first_name} ${ve.last_name||""}`.trim():"Unknown"},A=pe=>{if(!pe)return"0:00";const ve=Math.floor(pe/60),ge=pe%60;return`${ve}:${ge.toString().padStart(2,"0")}`},I=e==null?void 0:e.filter(pe=>{if(!c)return!0;const ve=P(pe.contact_id).toLowerCase(),ge=(pe.title||"").toLowerCase(),ke=(pe.notes||"").toLowerCase();return ve.includes(c.toLowerCase())||ge.includes(c.toLowerCase())||ke.includes(c.toLowerCase())}),O=(n==null?void 0:n.total_storage_mb)||0,R=(n==null?void 0:n.max_storage_mb)||1024,z=O/R*100,W=z>=80,V=z>=100,K=async(pe,ve)=>{await navigator.clipboard.writeText(pe),Dt.success(`${ve} copied to clipboard`)},Q=pe=>pe.share_token?`https://video.relevelup.com/${pe.share_token}`:pe.playback_url||"",te=pe=>{const ve=Q(pe),ge=i==null?void 0:i.find(bt=>bt.id===pe.contact_id),ke=P(pe.contact_id),Ce=ke!=="Unassigned"?ke.split(" ")[0]:"",Se=(ge==null?void 0:ge.phone)||"",je=`Hey${Ce?` ${Ce}`:""}! I recorded a quick video message for you. Check it out: ${ve}`,et=Se?`sms:${Se}?body=${encodeURIComponent(je)}`:`sms:?body=${encodeURIComponent(je)}`;window.open(et,"_self")},X=pe=>{const ve=i==null?void 0:i.find(et=>et.id===pe.contact_id),ge=(ve==null?void 0:ve.email)||"",ke=Q(pe),Ce="Check out this video",Se=`I recorded a quick video for you: ${ke}`,je=ge?`mailto:${ge}?subject=${encodeURIComponent(Ce)}&body=${encodeURIComponent(Se)}`:`mailto:?subject=${encodeURIComponent(Ce)}&body=${encodeURIComponent(Se)}`;window.open(je,"_self")},ie=async pe=>{try{Dt.loading("Preparing download...",{id:"download"});const{data:ve,error:ge}=await ae.functions.invoke("bunny-upload",{body:{action:"download-url",videoId:pe.bunny_video_id,isAgentVideo:!0}});if(ge||!(ve!=null&&ve.downloadUrl))throw new Error((ge==null?void 0:ge.message)||"Failed to get download URL");const Ce=`${((pe.title||"video").toString().trim()||"video").replace(/[\\/:*?"<>|]+/g,"-")}.mp4`,Se=await fetch(ve.downloadUrl);if(!Se.ok)throw new Error("Failed to fetch video file");const je=await Se.blob(),et=URL.createObjectURL(je),bt=document.createElement("a");bt.href=et,bt.download=Ce,bt.rel="noreferrer",document.body.appendChild(bt),bt.click(),bt.remove(),URL.revokeObjectURL(et),Dt.success("Download started",{id:"download"})}catch(ve){console.error("Download error:",ve),Dt.error("Could not force download (your browser may block it).",{id:"download"})}},he=pe=>{g(pe),j(!0)},xe=async()=>{if(m)try{await o.mutateAsync({id:m.id,bunnyVideoId:m.bunny_video_id,hardDelete:!0}),C(!1),g(null),Dt.success("Video deleted successfully")}catch{Dt.error("Failed to delete video")}};return s.jsx(Jr,{title:"Video Library",description:"Manage your video touches",children:s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4",children:[s.jsxs("div",{children:[s.jsx("h1",{className:"text-2xl font-bold",children:"Video Library"}),s.jsx("p",{className:"text-muted-foreground",children:"Manage and share your video touches"})]}),s.jsxs(de,{onClick:()=>t("/innercircle/video/record"),children:[s.jsx(Qn,{className:"h-4 w-4 mr-2"}),"Record New Video"]})]}),s.jsx(at,{className:W?"border-amber-500":V?"border-destructive":"",children:s.jsxs(ct,{className:"py-4",children:[s.jsxs("div",{className:"flex items-center gap-4",children:[s.jsx(E2e,{className:`h-5 w-5 ${V?"text-destructive":W?"text-amber-500":"text-muted-foreground"}`}),s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex items-center justify-between mb-1",children:[s.jsx("span",{className:"text-sm font-medium",children:"Storage Used"}),s.jsxs("span",{className:"text-sm text-muted-foreground",children:[O.toFixed(1)," MB / ",R>=1024?`${(R/1024).toFixed(0)} GB`:`${R} MB`]})]}),s.jsx(vc,{value:Math.min(z,100),className:`h-2 ${V?"[&>div]:bg-destructive":W?"[&>div]:bg-amber-500":""}`})]}),W&&!V&&s.jsxs(ir,{variant:"outline",className:"border-amber-500 text-amber-600",children:[s.jsx(sx,{className:"h-3 w-3 mr-1"}),"Near Limit"]}),V&&s.jsxs(ir,{variant:"destructive",children:[s.jsx(sx,{className:"h-3 w-3 mr-1"}),"At Limit"]})]}),V&&s.jsx("p",{className:"text-sm text-destructive mt-2",children:"You've reached your storage limit. Delete videos to record more."})]})}),s.jsxs("div",{className:"relative",children:[s.jsx(ba,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),s.jsx(Et,{placeholder:"Search videos by contact, title, or notes...",value:c,onChange:pe=>a(pe.target.value),className:"pl-10"})]}),r?s.jsx("div",{className:"flex items-center justify-center py-12",children:s.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full"})}):(I==null?void 0:I.length)===0?s.jsx(at,{children:s.jsxs(ct,{className:"py-12 text-center",children:[s.jsx(Ia,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),s.jsx("h3",{className:"font-semibold mb-2",children:"No videos yet"}),s.jsx("p",{className:"text-muted-foreground mb-4",children:"Record your first video touch to get started"}),s.jsxs(de,{onClick:()=>t("/innercircle/video/record"),children:[s.jsx(Qn,{className:"h-4 w-4 mr-2"}),"Record Video"]})]})}):s.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-4",children:I==null?void 0:I.map(pe=>s.jsxs(at,{className:"overflow-hidden group cursor-pointer",onClick:()=>he(pe),children:[s.jsxs("div",{className:"relative aspect-video bg-muted",children:[pe.preview_url||pe.thumbnail_url?s.jsx("img",{src:pe.preview_url||pe.thumbnail_url,alt:pe.title||"Video thumbnail",loading:"lazy",crossOrigin:"anonymous",referrerPolicy:"no-referrer",className:"w-full h-full object-cover",onError:ve=>{var ke;const ge=ve.currentTarget;if(pe.preview_url&&ge.src===pe.preview_url&&pe.thumbnail_url)ge.src=pe.thumbnail_url;else{ge.style.display="none";const Ce=(ke=ge.parentElement)==null?void 0:ke.querySelector(".thumbnail-fallback");Ce&&(Ce.style.display="flex")}}}):null,s.jsx("div",{className:"thumbnail-fallback w-full h-full items-center justify-center",style:{display:pe.preview_url||pe.thumbnail_url?"none":"flex"},children:s.jsx(Ia,{className:"h-12 w-12 text-muted-foreground"})}),s.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity",children:s.jsx("div",{className:"w-12 h-12 rounded-full bg-white/90 flex items-center justify-center",children:s.jsx(Sf,{className:"h-6 w-6 text-primary ml-1"})})}),s.jsx("div",{className:"absolute bottom-2 right-2 bg-black/70 text-white text-xs px-1.5 py-0.5 rounded",children:A(pe.duration_seconds)}),pe.status!=="ready"&&s.jsx(ir,{variant:pe.status==="processing"?"secondary":"destructive",className:"absolute top-2 left-2",children:pe.status})]}),s.jsx(ct,{className:"p-3",children:s.jsxs("div",{className:"flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("h3",{className:"font-medium truncate",children:pe.title||"Untitled Video"}),s.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mt-1",children:[s.jsx(bf,{className:"h-3 w-3"}),s.jsx("span",{className:"truncate",children:P(pe.contact_id)})]}),s.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mt-0.5",children:[s.jsx(No,{className:"h-3 w-3"}),s.jsx("span",{children:Vn(new Date(pe.created_at),"MMM d, yyyy")})]})]}),s.jsxs(rg,{children:[s.jsx(ng,{asChild:!0,children:s.jsx(de,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:ve=>ve.stopPropagation(),children:s.jsx(coe,{className:"h-4 w-4"})})}),s.jsxs(Op,{align:"end",children:[s.jsxs(Ro,{onClick:ve=>{ve.stopPropagation(),he(pe)},children:[s.jsx(Rc,{className:"h-4 w-4 mr-2"}),"Watch"]}),s.jsxs(Ro,{onClick:ve=>{ve.stopPropagation(),K(Q(pe),"Share link")},children:[s.jsx(Go,{className:"h-4 w-4 mr-2"}),"Copy Share Link"]}),pe.contact_id&&s.jsxs(Ro,{onClick:ve=>{ve.stopPropagation(),t(`/innercircle/contacts/${pe.contact_id}`)},children:[s.jsx(bf,{className:"h-4 w-4 mr-2"}),"View Contact"]}),s.jsxs(Ro,{onClick:ve=>{ve.stopPropagation(),g(pe),C(!0)},className:"text-destructive",children:[s.jsx(oi,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})]})})]},pe.id))}),s.jsx(mn,{open:_,onOpenChange:j,children:s.jsxs(pn,{className:"max-w-2xl",children:[s.jsxs(xn,{children:[s.jsx(gn,{children:(m==null?void 0:m.title)||"Video Preview"}),s.jsx(fi,{children:(m==null?void 0:m.contact_id)&&s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(bf,{className:"h-3 w-3"}),P(m.contact_id)]})})]}),m&&s.jsxs("div",{className:"space-y-4",children:[s.jsx("div",{className:"relative w-full",style:{paddingBottom:"56.25%"},children:m.playback_url?(()=>{let pe=m.playback_url;return pe.includes("iframe.mediadelivery.net/play/")&&(pe=pe.replace("/play/","/embed/"),pe+=(pe.includes("?")?"&":"?")+"autoplay=false&responsive=true"),pe.includes("iframe.mediadelivery.net")?s.jsx("iframe",{src:pe,title:m.title||"Video preview",className:"absolute top-0 left-0 w-full h-full rounded-lg",style:{border:0},allow:"accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture",allowFullScreen:!0}):s.jsx("video",{src:m.playback_url,controls:!0,playsInline:!0,preload:"metadata",poster:m.thumbnail_url||void 0,className:"absolute top-0 left-0 w-full h-full rounded-lg object-cover",onError:()=>Dt.error("Video preview failed to load")},m.playback_url)})():s.jsxs("div",{className:"absolute inset-0 flex items-center justify-center bg-muted rounded-lg",children:[s.jsx(Ia,{className:"h-12 w-12 text-muted-foreground"}),s.jsx("p",{className:"text-muted-foreground ml-2",children:"Video not available"})]})}),s.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[s.jsxs(de,{variant:"outline",onClick:()=>te(m),children:[s.jsx(Tf,{className:"h-4 w-4 mr-2"}),"Text Contact Video"]}),s.jsxs(de,{variant:"outline",onClick:()=>X(m),children:[s.jsx(Fo,{className:"h-4 w-4 mr-2"}),"Email Contact Video"]}),s.jsxs(de,{variant:"outline",onClick:()=>K(Q(m),"Share link"),children:[s.jsx(ix,{className:"h-4 w-4 mr-2"}),"Copy Share Link"]}),s.jsxs(de,{variant:"outline",onClick:()=>ie(m),children:[s.jsx(Pp,{className:"h-4 w-4 mr-2"}),"Download Video"]})]}),s.jsx("div",{className:"flex justify-end pt-2 border-t",children:s.jsxs(de,{variant:"destructive",onClick:()=>{j(!1),C(!0)},children:[s.jsx(oi,{className:"h-4 w-4 mr-2"}),"Delete Video"]})})]})]})}),s.jsx(mn,{open:N,onOpenChange:C,children:s.jsxs(pn,{children:[s.jsxs(xn,{children:[s.jsx(gn,{children:"Delete Video"}),s.jsx(fi,{children:"Are you sure you want to delete this video? This action cannot be undone."})]}),s.jsxs(zi,{children:[s.jsx(de,{variant:"outline",onClick:()=>C(!1),children:"Cancel"}),s.jsx(de,{variant:"destructive",onClick:xe,disabled:o.isPending,children:o.isPending?"Deleting...":"Delete"})]})]})})]})})}const fbe=new Date().getFullYear(),$bt=Array.from({length:5},(t,e)=>fbe-e);function Ubt(){const[t,e]=D.useState(fbe),r=Bs(),{data:n,isLoading:i}=HBe();return i?s.jsx(Jr,{title:"Scorecard Admin",children:s.jsxs("div",{className:"space-y-6",children:[s.jsx(Dn,{className:"h-8 w-64"}),s.jsx("div",{className:"grid grid-cols-4 gap-4",children:[1,2,3,4].map(o=>s.jsx(Dn,{className:"h-24"},o))}),s.jsx(Dn,{className:"h-96"})]})}):s.jsx(Jr,{title:"Scorecard Admin",children:s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[s.jsxs("div",{children:[s.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Scorecard Admin"}),s.jsx("p",{className:"text-muted-foreground",children:"View agent performance and scorecards"})]}),s.jsxs(Kn,{value:String(t),onValueChange:o=>e(Number(o)),children:[s.jsx(qn,{className:"w-[120px]",children:s.jsx(Zn,{})}),s.jsx(Hn,{children:$bt.map(o=>s.jsx(_r,{value:String(o),children:o},o))})]})]}),s.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[s.jsx(at,{children:s.jsxs(ct,{className:"pt-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[s.jsx(_i,{className:"h-4 w-4"}),s.jsx("span",{className:"text-xs font-medium",children:"Agents Tracking"})]}),s.jsx("p",{className:"text-2xl font-bold",children:(n==null?void 0:n.length)||0})]})}),s.jsx(at,{children:s.jsxs(ct,{className:"pt-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[s.jsx(_p,{className:"h-4 w-4"}),s.jsx("span",{className:"text-xs font-medium",children:"Total Agents"})]}),s.jsx("p",{className:"text-2xl font-bold",children:(n==null?void 0:n.length)||0}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"with transactions"})]})})]}),s.jsxs(at,{children:[s.jsxs(xr,{children:[s.jsx(wr,{children:"Agents with Scorecards"}),s.jsx(us,{children:"Click to view individual agent scorecards"})]}),s.jsx(ct,{children:!n||n.length===0?s.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[s.jsx(_p,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),s.jsx("p",{children:"No agents have added transactions yet"})]}):s.jsxs(ni,{children:[s.jsx(si,{children:s.jsxs(Dr,{children:[s.jsx(Nt,{children:"Agent"}),s.jsx(Nt,{children:"Email"}),s.jsx(Nt,{className:"text-right",children:"Actions"})]})}),s.jsx(ii,{children:n.map(o=>s.jsxs(Dr,{children:[s.jsx(xt,{className:"font-medium",children:o.name}),s.jsx(xt,{className:"text-muted-foreground",children:o.email}),s.jsx(xt,{className:"text-right",children:s.jsxs(de,{variant:"ghost",size:"sm",onClick:()=>r(`/admin/scorecard/${o.id}`),children:[s.jsx(Rc,{className:"h-4 w-4 mr-2"}),"View Scorecard"]})})]},o.id))})]})})]})]})})}const pbe=new Date().getFullYear(),Vbt=Array.from({length:10},(t,e)=>pbe-e);function qbt(){var N;const{userId:t}=mu(),e=Bs(),[r,n]=D.useState(pbe),{data:i,isLoading:o}=Sr({queryKey:["agent-profile",t],queryFn:async()=>{const{data:C,error:P}=await ae.from("profiles").select("id, name, email").eq("id",t).single();if(P)throw P;return C},enabled:!!t}),{data:c,isLoading:a}=Tq(r,t),{yearStats:m,lifetimeStats:g,showCommission:_}=_pe(r,t),{data:j}=vpe(r,t);return o?s.jsx(Jr,{title:"Agent Scorecard",children:s.jsxs("div",{className:"space-y-6",children:[s.jsx(Dn,{className:"h-8 w-64"}),s.jsx("div",{className:"grid grid-cols-4 gap-4",children:[1,2,3,4].map(C=>s.jsx(Dn,{className:"h-24"},C))})]})}):s.jsx(Jr,{title:`${i==null?void 0:i.name}'s Scorecard`,children:s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[s.jsxs("div",{className:"flex items-center gap-4",children:[s.jsx(de,{variant:"ghost",size:"icon",onClick:()=>e("/admin/scorecard"),children:s.jsx(Ka,{className:"h-5 w-5"})}),s.jsxs("div",{children:[s.jsx("h1",{className:"text-2xl font-bold text-foreground",children:i==null?void 0:i.name}),s.jsx("p",{className:"text-muted-foreground",children:i==null?void 0:i.email})]})]}),s.jsxs(Kn,{value:String(r),onValueChange:C=>n(Number(C)),children:[s.jsx(qn,{className:"w-[120px]",children:s.jsx(Zn,{})}),s.jsx(Hn,{children:Vbt.map(C=>s.jsx(_r,{value:String(C),children:C},C))})]})]}),s.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-5 gap-4",children:[s.jsx(at,{children:s.jsxs(ct,{className:"pt-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[s.jsx(ou,{className:"h-4 w-4"}),s.jsx("span",{className:"text-xs font-medium",children:"Transactions"})]}),s.jsx("p",{className:"text-2xl font-bold",children:m.totalTransactions}),s.jsxs("p",{className:"text-xs text-muted-foreground",children:[g.totalTransactions," lifetime"]})]})}),s.jsx(at,{children:s.jsxs(ct,{className:"pt-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[s.jsx(_i,{className:"h-4 w-4"}),s.jsx("span",{className:"text-xs font-medium",children:"Buyer/Seller"})]}),s.jsxs("p",{className:"text-2xl font-bold",children:[m.buyerCount,"/",m.sellerCount]})]})}),s.jsx(at,{children:s.jsxs(ct,{className:"pt-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[s.jsx(M1,{className:"h-4 w-4"}),s.jsx("span",{className:"text-xs font-medium",children:"Volume"})]}),s.jsx("p",{className:"text-2xl font-bold",children:fc(m.totalVolume,!0)})]})}),s.jsx(at,{children:s.jsxs(ct,{className:"pt-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[s.jsx(r0,{className:"h-4 w-4"}),s.jsx("span",{className:"text-xs font-medium",children:"Avg Price"})]}),s.jsx("p",{className:"text-2xl font-bold",children:fc(m.averagePrice,!0)})]})}),s.jsx(at,{children:s.jsxs(ct,{className:"pt-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[s.jsx(Jw,{className:"h-4 w-4"}),s.jsx("span",{className:"text-xs font-medium",children:"Top Source"})]}),s.jsx("p",{className:"text-lg font-bold truncate",children:((N=m.topLeadSource)==null?void 0:N.name)||"-"})]})})]}),j&&s.jsx(vxe,{goals:j,stats:m,year:r,showCommission:_}),s.jsxs(go,{defaultValue:"transactions",className:"space-y-4",children:[s.jsxs(ao,{children:[s.jsx(Bn,{value:"transactions",children:"Transactions"}),s.jsx(Bn,{value:"charts",children:"Charts"})]}),s.jsx(xs,{value:"transactions",children:s.jsx(xxe,{transactions:c||[],showCommission:_,isLoading:a})}),s.jsx(xs,{value:"charts",children:s.jsx(cbe,{stats:m,year:r})})]})]})})}function Hbt(){const t=Wn(),[e,r]=D.useState(""),[n,i]=D.useState("all");$ue();const{data:o,refetch:c}=Sr({queryKey:["listing-exchange-flag"],queryFn:async()=>{const{data:R}=await ae.from("feature_flags").select("enabled").eq("key","listing_exchange_enabled").single();return(R==null?void 0:R.enabled)??!1}}),{data:a,isLoading:m}=Sr({queryKey:["admin-listings"],queryFn:async()=>{const{data:R,error:z}=await ae.from("listings").select(` *, agent:profiles!listings_agent_id_fkey(id, name, email), photos:listing_photos(id, photo_url, is_primary) `).order("created_at",{ascending:!1});if(z)throw z;return R}}),{data:g}=Sr({queryKey:["admin-listing-stats"],queryFn:async()=>{const{data:R}=await ae.from("listings").select("id, is_approved, status"),{data:z}=await ae.from("listing_shares").select("id"),{data:W}=await ae.from("listing_views").select("id");return{total:(R==null?void 0:R.length)||0,pending:(R==null?void 0:R.filter(V=>!V.is_approved).length)||0,active:(R==null?void 0:R.filter(V=>V.status==="active").length)||0,totalShares:(z==null?void 0:z.length)||0,totalViews:(W==null?void 0:W.length)||0}}}),_=zr({mutationFn:async({id:R,approved:z})=>{const{error:W}=await ae.from("listings").update({is_approved:z}).eq("id",R);if(W)throw W},onSuccess:(R,{approved:z})=>{t.invalidateQueries({queryKey:["admin-listings"]}),t.invalidateQueries({queryKey:["admin-listing-stats"]}),Dt.success(z?"Listing approved":"Listing unapproved")}}),j=zr({mutationFn:async({id:R,featured:z})=>{const{error:W}=await ae.from("listings").update({is_featured:z}).eq("id",R);if(W)throw W},onSuccess:(R,{featured:z})=>{t.invalidateQueries({queryKey:["admin-listings"]}),Dt.success(z?"Listing featured":"Listing unfeatured")}}),N=zr({mutationFn:async R=>{const{error:z}=await ae.from("listings").delete().eq("id",R);if(z)throw z},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-listings"]}),t.invalidateQueries({queryKey:["admin-listing-stats"]}),Dt.success("Listing deleted")}}),C=zr({mutationFn:async R=>{const{error:z}=await ae.from("feature_flags").update({enabled:R}).eq("key","listing_exchange_enabled");if(z)throw z},onSuccess:()=>{c(),Dt.success("Feature flag updated")}}),P=o??!1,A=a==null?void 0:a.filter(R=>{var V,K,Q,te;const z=((V=R.city)==null?void 0:V.toLowerCase().includes(e.toLowerCase()))||((Q=(K=R.agent)==null?void 0:K.name)==null?void 0:Q.toLowerCase().includes(e.toLowerCase()))||((te=R.property_address)==null?void 0:te.toLowerCase().includes(e.toLowerCase())),W=n==="all"||n==="pending"&&!R.is_approved||n==="approved"&&R.is_approved;return z&&W}),I=R=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(R),O=R=>{const z={active:"bg-green-500/10 text-green-600 border-green-200",coming_soon:"bg-blue-500/10 text-blue-600 border-blue-200",price_improvement:"bg-amber-500/10 text-amber-600 border-amber-200",under_contract:"bg-purple-500/10 text-purple-600 border-purple-200",sold:"bg-gray-500/10 text-gray-600 border-gray-200"};return z[R]||z.active};return s.jsx(Jr,{title:"Listing Exchange Admin",children:s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[s.jsxs("div",{children:[s.jsx("h1",{className:"text-2xl font-bold",children:"Listing Exchange"}),s.jsx("p",{className:"text-muted-foreground",children:"Manage community listings"})]}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"text-sm text-muted-foreground",children:"Feature visible to agents"}),s.jsx(ri,{checked:P,onCheckedChange:R=>C.mutate(R)})]})]}),s.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-4",children:[s.jsx(at,{children:s.jsxs(ct,{className:"p-4",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(yc,{className:"h-4 w-4 text-muted-foreground"}),s.jsx("span",{className:"text-sm text-muted-foreground",children:"Total Listings"})]}),s.jsx("p",{className:"text-2xl font-bold mt-1",children:(g==null?void 0:g.total)||0})]})}),s.jsx(at,{children:s.jsxs(ct,{className:"p-4",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(r0,{className:"h-4 w-4 text-green-500"}),s.jsx("span",{className:"text-sm text-muted-foreground",children:"Active"})]}),s.jsx("p",{className:"text-2xl font-bold mt-1",children:(g==null?void 0:g.active)||0})]})}),s.jsx(at,{children:s.jsxs(ct,{className:"p-4",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(_i,{className:"h-4 w-4 text-amber-500"}),s.jsx("span",{className:"text-sm text-muted-foreground",children:"Pending Review"})]}),s.jsx("p",{className:"text-2xl font-bold mt-1",children:(g==null?void 0:g.pending)||0})]})}),s.jsx(at,{children:s.jsxs(ct,{className:"p-4",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Rc,{className:"h-4 w-4 text-blue-500"}),s.jsx("span",{className:"text-sm text-muted-foreground",children:"Total Views"})]}),s.jsx("p",{className:"text-2xl font-bold mt-1",children:(g==null?void 0:g.totalViews)||0})]})}),s.jsx(at,{children:s.jsxs(ct,{className:"p-4",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(ph,{className:"h-4 w-4 text-purple-500"}),s.jsx("span",{className:"text-sm text-muted-foreground",children:"Total Shares"})]}),s.jsx("p",{className:"text-2xl font-bold mt-1",children:(g==null?void 0:g.totalShares)||0})]})})]}),s.jsx(at,{children:s.jsx(ct,{className:"p-4",children:s.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[s.jsxs("div",{className:"relative flex-1",children:[s.jsx(ba,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),s.jsx(Et,{placeholder:"Search by city, address, or agent...",value:e,onChange:R=>r(R.target.value),className:"pl-9"})]}),s.jsx(go,{value:n,onValueChange:R=>i(R),children:s.jsxs(ao,{children:[s.jsx(Bn,{value:"all",children:"All"}),s.jsx(Bn,{value:"pending",children:"Pending"}),s.jsx(Bn,{value:"approved",children:"Approved"})]})})]})})}),s.jsxs(at,{children:[s.jsx(xr,{children:s.jsxs(wr,{children:["Listings (",(A==null?void 0:A.length)||0,")"]})}),s.jsx(ct,{children:s.jsx("div",{className:"overflow-x-auto",children:s.jsxs(ni,{children:[s.jsx(si,{children:s.jsxs(Dr,{children:[s.jsx(Nt,{children:"Property"}),s.jsx(Nt,{children:"Agent"}),s.jsx(Nt,{children:"Price"}),s.jsx(Nt,{children:"Status"}),s.jsx(Nt,{className:"text-center",children:"Approved"}),s.jsx(Nt,{className:"text-center",children:"Featured"}),s.jsx(Nt,{children:"Views"}),s.jsx(Nt,{children:"Shares"}),s.jsx(Nt,{children:"Date"}),s.jsx(Nt,{})]})}),s.jsx(ii,{children:m?s.jsx(Dr,{children:s.jsx(xt,{colSpan:10,className:"text-center py-8 text-muted-foreground",children:"Loading..."})}):(A==null?void 0:A.length)===0?s.jsx(Dr,{children:s.jsx(xt,{colSpan:10,className:"text-center py-8 text-muted-foreground",children:"No listings found"})}):A==null?void 0:A.map(R=>{var z,W,V,K,Q;return s.jsxs(Dr,{children:[s.jsx(xt,{children:s.jsxs("div",{className:"flex items-center gap-3",children:[(W=(z=R.photos)==null?void 0:z[0])!=null&&W.photo_url?s.jsx("img",{src:R.photos[0].photo_url,alt:"",className:"w-12 h-12 object-cover rounded"}):s.jsx("div",{className:"w-12 h-12 bg-muted rounded flex items-center justify-center",children:s.jsx(yc,{className:"h-5 w-5 text-muted-foreground"})}),s.jsxs("div",{children:[s.jsx("p",{className:"font-medium text-sm",children:R.property_address||`${R.city}, ${R.state}`}),s.jsx("p",{className:"text-xs text-muted-foreground",children:(V=R.property_type)==null?void 0:V.replace("_"," ")})]})]})}),s.jsx(xt,{children:s.jsx("p",{className:"text-sm",children:((K=R.agent)==null?void 0:K.name)||"Unknown"})}),s.jsx(xt,{className:"font-medium",children:I(R.price)}),s.jsx(xt,{children:s.jsx(ir,{variant:"outline",className:O(R.status),children:(Q=R.status)==null?void 0:Q.replace("_"," ")})}),s.jsx(xt,{className:"text-center",children:s.jsx(ri,{checked:R.is_approved??!1,onCheckedChange:te=>_.mutate({id:R.id,approved:te})})}),s.jsx(xt,{className:"text-center",children:s.jsx(ri,{checked:R.is_featured??!1,onCheckedChange:te=>j.mutate({id:R.id,featured:te})})}),s.jsx(xt,{children:R.view_count||0}),s.jsx(xt,{children:R.share_count||0}),s.jsx(xt,{className:"text-sm text-muted-foreground",children:Vn(new Date(R.created_at),"MMM d, yyyy")}),s.jsx(xt,{children:s.jsxs(rg,{children:[s.jsx(ng,{asChild:!0,children:s.jsx(de,{variant:"ghost",size:"icon",children:s.jsx(K6,{className:"h-4 w-4"})})}),s.jsxs(Op,{align:"end",children:[s.jsxs(Ro,{onClick:()=>window.open(`/innercircle/listings/${R.id}`,"_blank"),children:[s.jsx(Rc,{className:"h-4 w-4 mr-2"}),"View Listing"]}),s.jsxs(Ro,{onClick:()=>j.mutate({id:R.id,featured:!R.is_featured}),children:[s.jsx(mh,{className:"h-4 w-4 mr-2"}),R.is_featured?"Unfeature":"Feature"]}),s.jsxs(Ro,{className:"text-destructive",onClick:()=>{confirm("Are you sure you want to delete this listing?")&&N.mutate(R.id)},children:[s.jsx(Ni,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})})]},R.id)})})]})})})]})]})})}const Wbt=()=>{const[t,e]=D.useState(""),{data:r,isLoading:n}=Sr({queryKey:["membership-reviews"],queryFn:async()=>{const{data:g,error:_}=await ae.from("membership_reviews").select("*").order("created_at",{ascending:!1});if(_)throw _;const j=(g==null?void 0:g.map(P=>P.user_id))||[],{data:N}=await ae.from("profiles").select("id, name, email").in("id",j);return g==null?void 0:g.map(P=>({...P,profiles:(N==null?void 0:N.find(A=>A.id===P.user_id))||null}))}}),i=r==null?void 0:r.filter(g=>{var j,N,C,P,A;const _=t.toLowerCase();return((N=(j=g.profiles)==null?void 0:j.name)==null?void 0:N.toLowerCase().includes(_))||((P=(C=g.profiles)==null?void 0:C.email)==null?void 0:P.toLowerCase().includes(_))||((A=g.review_text)==null?void 0:A.toLowerCase().includes(_))}),o=r!=null&&r.length?(r.reduce((g,_)=>g+_.rating,0)/r.length).toFixed(1):"0.0",c=r==null?void 0:r.reduce((g,_)=>(g[_.rating]=(g[_.rating]||0)+1,g),{}),a=(r==null?void 0:r.filter(g=>g.posted_to_google).length)||0,m=g=>s.jsx("div",{className:"flex gap-0.5",children:[1,2,3,4,5].map(_=>s.jsx(mh,{className:ar("h-4 w-4",g>=_?"fill-yellow-400 text-yellow-400":"text-muted-foreground")},_))});return s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{children:[s.jsx("h1",{className:"text-3xl font-bold tracking-tight",children:"Membership Reviews"}),s.jsx("p",{className:"text-muted-foreground",children:"View and manage feedback from LevelUp members"})]}),s.jsxs("div",{className:"grid gap-4 md:grid-cols-4",children:[s.jsx(at,{children:s.jsxs(xr,{className:"pb-2",children:[s.jsx(us,{children:"Total Reviews"}),s.jsx(wr,{className:"text-3xl",children:(r==null?void 0:r.length)||0})]})}),s.jsx(at,{children:s.jsxs(xr,{className:"pb-2",children:[s.jsx(us,{children:"Average Rating"}),s.jsxs(wr,{className:"flex items-center gap-2 text-3xl",children:[o,s.jsx(mh,{className:"h-6 w-6 fill-yellow-400 text-yellow-400"})]})]})}),s.jsx(at,{children:s.jsxs(xr,{className:"pb-2",children:[s.jsx(us,{children:"5-Star Reviews"}),s.jsx(wr,{className:"text-3xl",children:(c==null?void 0:c[5])||0})]})}),s.jsx(at,{children:s.jsxs(xr,{className:"pb-2",children:[s.jsx(us,{children:"Posted to Google"}),s.jsxs(wr,{className:"flex items-center gap-2 text-3xl",children:[a,s.jsx(oa,{className:"h-5 w-5 text-muted-foreground"})]})]})})]}),s.jsxs("div",{className:"relative max-w-sm",children:[s.jsx(ba,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),s.jsx(Et,{placeholder:"Search by name, email, or review...",value:t,onChange:g=>e(g.target.value),className:"pl-9"})]}),s.jsx(at,{children:s.jsx(ct,{className:"p-0",children:s.jsxs(ni,{children:[s.jsx(si,{children:s.jsxs(Dr,{children:[s.jsx(Nt,{children:"Member"}),s.jsx(Nt,{children:"Rating"}),s.jsx(Nt,{className:"hidden md:table-cell",children:"Review"}),s.jsx(Nt,{children:"Google"}),s.jsx(Nt,{children:"Date"})]})}),s.jsx(ii,{children:n?s.jsx(Dr,{children:s.jsx(xt,{colSpan:5,className:"text-center py-8",children:"Loading reviews..."})}):(i==null?void 0:i.length)===0?s.jsx(Dr,{children:s.jsx(xt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No reviews found"})}):i==null?void 0:i.map(g=>{var _,j;return s.jsxs(Dr,{children:[s.jsx(xt,{children:s.jsxs("div",{children:[s.jsx("div",{className:"font-medium",children:((_=g.profiles)==null?void 0:_.name)||"Unknown"}),s.jsx("div",{className:"text-sm text-muted-foreground",children:(j=g.profiles)==null?void 0:j.email})]})}),s.jsx(xt,{children:m(g.rating)}),s.jsx(xt,{className:"hidden md:table-cell max-w-xs",children:s.jsx("p",{className:"truncate text-sm text-muted-foreground",children:g.review_text||"-"})}),s.jsx(xt,{children:g.posted_to_google?s.jsx(ir,{variant:"secondary",className:"bg-green-100 text-green-800",children:"Posted"}):s.jsx(ir,{variant:"outline",children:"No"})}),s.jsx(xt,{className:"text-sm text-muted-foreground",children:Vn(new Date(g.created_at),"MMM d, yyyy")})]},g.id)})})]})})})]})},Gbt=[{value:"0",label:"Sunday"},{value:"1",label:"Monday"},{value:"2",label:"Tuesday"},{value:"3",label:"Wednesday"},{value:"4",label:"Thursday"},{value:"5",label:"Friday"},{value:"6",label:"Saturday"}],Kbt=Array.from({length:24},(t,e)=>({value:String(e),label:e===0?"12:00 AM":e<12?`${e}:00 AM`:e===12?"12:00 PM":`${e-12}:00 PM`}));function Zbt(){var A;const t=Wn(),{user:e}=rn(),[r,n]=D.useState(!1),[i,o]=D.useState(!1),{data:c,isLoading:a}=Sr({queryKey:["weekly-digest-settings"],queryFn:async()=>{const{data:I,error:O}=await ae.from("weekly_digest_settings").select("*").single();if(O)throw O;return I}}),{data:m,isLoading:g}=Sr({queryKey:["weekly-digest-logs"],queryFn:async()=>{const{data:I,error:O}=await ae.from("weekly_digest_logs").select("*").order("sent_at",{ascending:!1}).limit(100);if(O)throw O;return I}}),{data:_}=Sr({queryKey:["digest-subscriber-count"],queryFn:async()=>{const{count:I,error:O}=await ae.from("profiles").select("id",{count:"exact",head:!0}).eq("digest_opt_out",!1).not("email","is",null);if(O)throw O;return I||0}}),j=zr({mutationFn:async I=>{const{error:O}=await ae.from("weekly_digest_settings").update(I).eq("id",c==null?void 0:c.id);if(O)throw O},onSuccess:()=>{t.invalidateQueries({queryKey:["weekly-digest-settings"]}),Dt.success("Settings updated")},onError:I=>{Dt.error("Failed to update settings: "+I.message)}}),N=async()=>{n(!0);try{const{data:I,error:O}=await ae.functions.invoke("send-weekly-digest",{body:{manual:!0}});if(O)throw O;Dt.success(`Digest sent! ${I.sent} emails delivered, ${I.failed} failed`),t.invalidateQueries({queryKey:["weekly-digest-logs"]})}catch(I){Dt.error("Failed to send digest: "+I.message)}finally{n(!1)}},C=async()=>{if(!(e!=null&&e.email)){Dt.error("No email found for your account");return}o(!0);try{const{data:I,error:O}=await ae.functions.invoke("send-weekly-digest",{body:{preview:!0,previewEmail:e.email}});if(O)throw O;Dt.success(`Preview sent to ${e.email}`)}catch(I){Dt.error("Failed to send preview: "+I.message)}finally{o(!1)}},P={totalSent:(m==null?void 0:m.filter(I=>I.delivery_status==="sent").length)||0,totalFailed:(m==null?void 0:m.filter(I=>I.delivery_status==="failed").length)||0,lastSent:(A=m==null?void 0:m[0])==null?void 0:A.sent_at,agentOsEngaged:(m==null?void 0:m.filter(I=>I.has_agent_os_activity).length)||0};return a?s.jsx(Jr,{title:"Weekly Digest",description:"Manage automated weekly email digests",children:s.jsxs("div",{className:"animate-pulse space-y-4",children:[s.jsx("div",{className:"h-32 bg-muted rounded-lg"}),s.jsx("div",{className:"h-64 bg-muted rounded-lg"})]})}):s.jsx(Jr,{title:"Weekly Digest",description:"Configure and manage automated weekly email digests for members",children:s.jsxs(go,{defaultValue:"settings",className:"space-y-6",children:[s.jsxs(ao,{children:[s.jsxs(Bn,{value:"settings",className:"flex items-center gap-2",children:[s.jsx(eg,{className:"h-4 w-4"}),"Settings"]}),s.jsxs(Bn,{value:"stats",className:"flex items-center gap-2",children:[s.jsx(_p,{className:"h-4 w-4"}),"Delivery Stats"]})]}),s.jsxs(xs,{value:"settings",className:"space-y-6",children:[s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[s.jsx(at,{children:s.jsx(ct,{className:"pt-6",children:s.jsxs("div",{className:"flex items-center gap-4",children:[s.jsx("div",{className:"p-3 rounded-full bg-primary/10",children:s.jsx(_i,{className:"h-5 w-5 text-primary"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-2xl font-bold",children:_}),s.jsx("p",{className:"text-sm text-muted-foreground",children:"Subscribers"})]})]})})}),s.jsx(at,{children:s.jsx(ct,{className:"pt-6",children:s.jsxs("div",{className:"flex items-center gap-4",children:[s.jsx("div",{className:"p-3 rounded-full bg-green-500/10",children:s.jsx(E_,{className:"h-5 w-5 text-green-500"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-2xl font-bold",children:P.totalSent}),s.jsx("p",{className:"text-sm text-muted-foreground",children:"Delivered"})]})]})})}),s.jsx(at,{children:s.jsx(ct,{className:"pt-6",children:s.jsxs("div",{className:"flex items-center gap-4",children:[s.jsx("div",{className:"p-3 rounded-full bg-red-500/10",children:s.jsx(W2,{className:"h-5 w-5 text-red-500"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-2xl font-bold",children:P.totalFailed}),s.jsx("p",{className:"text-sm text-muted-foreground",children:"Failed"})]})]})})}),s.jsx(at,{children:s.jsx(ct,{className:"pt-6",children:s.jsxs("div",{className:"flex items-center gap-4",children:[s.jsx("div",{className:"p-3 rounded-full bg-blue-500/10",children:s.jsx(No,{className:"h-5 w-5 text-blue-500"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-2xl font-bold",children:P.lastSent?Vn(new Date(P.lastSent),"MMM d"):"Never"}),s.jsx("p",{className:"text-sm text-muted-foreground",children:"Last Sent"})]})]})})})]}),s.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[s.jsxs(at,{children:[s.jsxs(xr,{children:[s.jsxs(wr,{className:"flex items-center gap-2",children:[s.jsx(No,{className:"h-5 w-5"}),"Schedule"]}),s.jsx(us,{children:"Configure when the digest is sent"})]}),s.jsxs(ct,{className:"space-y-6",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx(mt,{children:"Enable Weekly Digest"}),s.jsx("p",{className:"text-sm text-muted-foreground",children:"Send automated weekly emails to members"})]}),s.jsx(ri,{checked:c==null?void 0:c.is_enabled,onCheckedChange:I=>j.mutate({is_enabled:I})})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Cron Frequency"}),s.jsxs(Kn,{value:(c==null?void 0:c.cron_frequency)||"daily",onValueChange:I=>j.mutate({cron_frequency:I}),children:[s.jsx(qn,{children:s.jsx(Zn,{})}),s.jsxs(Hn,{children:[s.jsx(_r,{value:"daily",children:"Daily (runs once at selected time)"}),s.jsx(_r,{value:"hourly",children:"Hourly (checks every hour)"})]})]}),s.jsx("p",{className:"text-xs text-muted-foreground",children:(c==null?void 0:c.cron_frequency)==="hourly"?"Cron runs every hour; digest sends when day & hour match.":"Cron runs once daily at the selected hour (UTC)."})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Day of Week"}),s.jsxs(Kn,{value:String(c==null?void 0:c.send_day),onValueChange:I=>j.mutate({send_day:parseInt(I)}),children:[s.jsx(qn,{children:s.jsx(Zn,{})}),s.jsx(Hn,{children:Gbt.map(I=>s.jsx(_r,{value:I.value,children:I.label},I.value))})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(mt,{children:"Time (UTC)"}),s.jsxs(Kn,{value:String(c==null?void 0:c.send_hour),onValueChange:I=>j.mutate({send_hour:parseInt(I)}),disabled:(c==null?void 0:c.cron_frequency)==="daily",children:[s.jsx(qn,{children:s.jsx(Zn,{})}),s.jsx(Hn,{children:Kbt.map(I=>s.jsx(_r,{value:I.value,children:I.label},I.value))})]})]})]}),s.jsxs("div",{className:"flex gap-2",children:[s.jsxs(de,{onClick:C,disabled:i,variant:"outline",className:"flex-1",children:[s.jsx(Rc,{className:"h-4 w-4 mr-2"}),i?"Sending...":"Send Preview to Me"]}),s.jsxs(de,{onClick:N,disabled:r,className:"flex-1",children:[s.jsx(Dc,{className:"h-4 w-4 mr-2"}),r?"Sending...":"Send to All"]})]})]})]}),s.jsxs(at,{children:[s.jsxs(xr,{children:[s.jsxs(wr,{className:"flex items-center gap-2",children:[s.jsx(Ii,{className:"h-5 w-5"}),"Content Sections"]}),s.jsx(us,{children:"Choose what to include in the digest"})]}),s.jsxs(ct,{className:"space-y-4",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Ii,{className:"h-4 w-4 text-muted-foreground"}),s.jsx(mt,{children:"New Resources"})]}),s.jsx(ri,{checked:c==null?void 0:c.include_new_resources,onCheckedChange:I=>j.mutate({include_new_resources:I})})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(_p,{className:"h-4 w-4 text-muted-foreground"}),s.jsx(mt,{children:"Agent OS Stats"})]}),s.jsx(ri,{checked:c==null?void 0:c.include_agent_os_stats,onCheckedChange:I=>j.mutate({include_agent_os_stats:I})})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(ko,{className:"h-4 w-4 text-muted-foreground"}),s.jsx(mt,{children:"Upcoming Events"})]}),s.jsx(ri,{checked:c==null?void 0:c.include_upcoming_events,onCheckedChange:I=>j.mutate({include_upcoming_events:I})})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(rD,{className:"h-4 w-4 text-muted-foreground"}),s.jsx(mt,{children:"Goals Progress"})]}),s.jsx(ri,{checked:c==null?void 0:c.include_goals_progress,onCheckedChange:I=>j.mutate({include_goals_progress:I})})]})]})]})]}),s.jsxs(at,{children:[s.jsxs(xr,{children:[s.jsx(wr,{children:"Custom Introduction"}),s.jsx(us,{children:"Personalize the intro message (optional)"})]}),s.jsx(ct,{children:s.jsx(mi,{placeholder:"Here's what's new this week to help you grow your business...",value:(c==null?void 0:c.custom_intro_text)||"",onChange:I=>j.mutate({custom_intro_text:I.target.value||null}),rows:3})})]})]}),s.jsx(xs,{value:"stats",children:s.jsxs(at,{children:[s.jsxs(xr,{children:[s.jsxs(wr,{className:"flex items-center gap-2",children:[s.jsx(Fo,{className:"h-5 w-5"}),"Delivery History"]}),s.jsx(us,{children:"Recent digest emails sent to members"})]}),s.jsx(ct,{children:g?s.jsx("div",{className:"animate-pulse space-y-2",children:[1,2,3,4,5].map(I=>s.jsx("div",{className:"h-12 bg-muted rounded"},I))}):m&&m.length>0?s.jsxs(ni,{children:[s.jsx(si,{children:s.jsxs(Dr,{children:[s.jsx(Nt,{children:"Email"}),s.jsx(Nt,{children:"Sent At"}),s.jsx(Nt,{children:"Status"}),s.jsx(Nt,{children:"Resources"}),s.jsx(Nt,{children:"Agent OS"})]})}),s.jsx(ii,{children:m.map(I=>s.jsxs(Dr,{children:[s.jsx(xt,{className:"font-medium",children:I.email_sent_to}),s.jsx(xt,{children:Vn(new Date(I.sent_at),"MMM d, yyyy h:mm a")}),s.jsx(xt,{children:s.jsx(ir,{variant:I.delivery_status==="sent"?"default":"destructive",children:I.delivery_status})}),s.jsx(xt,{children:I.resources_count}),s.jsx(xt,{children:I.has_agent_os_activity?s.jsx(ir,{variant:"secondary",children:"Active"}):s.jsx(ir,{variant:"outline",children:"Not Started"})})]},I.id))})]}):s.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[s.jsx(Fo,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),s.jsx("p",{children:"No digests sent yet"}),s.jsx("p",{className:"text-sm",children:"Send your first digest to see delivery stats"})]})})]})})]})})}const Ybt=()=>{const t=xx();return D.useEffect(()=>{console.error("404 Error: User attempted to access non-existent route:",t.pathname)},[t.pathname]),s.jsx("div",{className:"flex min-h-screen items-center justify-center bg-gray-100",children:s.jsxs("div",{className:"text-center",children:[s.jsx("h1",{className:"mb-4 text-4xl font-bold",children:"404"}),s.jsx("p",{className:"mb-4 text-xl text-gray-600",children:"Oops! Page not found"}),s.jsx("a",{href:"/",className:"text-blue-500 underline hover:text-blue-700",children:"Return to Home"})]})})},Xbt=new lAe,Qbt=()=>s.jsx(fAe,{client:Xbt,children:s.jsx(Hle,{children:s.jsxs(fle,{children:[s.jsx(Eke,{}),s.jsx(oTe,{}),s.jsx(jPe,{children:s.jsx(EOe,{children:s.jsxs(mPe,{children:[s.jsx(jn,{path:"/",element:s.jsx($Re,{})}),s.jsx(jn,{path:"/auth",element:s.jsx(gDe,{})}),s.jsx(jn,{path:"/subscription-success",element:s.jsx(yDe,{})}),s.jsx(jn,{path:"/share/video/:shareToken",element:s.jsx(DDe,{})}),s.jsx(jn,{path:"/og/video/:token",element:s.jsx(LDe,{})}),s.jsx(jn,{path:"/setup-brokerage",element:s.jsx(Un,{children:s.jsx(xDe,{})})}),s.jsx(jn,{path:"/claim-account",element:s.jsx(vDe,{})}),s.jsx(jn,{path:"/join",element:s.jsx(_De,{})}),s.jsx(jn,{path:"/dashboard",element:s.jsx(Un,{children:s.jsx(XBe,{})})}),s.jsx(jn,{path:"/profile",element:s.jsx(Un,{children:s.jsx(R5e,{})})}),s.jsx(jn,{path:"/apps",element:s.jsx(Un,{children:s.jsx(z5e,{})})}),s.jsx(jn,{path:"/admin",element:s.jsx(Un,{requireAdmin:!0,children:s.jsx(j$e,{})})}),s.jsx(jn,{path:"/admin/apps",element:s.jsx(Un,{requireAdmin:!0,children:s.jsx(C$e,{})})}),s.jsx(jn,{path:"/admin/members",element:s.jsx(Un,{requireAdmin:!0,children:s.jsx(k$e,{})})}),s.jsx(jn,{path:"/admin/invite-codes",element:s.jsx(Un,{requireAdmin:!0,children:s.jsx(T$e,{})})}),s.jsx(jn,{path:"/admin/events",element:s.jsx(Un,{requireAdmin:!0,children:s.jsx(t9e,{})})}),s.jsx(jn,{path:"/events",element:s.jsx(Un,{children:s.jsx(D5e,{})})}),s.jsx(jn,{path:"/events/:eventId",element:s.jsx(Un,{children:s.jsx(F5e,{})})}),s.jsx(jn,{path:"/templates",element:s.jsx(Un,{children:s.jsx(B5e,{})})}),s.jsx(jn,{path:"/templates/:templateId",element:s.jsx(Un,{children:s.jsx(q5e,{})})}),s.jsx(jn,{path:"/admin/templates",element:s.jsx(Un,{requireAdmin:!0,children:s.jsx(r9e,{})})}),s.jsx(jn,{path:"/academy",element:s.jsx(Un,{children:s.jsx(K5e,{})})}),s.jsx(jn,{path:"/academy/:videoId",element:s.jsx(Un,{children:s.jsx(Y5e,{})})}),s.jsx(jn,{path:"/admin/academy",element:s.jsx(Un,{requireAdmin:!0,children:s.jsx(s9e,{})})}),s.jsx(jn,{path:"/toolbox",element:s.jsx(Un,{children:s.jsx(X5e,{})})}),s.jsx(jn,{path:"/toolbox/:kitId",element:s.jsx(Un,{children:s.jsx(Q5e,{})})}),s.jsx(jn,{path:"/admin/toolbox",element:s.jsx(Un,{requireAdmin:!0,children:s.jsx(i9e,{})})}),s.jsx(jn,{path:"/social-swag",element:s.jsx(Un,{children:s.jsx(J5e,{})})}),s.jsx(jn,{path:"/social-swag/:swagId",element:s.jsx(Un,{children:s.jsx(e$e,{})})}),s.jsx(jn,{path:"/admin/social-swag",element:s.jsx(Un,{requireAdmin:!0,children:s.jsx(a9e,{})})}),s.jsx(jn,{path:"/community",element:s.jsx(Un,{children:s.jsx(p$e,{})})}),s.jsx(jn,{path:"/support",element:s.jsx(Un,{children:s.jsx(m$e,{})})}),s.jsx(jn,{path:"/admin/community",element:s.jsx(Un,{requireAdmin:!0,children:s.jsx(o9e,{})})}),s.jsx(jn,{path:"/admin/support-tickets",element:s.jsx(Un,{requireAdmin:!0,children:s.jsx(m9e,{})})}),s.jsx(jn,{path:"/admin/email-templates",element:s.jsx(Un,{requireAdmin:!0,children:s.jsx(x9e,{})})}),s.jsx(jn,{path:"/admin/analytics",element:s.jsx(Un,{requireAdmin:!0,children:s.jsx(h9e,{})})}),s.jsx(jn,{path:"/admin/brokerage-resources",element:s.jsx(Un,{requireAdmin:!0,children:s.jsx(f9e,{})})}),s.jsx(jn,{path:"/admin/dashboard-management",element:s.jsx(Un,{requireAdmin:!0,children:s.jsx(p9e,{})})}),s.jsx(jn,{path:"/brokerage/dashboard",element:s.jsx(Un,{requireBrokerageManager:!0,children:s.jsx(k9e,{})})}),s.jsx(jn,{path:"/brokerage-resources",element:s.jsx(Un,{requireBrokerageManager:!0,children:s.jsx(b$e,{})})}),s.jsx(jn,{path:"/brokerage-resources/:resourceId",element:s.jsx(Un,{requireBrokerageManager:!0,children:s.jsx(w$e,{})})}),s.jsx(jn,{path:"/newsletters",element:s.jsx(Un,{children:s.jsx(T9e,{})})}),s.jsx(jn,{path:"/newsletters/:id",element:s.jsx(Un,{children:s.jsx(E9e,{})})}),s.jsx(jn,{path:"/wishlist",element:s.jsx(Un,{children:s.jsx(P9e,{})})}),s.jsx(jn,{path:"/wishlist/:itemId",element:s.jsx(Un,{children:s.jsx(I9e,{})})}),s.jsx(jn,{path:"/admin/wishlist",element:s.jsx(Un,{requireAdmin:!0,children:s.jsx(M9e,{})})}),s.jsx(jn,{path:"/admin/levelup-brief",element:s.jsx(Un,{requireAdmin:!0,children:s.jsx(O9e,{})})}),s.jsx(jn,{path:"/admin/newsletters",element:s.jsx(Un,{requireAdmin:!0,children:s.jsx(A9e,{})})}),s.jsx(jn,{path:"/admin/additional-services",element:s.jsx(Un,{requireAdmin:!0,children:s.jsx(R9e,{})})}),s.jsx(jn,{path:"/admin/discounts",element:s.jsx(Un,{requireAdmin:!0,children:s.jsx(D9e,{})})}),s.jsx(jn,{path:"/admin/subscriptions",element:s.jsx(Un,{requireAdmin:!0,children:s.jsx(L9e,{})})}),s.jsx(jn,{path:"/admin/referrals",element:s.jsx(Un,{requireAdmin:!0,children:s.jsx(F9e,{})})}),s.jsx(jn,{path:"/admin/onboarding-checklist",element:s.jsx(Un,{requireAdmin:!0,children:s.jsx(B9e,{})})}),s.jsx(jn,{path:"/additional-services",element:s.jsx(Un,{children:s.jsx(Y9e,{})})}),s.jsx(jn,{path:"/additional-services/:serviceId",element:s.jsx(Un,{children:s.jsx(X9e,{})})}),s.jsx(jn,{path:"/ai-toolkit",element:s.jsx(Un,{children:s.jsx(Q9e,{})})}),s.jsx(jn,{path:"/innercircle",element:s.jsx(Un,{children:s.jsx(t7e,{})})}),s.jsx(jn,{path:"/innercircle/contacts",element:s.jsx(Un,{children:s.jsx(a7e,{})})}),s.jsx(jn,{path:"/innercircle/contacts/:contactId",element:s.jsx(Un,{children:s.jsx(N7e,{})})}),s.jsx(jn,{path:"/innercircle/plans",element:s.jsx(Un,{children:s.jsx(C7e,{})})}),s.jsx(jn,{path:"/innercircle/popbys",element:s.jsx(Un,{children:s.jsx(T7e,{})})}),s.jsx(jn,{path:"/innercircle/popbys/map",element:s.jsx(Un,{children:s.jsx(A7e,{})})}),s.jsx(jn,{path:"/admin/agent-os",element:s.jsx(Un,{requireAdmin:!0,children:s.jsx($9e,{})})}),s.jsx(jn,{path:"/innercircle/listings",element:s.jsx(Un,{children:s.jsx(Abt,{})})}),s.jsx(jn,{path:"/innercircle/listings/new",element:s.jsx(Un,{children:s.jsx(ese,{})})}),s.jsx(jn,{path:"/innercircle/listings/:listingId",element:s.jsx(Un,{children:s.jsx(Mbt,{})})}),s.jsx(jn,{path:"/innercircle/listings/:listingId/edit",element:s.jsx(Un,{children:s.jsx(ese,{})})}),s.jsx(jn,{path:"/admin/listing-exchange",element:s.jsx(Un,{requireAdmin:!0,children:s.jsx(Hbt,{})})}),s.jsx(jn,{path:"/innercircle/scorecard",element:s.jsx(Un,{children:s.jsx(wbt,{})})}),s.jsx(jn,{path:"/admin/scorecard",element:s.jsx(Un,{requireAdmin:!0,children:s.jsx(Ubt,{})})}),s.jsx(jn,{path:"/admin/scorecard/:userId",element:s.jsx(Un,{requireAdmin:!0,children:s.jsx(qbt,{})})}),s.jsx(jn,{path:"/admin/membership-reviews",element:s.jsx(Un,{requireAdmin:!0,children:s.jsx(Wbt,{})})}),s.jsx(jn,{path:"/admin/weekly-digest",element:s.jsx(Un,{requireAdmin:!0,children:s.jsx(Zbt,{})})}),s.jsx(jn,{path:"/innercircle/video/record",element:s.jsx(Un,{children:s.jsx(zbt,{})})}),s.jsx(jn,{path:"/innercircle/video-library",element:s.jsx(Un,{children:s.jsx(Bbt,{})})}),s.jsx(jn,{path:"*",element:s.jsx(Ybt,{})})]})})})]})})});Nae(document.getElementById("root")).render(s.jsx(Qbt,{}));